/*!
 * Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * 
 * Neither the name of Anaconda nor the names of any contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
(function(root, factory) {
  const bokeh = factory();
  bokeh.__bokeh__ = true;
  if (typeof root.Bokeh === "undefined" || typeof root.Bokeh.__bokeh__ === "undefined") {
    root.Bokeh = bokeh;
  }
  const Bokeh = root.Bokeh;
  Bokeh[bokeh.version] = bokeh;
})(this, function() {
  let define;
  const parent_require = typeof require === "function" && require
  return (function(modules, entry, aliases, externals) {
  if (aliases === undefined) aliases = {};
  if (externals === undefined) externals = {};

  const cache = {};

  const normalize = function(name) {
    if (typeof name === "number")
      return name;

    if (name === "bokehjs")
      return entry;

    if (!externals[name]) {
      const prefix = "@bokehjs/"
      if (name.slice(0, prefix.length) === prefix)
        name = name.slice(prefix.length)
    }

    const alias = aliases[name]
    if (alias != null)
      return alias;

    const trailing = name.length > 0 && name[name.lenght-1] === "/";
    const index = aliases[name + (trailing ? "" : "/") + "index"];
    if (index != null)
      return index;

    return name;
  }

  const require = function(name) {
    let mod = cache[name];
    if (!mod) {
      const id = normalize(name);

      mod = cache[id];
      if (!mod) {
        if (!modules[id]) {
          if (externals[id] === false || (externals[id] == true && parent_require)) {
            try {
              mod = {exports: externals[id] ? parent_require(id) : {}};
              cache[id] = cache[name] = mod;
              return mod.exports;
            } catch (e) {}
          }

          const err = new Error("Cannot find module '" + name + "'");
          err.code = 'MODULE_NOT_FOUND';
          throw err;
        }

        mod = {exports: {}};
        cache[id] = cache[name] = mod;

        function __esModule() {
          Object.defineProperty(mod.exports, "__esModule", {value: true});
        }

        function __esExport(name, value) {
          Object.defineProperty(mod.exports, name, {
            enumerable: true, get: function () { return value; }
          });
        }

        modules[id].call(mod.exports, require, mod, mod.exports, __esModule, __esExport);
      } else {
        cache[name] = mod;
      }
    }

    return mod.exports;
  }
  require.resolve = function(name) {
    return ""
  }

  const main = require(entry);
  main.require = require;

  if (typeof Proxy !== "undefined") {
    // allow Bokeh.loader["@bokehjs/module/name"] syntax
    main.loader = new Proxy({}, {
      get: function(_obj, module) {
        return require(module);
      }
    });
  }

  main.register_plugin = function(plugin_modules, plugin_entry, plugin_aliases, plugin_externals) {
    if (plugin_aliases === undefined) plugin_aliases = {};
    if (plugin_externals === undefined) plugin_externals = {};

    for (let name in plugin_modules) {
      modules[name] = plugin_modules[name];
    }

    for (let name in plugin_aliases) {
      aliases[name] = plugin_aliases[name];
    }

    for (let name in plugin_externals) {
      externals[name] = plugin_externals[name];
    }

    const plugin = require(plugin_entry);

    for (let name in plugin) {
      main[name] = plugin[name];
    }

    return plugin;
  }

  return main;
})
([
/* legacy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    require(2) /* ./polyfill */;
    (0, tslib_1.__exportStar)(require(118) /* ./main */, exports);
},
/* tslib/tslib.es6.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) {
                for (var p in b)
                    if (Object.prototype.hasOwnProperty.call(b, p))
                        d[p] = b[p];
            };
        return extendStatics(d, b);
    };
    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    exports.__extends = __extends;
    var __assign = function () {
        exports.__assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s)
                    if (Object.prototype.hasOwnProperty.call(s, p))
                        t[p] = s[p];
            }
            return t;
        };
        return exports.__assign.apply(this, arguments);
    };
    exports.__assign = __assign;
    function __rest(s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }
    exports.__rest = __rest;
    function __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }
    exports.__decorate = __decorate;
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    exports.__param = __param;
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    exports.__metadata = __metadata;
    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) {
                try {
                    step(generator.next(value));
                }
                catch (e) {
                    reject(e);
                }
            }
            function rejected(value) {
                try {
                    step(generator["throw"](value));
                }
                catch (e) {
                    reject(e);
                }
            }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }
    exports.__awaiter = __awaiter;
    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function () {
                if (t[0] & 1)
                    throw t[1];
                return t[1];
            }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f)
                throw new TypeError("Generator is already executing.");
            while (_)
                try {
                    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
                        return t;
                    if (y = 0, t)
                        op = [op[0] & 2, t.value];
                    switch (op[0]) {
                        case 0:
                        case 1:
                            t = op;
                            break;
                        case 4:
                            _.label++;
                            return { value: op[1], done: false };
                        case 5:
                            _.label++;
                            y = op[1];
                            op = [0];
                            continue;
                        case 7:
                            op = _.ops.pop();
                            _.trys.pop();
                            continue;
                        default:
                            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                                _ = 0;
                                continue;
                            }
                            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                                _.label = op[1];
                                break;
                            }
                            if (op[0] === 6 && _.label < t[1]) {
                                _.label = t[1];
                                t = op;
                                break;
                            }
                            if (t && _.label < t[2]) {
                                _.label = t[2];
                                _.ops.push(op);
                                break;
                            }
                            if (t[2])
                                _.ops.pop();
                            _.trys.pop();
                            continue;
                    }
                    op = body.call(thisArg, _);
                }
                catch (e) {
                    op = [6, e];
                    y = 0;
                }
                finally {
                    f = t = 0;
                }
            if (op[0] & 5)
                throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
        }
    }
    exports.__generator = __generator;
    exports.__createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                (0, exports.__createBinding)(o, m, p);
    }
    exports.__exportStar = __exportStar;
    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m)
            return m.call(o);
        if (o && typeof o.length === "number")
            return {
                next: function () {
                    if (o && i >= o.length)
                        o = void 0;
                    return { value: o && o[i++], done: !o };
                }
            };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    exports.__values = __values;
    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m)
            return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
                ar.push(r.value);
        }
        catch (error) {
            e = { error: error };
        }
        finally {
            try {
                if (r && !r.done && (m = i["return"]))
                    m.call(i);
            }
            finally {
                if (e)
                    throw e.error;
            }
        }
        return ar;
    }
    exports.__read = __read;
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    exports.__spread = __spread;
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    exports.__spreadArrays = __spreadArrays;
    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2)
            for (var i = 0, l = from.length, ar; i < l; i++) {
                if (ar || !(i in from)) {
                    if (!ar)
                        ar = Array.prototype.slice.call(from, 0, i);
                    ar[i] = from[i];
                }
            }
        return to.concat(ar || Array.prototype.slice.call(from));
    }
    exports.__spreadArray = __spreadArray;
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    exports.__await = __await;
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) {
            if (g[n])
                i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); };
        }
        function resume(n, v) {
            try {
                step(g[n](v));
            }
            catch (e) {
                settle(q[0][3], e);
            }
        }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) {
            if (f(v), q.shift(), q.length)
                resume(q[0][0], q[0][1]);
        }
    }
    exports.__asyncGenerator = __asyncGenerator;
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
    }
    exports.__asyncDelegator = __asyncDelegator;
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    exports.__asyncValues = __asyncValues;
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    exports.__makeTemplateObject = __makeTemplateObject;
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    (0, exports.__createBinding)(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    }
    exports.__importStar = __importStar;
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    exports.__importDefault = __importDefault;
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    exports.__classPrivateFieldGet = __classPrivateFieldGet;
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }
    exports.__classPrivateFieldSet = __classPrivateFieldSet;
},
/* polyfill.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    require(3) /* es5-ext/object/assign/implement */;
    require(12) /* es5-ext/object/entries/implement */;
    require(15) /* es5-ext/number/is-integer/implement */;
    require(18) /* es5-ext/string/#/repeat/implement */;
    require(25) /* es5-ext/array/from/implement */;
    require(55) /* es5-ext/array/#/fill/implement */;
    require(58) /* es5-ext/math/log10/implement */;
    require(61) /* es5-ext/math/log1p/implement */;
    require(64) /* es6-set/implement */;
    require(100) /* es6-map/implement */;
    require(107) /* es6-weak-map/implement */;
    require(113) /* es6-symbol/implement */;
    require(114) /* es6-promise/auto */;
    if (typeof Object.is === "undefined") {
        Object.is = function (a, b) {
            if (a === b)
                return a !== 0 || 1 / a === 1 / b;
            else
                return a !== a && b !== b;
        };
    }
    if (typeof Object.values === "undefined") {
        Object.values = function (obj) {
            return Object.keys(obj).map(function (key) { return obj[key]; });
        };
    }
    if (typeof String.prototype.includes === "undefined") {
        String.prototype.includes = function (search, start) {
            if (start === void 0) {
                start = 0;
            }
            return this.indexOf(search, start) != -1;
        };
    }
    if (typeof Uint8Array.prototype.fill === "undefined") {
        var fill = Array.prototype.fill;
        Uint8Array.prototype.fill = fill;
        Int8Array.prototype.fill = fill;
        Uint16Array.prototype.fill = fill;
        Int16Array.prototype.fill = fill;
        Uint32Array.prototype.fill = fill;
        Int32Array.prototype.fill = fill;
        Float32Array.prototype.fill = fill;
        Float64Array.prototype.fill = fill;
    }
    var arrayable_1 = require(116) /* ./core/util/arrayable */;
    if (typeof Uint8Array.from === "undefined") {
        function from(ctor) {
            var that = this;
            return function (arrayLike, mapfn, thisArg) {
                var arr = new ctor((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arrayLike), false));
                if (mapfn != null)
                    (0, arrayable_1.inplace_map)(arr, function (v, k) { return mapfn.call(thisArg !== null && thisArg !== void 0 ? thisArg : that, v, k); });
                return arr;
            };
        }
        Uint8Array.from = from(Uint8Array);
        Int8Array.from = from(Int8Array);
        Uint16Array.from = from(Uint16Array);
        Int16Array.from = from(Int16Array);
        Uint32Array.from = from(Uint32Array);
        Int32Array.from = from(Int32Array);
        Float32Array.from = from(Float32Array);
        Float64Array.from = from(Float64Array);
    }
    if (typeof Array.prototype[Symbol.iterator] === "undefined") {
        function iterator() {
            var i = 0;
            var self = this;
            return {
                next: function () {
                    var done = self.length <= i;
                    var value = done ? undefined : self[i++];
                    return { value: value, done: done };
                },
            };
        }
        (function () {
            arguments.constructor.prototype[Symbol.iterator] = iterator;
            Array.prototype[Symbol.iterator] = iterator;
            Uint8Array.prototype[Symbol.iterator] = iterator;
            Int8Array.prototype[Symbol.iterator] = iterator;
            Uint16Array.prototype[Symbol.iterator] = iterator;
            Int16Array.prototype[Symbol.iterator] = iterator;
            Uint32Array.prototype[Symbol.iterator] = iterator;
            Int32Array.prototype[Symbol.iterator] = iterator;
            Float32Array.prototype[Symbol.iterator] = iterator;
            Float64Array.prototype[Symbol.iterator] = iterator;
        })();
    }
    // fixes up a problem with some versions of IE11
    // ref: http://stackoverflow.com/questions/22062313/imagedata-set-in-internetexplorer
    if (typeof CanvasPixelArray !== "undefined") {
        CanvasPixelArray.prototype.set = function (arr) {
            for (var i = 0; i < this.length; i++) {
                this[i] = arr[i];
            }
        };
    }
},
/* es5-ext/object/assign/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(4) /* ./is-implemented */()) {
        Object.defineProperty(Object, "assign", {
            value: require(5) /* ./shim */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es5-ext/object/assign/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var assign = Object.assign, obj;
        if (typeof assign !== "function")
            return false;
        obj = { foo: "raz" };
        assign(obj, { bar: "dwa" }, { trzy: "trzy" });
        return obj.foo + obj.bar + obj.trzy === "razdwatrzy";
    };
},
/* es5-ext/object/assign/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var keys = require(6) /* ../keys */, value = require(11) /* ../valid-value */, max = Math.max;
    module.exports = function (dest, src /*, …srcn*/) {
        var error, i, length = max(arguments.length, 2), assign;
        dest = Object(value(dest));
        assign = function (key) {
            try {
                dest[key] = src[key];
            }
            catch (e) {
                if (!error)
                    error = e;
            }
        };
        for (i = 1; i < length; ++i) {
            src = arguments[i];
            keys(src).forEach(assign);
        }
        if (error !== undefined)
            throw error;
        return dest;
    };
},
/* es5-ext/object/keys/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(7) /* ./is-implemented */() ? Object.keys : require(8) /* ./shim */;
},
/* es5-ext/object/keys/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        try {
            Object.keys("primitive");
            return true;
        }
        catch (e) {
            return false;
        }
    };
},
/* es5-ext/object/keys/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(9) /* ../is-value */;
    var keys = Object.keys;
    module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); };
},
/* es5-ext/object/is-value.js */ function _(require, module, exports, __esModule, __esExport) {
    var _undefined = require(10) /* ../function/noop */(); // Support ES3 engines
    module.exports = function (val) { return val !== _undefined && val !== null; };
},
/* es5-ext/function/noop.js */ function _(require, module, exports, __esModule, __esExport) {
    // eslint-disable-next-line no-empty-function
    module.exports = function () { };
},
/* es5-ext/object/valid-value.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(9) /* ./is-value */;
    module.exports = function (value) {
        if (!isValue(value))
            throw new TypeError("Cannot use null or undefined");
        return value;
    };
},
/* es5-ext/object/entries/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(13) /* ./is-implemented */()) {
        Object.defineProperty(Object, "entries", {
            value: require(14) /* ./shim */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es5-ext/object/entries/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        try {
            return Object.entries({ foo: 12 })[0][0] === "foo";
        }
        catch (e) {
            return false;
        }
    };
},
/* es5-ext/object/entries/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var ensureValue = require(11) /* ../valid-value */;
    module.exports = function (object) {
        ensureValue(object);
        var result = [];
        object = Object(object);
        for (var key in object) {
            if (!propertyIsEnumerable.call(object, key))
                continue;
            result.push([key, object[key]]);
        }
        return result;
    };
},
/* es5-ext/number/is-integer/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(16) /* ./is-implemented */()) {
        Object.defineProperty(Number, "isInteger", {
            value: require(17) /* ./shim */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es5-ext/number/is-integer/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var isInteger = Number.isInteger;
        if (typeof isInteger !== "function")
            return false;
        return !isInteger("23") && isInteger(34) && !isInteger(32.34);
    };
},
/* es5-ext/number/is-integer/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function (value) {
        if (typeof value !== "number")
            return false;
        return value % 1 === 0;
    };
},
/* es5-ext/string/#/repeat/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(19) /* ./is-implemented */()) {
        Object.defineProperty(String.prototype, "repeat", {
            value: require(20) /* ./shim */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es5-ext/string/#/repeat/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    var str = "foo";
    module.exports = function () {
        if (typeof str.repeat !== "function")
            return false;
        return str.repeat(2) === "foofoo";
    };
},
/* es5-ext/string/#/repeat/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var value = require(11) /* ../../../object/valid-value */, toInteger = require(21) /* ../../../number/to-integer */;
    module.exports = function (count) {
        var str = String(value(this)), result;
        count = toInteger(count);
        if (count < 0)
            throw new RangeError("Count must be >= 0");
        if (!isFinite(count))
            throw new RangeError("Count must be < ∞");
        result = "";
        while (count) {
            if (count % 2)
                result += str;
            if (count > 1)
                str += str;
            // eslint-disable-next-line no-bitwise
            count >>= 1;
        }
        return result;
    };
},
/* es5-ext/number/to-integer.js */ function _(require, module, exports, __esModule, __esExport) {
    var sign = require(22) /* ../math/sign */, abs = Math.abs, floor = Math.floor;
    module.exports = function (value) {
        if (isNaN(value))
            return 0;
        value = Number(value);
        if (value === 0 || !isFinite(value))
            return value;
        return sign(value) * floor(abs(value));
    };
},
/* es5-ext/math/sign/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(23) /* ./is-implemented */() ? Math.sign : require(24) /* ./shim */;
},
/* es5-ext/math/sign/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var sign = Math.sign;
        if (typeof sign !== "function")
            return false;
        return sign(10) === 1 && sign(-20) === -1;
    };
},
/* es5-ext/math/sign/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function (value) {
        value = Number(value);
        if (isNaN(value) || value === 0)
            return value;
        return value > 0 ? 1 : -1;
    };
},
/* es5-ext/array/from/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(26) /* ./is-implemented */()) {
        Object.defineProperty(Array, "from", {
            value: require(27) /* ./shim */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es5-ext/array/from/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var from = Array.from, arr, result;
        if (typeof from !== "function")
            return false;
        arr = ["raz", "dwa"];
        result = from(arr);
        return Boolean(result && result !== arr && result[1] === "dwa");
    };
},
/* es5-ext/array/from/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var iteratorSymbol = require(28) /* es6-symbol */.iterator, isArguments = require(50) /* ../../function/is-arguments */, isFunction = require(51) /* ../../function/is-function */, toPosInt = require(52) /* ../../number/to-pos-integer */, callable = require(53) /* ../../object/valid-callable */, validValue = require(11) /* ../../object/valid-value */, isValue = require(9) /* ../../object/is-value */, isString = require(54) /* ../../string/is-string */, isArray = Array.isArray, call = Function.prototype.call, desc = { configurable: true, enumerable: true, writable: true, value: null }, defineProperty = Object.defineProperty;
    // eslint-disable-next-line complexity, max-lines-per-function
    module.exports = function (arrayLike /*, mapFn, thisArg*/) {
        var mapFn = arguments[1], thisArg = arguments[2], Context, i, j, arr, length, code, iterator, result, getIterator, value;
        arrayLike = Object(validValue(arrayLike));
        if (isValue(mapFn))
            callable(mapFn);
        if (!this || this === Array || !isFunction(this)) {
            // Result: Plain array
            if (!mapFn) {
                if (isArguments(arrayLike)) {
                    // Source: Arguments
                    length = arrayLike.length;
                    if (length !== 1)
                        return Array.apply(null, arrayLike);
                    arr = new Array(1);
                    arr[0] = arrayLike[0];
                    return arr;
                }
                if (isArray(arrayLike)) {
                    // Source: Array
                    arr = new Array((length = arrayLike.length));
                    for (i = 0; i < length; ++i)
                        arr[i] = arrayLike[i];
                    return arr;
                }
            }
            arr = [];
        }
        else {
            // Result: Non plain array
            Context = this;
        }
        if (!isArray(arrayLike)) {
            if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
                // Source: Iterator
                iterator = callable(getIterator).call(arrayLike);
                if (Context)
                    arr = new Context();
                result = iterator.next();
                i = 0;
                while (!result.done) {
                    value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
                    if (Context) {
                        desc.value = value;
                        defineProperty(arr, i, desc);
                    }
                    else {
                        arr[i] = value;
                    }
                    result = iterator.next();
                    ++i;
                }
                length = i;
            }
            else if (isString(arrayLike)) {
                // Source: String
                length = arrayLike.length;
                if (Context)
                    arr = new Context();
                for (i = 0, j = 0; i < length; ++i) {
                    value = arrayLike[i];
                    if (i + 1 < length) {
                        code = value.charCodeAt(0);
                        // eslint-disable-next-line max-depth
                        if (code >= 0xd800 && code <= 0xdbff)
                            value += arrayLike[++i];
                    }
                    value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
                    if (Context) {
                        desc.value = value;
                        defineProperty(arr, j, desc);
                    }
                    else {
                        arr[j] = value;
                    }
                    ++j;
                }
                length = j;
            }
        }
        if (length === undefined) {
            // Source: array or array-like
            length = toPosInt(arrayLike.length);
            if (Context)
                arr = new Context(length);
            for (i = 0; i < length; ++i) {
                value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
                if (Context) {
                    desc.value = value;
                    defineProperty(arr, i, desc);
                }
                else {
                    arr[i] = value;
                }
            }
        }
        if (Context) {
            desc.value = null;
            arr.length = length;
        }
        return arr;
    };
},
/* es6-symbol/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(29) /* ./is-implemented */()
        ? require(30) /* ext/global-this */.Symbol
        : require(33) /* ./polyfill */;
},
/* es6-symbol/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    var global = require(30) /* ext/global-this */, validTypes = { object: true, symbol: true };
    module.exports = function () {
        var Symbol = global.Symbol;
        var symbol;
        if (typeof Symbol !== "function")
            return false;
        symbol = Symbol("test symbol");
        try {
            String(symbol);
        }
        catch (e) {
            return false;
        }
        // Return 'true' also for polyfills
        if (!validTypes[typeof Symbol.iterator])
            return false;
        if (!validTypes[typeof Symbol.toPrimitive])
            return false;
        if (!validTypes[typeof Symbol.toStringTag])
            return false;
        return true;
    };
},
/* ext/global-this/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(31) /* ./is-implemented */() ? globalThis : require(32) /* ./implementation */;
},
/* ext/global-this/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        if (typeof globalThis !== "object")
            return false;
        if (!globalThis)
            return false;
        return globalThis.Array === Array;
    };
},
/* ext/global-this/implementation.js */ function _(require, module, exports, __esModule, __esExport) {
    var naiveFallback = function () {
        if (typeof self === "object" && self)
            return self;
        if (typeof window === "object" && window)
            return window;
        throw new Error("Unable to resolve global `this`");
    };
    module.exports = (function () {
        if (this)
            return this;
        // Unexpected strict mode (may happen if e.g. bundled into ESM module)
        // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
        // In all ES5+ engines global object inherits from Object.prototype
        // (if you approached one that doesn't please report)
        try {
            Object.defineProperty(Object.prototype, "__global__", {
                get: function () { return this; },
                configurable: true
            });
        }
        catch (error) {
            // Unfortunate case of Object.prototype being sealed (via preventExtensions, seal or freeze)
            return naiveFallback();
        }
        try {
            // Safari case (window.__global__ is resolved with global context, but __global__ does not)
            if (!__global__)
                return naiveFallback();
            return __global__;
        }
        finally {
            delete Object.prototype.__global__;
        }
    })();
},
/* es6-symbol/polyfill.js */ function _(require, module, exports, __esModule, __esExport) {
    var d = require(34) /* d */, validateSymbol = require(45) /* ./validate-symbol */, NativeSymbol = require(30) /* ext/global-this */.Symbol, generateName = require(47) /* ./lib/private/generate-name */, setupStandardSymbols = require(48) /* ./lib/private/setup/standard-symbols */, setupSymbolRegistry = require(49) /* ./lib/private/setup/symbol-registry */;
    var create = Object.create, defineProperties = Object.defineProperties, defineProperty = Object.defineProperty;
    var SymbolPolyfill, HiddenSymbol, isNativeSafe;
    if (typeof NativeSymbol === "function") {
        try {
            String(NativeSymbol());
            isNativeSafe = true;
        }
        catch (ignore) { }
    }
    else {
        NativeSymbol = null;
    }
    // Internal constructor (not one exposed) for creating Symbol instances.
    // This one is used to ensure that `someSymbol instanceof Symbol` always return false
    HiddenSymbol = function Symbol(description) {
        if (this instanceof HiddenSymbol)
            throw new TypeError("Symbol is not a constructor");
        return SymbolPolyfill(description);
    };
    // Exposed `Symbol` constructor
    // (returns instances of HiddenSymbol)
    module.exports = SymbolPolyfill = function Symbol(description) {
        var symbol;
        if (this instanceof Symbol)
            throw new TypeError("Symbol is not a constructor");
        if (isNativeSafe)
            return NativeSymbol(description);
        symbol = create(HiddenSymbol.prototype);
        description = description === undefined ? "" : String(description);
        return defineProperties(symbol, {
            __description__: d("", description),
            __name__: d("", generateName(description))
        });
    };
    setupStandardSymbols(SymbolPolyfill);
    setupSymbolRegistry(SymbolPolyfill);
    // Internal tweaks for real symbol producer
    defineProperties(HiddenSymbol.prototype, {
        constructor: d(SymbolPolyfill),
        toString: d("", function () { return this.__name__; })
    });
    // Proper implementation of methods exposed on Symbol.prototype
    // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
    defineProperties(SymbolPolyfill.prototype, {
        toString: d(function () { return "Symbol (" + validateSymbol(this).__description__ + ")"; }),
        valueOf: d(function () { return validateSymbol(this); })
    });
    defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d("", function () {
        var symbol = validateSymbol(this);
        if (typeof symbol === "symbol")
            return symbol;
        return symbol.toString();
    }));
    defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d("c", "Symbol"));
    // Proper implementaton of toPrimitive and toStringTag for returned symbol instances
    defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag, d("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));
    // Note: It's important to define `toPrimitive` as last one, as some implementations
    // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
    // And that may invoke error in definition flow:
    // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
    defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, d("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));
},
/* d/index.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(35) /* type/value/is */, isPlainFunction = require(36) /* type/plain-function/is */, assign = require(40) /* es5-ext/object/assign */, normalizeOpts = require(41) /* es5-ext/object/normalize-options */, contains = require(42) /* es5-ext/string/#/contains */;
    var d = (module.exports = function (dscr, value /*, options*/) {
        var c, e, w, options, desc;
        if (arguments.length < 2 || typeof dscr !== "string") {
            options = value;
            value = dscr;
            dscr = null;
        }
        else {
            options = arguments[2];
        }
        if (isValue(dscr)) {
            c = contains.call(dscr, "c");
            e = contains.call(dscr, "e");
            w = contains.call(dscr, "w");
        }
        else {
            c = w = true;
            e = false;
        }
        desc = { value: value, configurable: c, enumerable: e, writable: w };
        return !options ? desc : assign(normalizeOpts(options), desc);
    });
    d.gs = function (dscr, get, set /*, options*/) {
        var c, e, options, desc;
        if (typeof dscr !== "string") {
            options = set;
            set = get;
            get = dscr;
            dscr = null;
        }
        else {
            options = arguments[3];
        }
        if (!isValue(get)) {
            get = undefined;
        }
        else if (!isPlainFunction(get)) {
            options = get;
            get = set = undefined;
        }
        else if (!isValue(set)) {
            set = undefined;
        }
        else if (!isPlainFunction(set)) {
            options = set;
            set = undefined;
        }
        if (isValue(dscr)) {
            c = contains.call(dscr, "c");
            e = contains.call(dscr, "e");
        }
        else {
            c = true;
            e = false;
        }
        desc = { get: get, set: set, configurable: c, enumerable: e };
        return !options ? desc : assign(normalizeOpts(options), desc);
    };
},
/* type/value/is.js */ function _(require, module, exports, __esModule, __esExport) {
    // ES3 safe
    var _undefined = void 0;
    module.exports = function (value) { return value !== _undefined && value !== null; };
},
/* type/plain-function/is.js */ function _(require, module, exports, __esModule, __esExport) {
    var isFunction = require(37) /* ../function/is */;
    var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString;
    module.exports = function (value) {
        if (!isFunction(value))
            return false;
        if (classRe.test(functionToString.call(value)))
            return false;
        return true;
    };
},
/* type/function/is.js */ function _(require, module, exports, __esModule, __esExport) {
    var isPrototype = require(38) /* ../prototype/is */;
    module.exports = function (value) {
        if (typeof value !== "function")
            return false;
        if (!hasOwnProperty.call(value, "length"))
            return false;
        try {
            if (typeof value.length !== "number")
                return false;
            if (typeof value.call !== "function")
                return false;
            if (typeof value.apply !== "function")
                return false;
        }
        catch (error) {
            return false;
        }
        return !isPrototype(value);
    };
},
/* type/prototype/is.js */ function _(require, module, exports, __esModule, __esExport) {
    var isObject = require(39) /* ../object/is */;
    module.exports = function (value) {
        if (!isObject(value))
            return false;
        try {
            if (!value.constructor)
                return false;
            return value.constructor.prototype === value;
        }
        catch (error) {
            return false;
        }
    };
},
/* type/object/is.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(35) /* ../value/is */;
    // prettier-ignore
    var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ };
    module.exports = function (value) {
        if (!isValue(value))
            return false;
        return hasOwnProperty.call(possibleTypes, typeof value);
    };
},
/* es5-ext/object/assign/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(4) /* ./is-implemented */() ? Object.assign : require(5) /* ./shim */;
},
/* es5-ext/object/normalize-options.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(9) /* ./is-value */;
    var forEach = Array.prototype.forEach, create = Object.create;
    var process = function (src, obj) {
        var key;
        for (key in src)
            obj[key] = src[key];
    };
    // eslint-disable-next-line no-unused-vars
    module.exports = function (opts1 /*, …options*/) {
        var result = create(null);
        forEach.call(arguments, function (options) {
            if (!isValue(options))
                return;
            process(Object(options), result);
        });
        return result;
    };
},
/* es5-ext/string/#/contains/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(43) /* ./is-implemented */() ? String.prototype.contains : require(44) /* ./shim */;
},
/* es5-ext/string/#/contains/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    var str = "razdwatrzy";
    module.exports = function () {
        if (typeof str.contains !== "function")
            return false;
        return str.contains("dwa") === true && str.contains("foo") === false;
    };
},
/* es5-ext/string/#/contains/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var indexOf = String.prototype.indexOf;
    module.exports = function (searchString /*, position*/) {
        return indexOf.call(this, searchString, arguments[1]) > -1;
    };
},
/* es6-symbol/validate-symbol.js */ function _(require, module, exports, __esModule, __esExport) {
    var isSymbol = require(46) /* ./is-symbol */;
    module.exports = function (value) {
        if (!isSymbol(value))
            throw new TypeError(value + " is not a symbol");
        return value;
    };
},
/* es6-symbol/is-symbol.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function (value) {
        if (!value)
            return false;
        if (typeof value === "symbol")
            return true;
        if (!value.constructor)
            return false;
        if (value.constructor.name !== "Symbol")
            return false;
        return value[value.constructor.toStringTag] === "Symbol";
    };
},
/* es6-symbol/lib/private/generate-name.js */ function _(require, module, exports, __esModule, __esExport) {
    var d = require(34) /* d */;
    var create = Object.create, defineProperty = Object.defineProperty, objPrototype = Object.prototype;
    var created = create(null);
    module.exports = function (desc) {
        var postfix = 0, name, ie11BugWorkaround;
        while (created[desc + (postfix || "")])
            ++postfix;
        desc += postfix || "";
        created[desc] = true;
        name = "@@" + desc;
        defineProperty(objPrototype, name, d.gs(null, function (value) {
            // For IE11 issue see:
            // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
            //    ie11-broken-getters-on-dom-objects
            // https://github.com/medikoo/es6-symbol/issues/12
            if (ie11BugWorkaround)
                return;
            ie11BugWorkaround = true;
            defineProperty(this, name, d(value));
            ie11BugWorkaround = false;
        }));
        return name;
    };
},
/* es6-symbol/lib/private/setup/standard-symbols.js */ function _(require, module, exports, __esModule, __esExport) {
    var d = require(34) /* d */, NativeSymbol = require(30) /* ext/global-this */.Symbol;
    module.exports = function (SymbolPolyfill) {
        return Object.defineProperties(SymbolPolyfill, {
            // To ensure proper interoperability with other native functions (e.g. Array.from)
            // fallback to eventual native implementation of given symbol
            hasInstance: d("", (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill("hasInstance")),
            isConcatSpreadable: d("", (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
                SymbolPolyfill("isConcatSpreadable")),
            iterator: d("", (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill("iterator")),
            match: d("", (NativeSymbol && NativeSymbol.match) || SymbolPolyfill("match")),
            replace: d("", (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill("replace")),
            search: d("", (NativeSymbol && NativeSymbol.search) || SymbolPolyfill("search")),
            species: d("", (NativeSymbol && NativeSymbol.species) || SymbolPolyfill("species")),
            split: d("", (NativeSymbol && NativeSymbol.split) || SymbolPolyfill("split")),
            toPrimitive: d("", (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill("toPrimitive")),
            toStringTag: d("", (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill("toStringTag")),
            unscopables: d("", (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill("unscopables"))
        });
    };
},
/* es6-symbol/lib/private/setup/symbol-registry.js */ function _(require, module, exports, __esModule, __esExport) {
    var d = require(34) /* d */, validateSymbol = require(45) /* ../../../validate-symbol */;
    var registry = Object.create(null);
    module.exports = function (SymbolPolyfill) {
        return Object.defineProperties(SymbolPolyfill, {
            for: d(function (key) {
                if (registry[key])
                    return registry[key];
                return (registry[key] = SymbolPolyfill(String(key)));
            }),
            keyFor: d(function (symbol) {
                var key;
                validateSymbol(symbol);
                for (key in registry) {
                    if (registry[key] === symbol)
                        return key;
                }
                return undefined;
            })
        });
    };
},
/* es5-ext/function/is-arguments.js */ function _(require, module, exports, __esModule, __esExport) {
    var objToString = Object.prototype.toString, id = objToString.call((function () { return arguments; })());
    module.exports = function (value) { return objToString.call(value) === id; };
},
/* es5-ext/function/is-function.js */ function _(require, module, exports, __esModule, __esExport) {
    var objToString = Object.prototype.toString, isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/);
    module.exports = function (value) {
        return typeof value === "function" && isFunctionStringTag(objToString.call(value));
    };
},
/* es5-ext/number/to-pos-integer.js */ function _(require, module, exports, __esModule, __esExport) {
    var toInteger = require(21) /* ./to-integer */, max = Math.max;
    module.exports = function (value) { return max(0, toInteger(value)); };
},
/* es5-ext/object/valid-callable.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function (fn) {
        if (typeof fn !== "function")
            throw new TypeError(fn + " is not a function");
        return fn;
    };
},
/* es5-ext/string/is-string.js */ function _(require, module, exports, __esModule, __esExport) {
    var objToString = Object.prototype.toString, id = objToString.call("");
    module.exports = function (value) {
        return (typeof value === "string" ||
            (value &&
                typeof value === "object" &&
                (value instanceof String || objToString.call(value) === id)) ||
            false);
    };
},
/* es5-ext/array/#/fill/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(56) /* ./is-implemented */()) {
        Object.defineProperty(Array.prototype, "fill", {
            value: require(57) /* ./shim */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es5-ext/array/#/fill/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var arr = [1, 2, 3, 4, 5, 6];
        if (typeof arr.fill !== "function")
            return false;
        return String(arr.fill(-1, -3)) === "1,2,3,-1,-1,-1";
    };
},
/* es5-ext/array/#/fill/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var toInteger = require(21) /* ../../../number/to-integer */, toPosInt = require(52) /* ../../../number/to-pos-integer */, validValue = require(11) /* ../../../object/valid-value */, max = Math.max, min = Math.min;
    module.exports = function (value /*, start, end*/) {
        var arr = validValue(this), start = arguments[1], end = arguments[2], length = toPosInt(arr.length), relativeStart, i;
        start = start === undefined ? 0 : toInteger(start);
        end = end === undefined ? length : toInteger(end);
        relativeStart = start < 0 ? max(length + start, 0) : min(start, length);
        for (i = relativeStart; i < length && i < end; ++i)
            arr[i] = value;
        return arr;
    };
},
/* es5-ext/math/log10/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(59) /* ./is-implemented */()) {
        Object.defineProperty(Math, "log10", {
            value: require(60) /* ./shim */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es5-ext/math/log10/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var log10 = Math.log10;
        if (typeof log10 !== "function")
            return false;
        return log10(2) === 0.3010299956639812;
    };
},
/* es5-ext/math/log10/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var log = Math.log, LOG10E = Math.LOG10E;
    module.exports = function (value) {
        if (isNaN(value))
            return NaN;
        value = Number(value);
        if (value < 0)
            return NaN;
        if (value === 0)
            return -Infinity;
        if (value === 1)
            return 0;
        if (value === Infinity)
            return Infinity;
        return log(value) * LOG10E;
    };
},
/* es5-ext/math/log1p/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(62) /* ./is-implemented */()) {
        Object.defineProperty(Math, "log1p", {
            value: require(63) /* ./shim */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es5-ext/math/log1p/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var log1p = Math.log1p;
        if (typeof log1p !== "function")
            return false;
        return log1p(1) === 0.6931471805599453;
    };
},
/* es5-ext/math/log1p/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var log = Math.log;
    module.exports = function (value) {
        if (isNaN(value))
            return NaN;
        value = Number(value);
        if (value < -1)
            return NaN;
        if (value === -1)
            return -Infinity;
        if (value === 0)
            return value;
        if (value === Infinity)
            return Infinity;
        if (value > -1.0e-8 && value < 1.0e-8)
            return value - (value * value) / 2;
        return log(1 + value);
    };
},
/* es6-set/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(65) /* ./is-implemented */()) {
        Object.defineProperty(require(66) /* es5-ext/global */, 'Set', { value: require(67) /* ./polyfill */, configurable: true, enumerable: false,
            writable: true });
    }
},
/* es6-set/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var set, iterator, result;
        if (typeof Set !== 'function')
            return false;
        set = new Set(['raz', 'dwa', 'trzy']);
        if (String(set) !== '[object Set]')
            return false;
        if (set.size !== 3)
            return false;
        if (typeof set.add !== 'function')
            return false;
        if (typeof set.clear !== 'function')
            return false;
        if (typeof set.delete !== 'function')
            return false;
        if (typeof set.entries !== 'function')
            return false;
        if (typeof set.forEach !== 'function')
            return false;
        if (typeof set.has !== 'function')
            return false;
        if (typeof set.keys !== 'function')
            return false;
        if (typeof set.values !== 'function')
            return false;
        iterator = set.values();
        result = iterator.next();
        if (result.done !== false)
            return false;
        if (result.value !== 'raz')
            return false;
        return true;
    };
},
/* es5-ext/global.js */ function _(require, module, exports, __esModule, __esExport) {
    var naiveFallback = function () {
        if (typeof self === "object" && self)
            return self;
        if (typeof window === "object" && window)
            return window;
        throw new Error("Unable to resolve global `this`");
    };
    module.exports = (function () {
        if (this)
            return this;
        // Unexpected strict mode (may happen if e.g. bundled into ESM module)
        // Fallback to standard globalThis if available
        if (typeof globalThis === "object" && globalThis)
            return globalThis;
        // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
        // In all ES5+ engines global object inherits from Object.prototype
        // (if you approached one that doesn't please report)
        try {
            Object.defineProperty(Object.prototype, "__global__", {
                get: function () { return this; },
                configurable: true
            });
        }
        catch (error) {
            // Unfortunate case of updates to Object.prototype being restricted
            // via preventExtensions, seal or freeze
            return naiveFallback();
        }
        try {
            // Safari case (window.__global__ works, but __global__ does not)
            if (!__global__)
                return naiveFallback();
            return __global__;
        }
        finally {
            delete Object.prototype.__global__;
        }
    })();
},
/* es6-set/polyfill.js */ function _(require, module, exports, __esModule, __esExport) {
    var clear = require(68) /* es5-ext/array/#/clear */, eIndexOf = require(69) /* es5-ext/array/#/e-index-of */, setPrototypeOf = require(73) /* es5-ext/object/set-prototype-of */, callable = require(53) /* es5-ext/object/valid-callable */, d = require(34) /* d */, ee = require(78) /* event-emitter */, Symbol = require(28) /* es6-symbol */, iterator = require(79) /* es6-iterator/valid-iterable */, forOf = require(81) /* es6-iterator/for-of */, Iterator = require(98) /* ./lib/iterator */, isNative = require(99) /* ./is-native-implemented */, call = Function.prototype.call, defineProperty = Object.defineProperty, getPrototypeOf = Object.getPrototypeOf, SetPoly, getValues, NativeSet;
    if (isNative)
        NativeSet = Set;
    module.exports = SetPoly = function Set( /*iterable*/) {
        var iterable = arguments[0], self;
        if (!(this instanceof SetPoly))
            throw new TypeError('Constructor requires \'new\'');
        if (isNative && setPrototypeOf)
            self = setPrototypeOf(new NativeSet(), getPrototypeOf(this));
        else
            self = this;
        if (iterable != null)
            iterator(iterable);
        defineProperty(self, '__setData__', d('c', []));
        if (!iterable)
            return self;
        forOf(iterable, function (value) {
            if (eIndexOf.call(this, value) !== -1)
                return;
            this.push(value);
        }, self.__setData__);
        return self;
    };
    if (isNative) {
        if (setPrototypeOf)
            setPrototypeOf(SetPoly, NativeSet);
        SetPoly.prototype = Object.create(NativeSet.prototype, { constructor: d(SetPoly) });
    }
    ee(Object.defineProperties(SetPoly.prototype, {
        add: d(function (value) {
            if (this.has(value))
                return this;
            this.emit('_add', this.__setData__.push(value) - 1, value);
            return this;
        }),
        clear: d(function () {
            if (!this.__setData__.length)
                return;
            clear.call(this.__setData__);
            this.emit('_clear');
        }),
        delete: d(function (value) {
            var index = eIndexOf.call(this.__setData__, value);
            if (index === -1)
                return false;
            this.__setData__.splice(index, 1);
            this.emit('_delete', index, value);
            return true;
        }),
        entries: d(function () { return new Iterator(this, 'key+value'); }),
        forEach: d(function (cb /*, thisArg*/) {
            var thisArg = arguments[1], iterator, result, value;
            callable(cb);
            iterator = this.values();
            result = iterator._next();
            while (result !== undefined) {
                value = iterator._resolve(result);
                call.call(cb, thisArg, value, value, this);
                result = iterator._next();
            }
        }),
        has: d(function (value) {
            return (eIndexOf.call(this.__setData__, value) !== -1);
        }),
        keys: d(getValues = function () { return this.values(); }),
        size: d.gs(function () { return this.__setData__.length; }),
        values: d(function () { return new Iterator(this); }),
        toString: d(function () { return '[object Set]'; })
    }));
    defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues));
    defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set'));
},
/* es5-ext/array/#/clear.js */ function _(require, module, exports, __esModule, __esExport) {
    var value = require(11) /* ../../object/valid-value */;
    module.exports = function () {
        value(this).length = 0;
        return this;
    };
},
/* es5-ext/array/#/e-index-of.js */ function _(require, module, exports, __esModule, __esExport) {
    var numberIsNaN = require(70) /* ../../number/is-nan */, toPosInt = require(52) /* ../../number/to-pos-integer */, value = require(11) /* ../../object/valid-value */, indexOf = Array.prototype.indexOf, objHasOwnProperty = Object.prototype.hasOwnProperty, abs = Math.abs, floor = Math.floor;
    module.exports = function (searchElement /*, fromIndex*/) {
        var i, length, fromIndex, val;
        if (!numberIsNaN(searchElement))
            return indexOf.apply(this, arguments);
        length = toPosInt(value(this).length);
        fromIndex = arguments[1];
        if (isNaN(fromIndex))
            fromIndex = 0;
        else if (fromIndex >= 0)
            fromIndex = floor(fromIndex);
        else
            fromIndex = toPosInt(this.length) - floor(abs(fromIndex));
        for (i = fromIndex; i < length; ++i) {
            if (objHasOwnProperty.call(this, i)) {
                val = this[i];
                if (numberIsNaN(val))
                    return i; // Jslint: ignore
            }
        }
        return -1;
    };
},
/* es5-ext/number/is-nan/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(71) /* ./is-implemented */() ? Number.isNaN : require(72) /* ./shim */;
},
/* es5-ext/number/is-nan/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var numberIsNaN = Number.isNaN;
        if (typeof numberIsNaN !== "function")
            return false;
        return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34);
    };
},
/* es5-ext/number/is-nan/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function (value) {
        // eslint-disable-next-line no-self-compare
        return value !== value;
    };
},
/* es5-ext/object/set-prototype-of/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(74) /* ./is-implemented */() ? Object.setPrototypeOf : require(75) /* ./shim */;
},
/* es5-ext/object/set-prototype-of/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {};
    module.exports = function ( /* CustomCreate*/) {
        var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
        if (typeof setPrototypeOf !== "function")
            return false;
        return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
    };
},
/* es5-ext/object/set-prototype-of/shim.js */ function _(require, module, exports, __esModule, __esExport) {
    var isObject = require(76) /* ../is-object */, value = require(11) /* ../valid-value */, objIsPrototypeOf = Object.prototype.isPrototypeOf, defineProperty = Object.defineProperty, nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined }, validate;
    validate = function (obj, prototype) {
        value(obj);
        if (prototype === null || isObject(prototype))
            return obj;
        throw new TypeError("Prototype must be null or an object");
    };
    module.exports = (function (status) {
        var fn, set;
        if (!status)
            return null;
        if (status.level === 2) {
            if (status.set) {
                set = status.set;
                fn = function (obj, prototype) {
                    set.call(validate(obj, prototype), prototype);
                    return obj;
                };
            }
            else {
                fn = function (obj, prototype) {
                    validate(obj, prototype).__proto__ = prototype;
                    return obj;
                };
            }
        }
        else {
            fn = function self(obj, prototype) {
                var isNullBase;
                validate(obj, prototype);
                isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
                if (isNullBase)
                    delete self.nullPolyfill.__proto__;
                if (prototype === null)
                    prototype = self.nullPolyfill;
                obj.__proto__ = prototype;
                if (isNullBase)
                    defineProperty(self.nullPolyfill, "__proto__", nullDesc);
                return obj;
            };
        }
        return Object.defineProperty(fn, "level", {
            configurable: false,
            enumerable: false,
            writable: false,
            value: status.level
        });
    })((function () {
        var tmpObj1 = Object.create(null), tmpObj2 = {}, set, desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
        if (desc) {
            try {
                set = desc.set; // Opera crashes at this point
                set.call(tmpObj1, tmpObj2);
            }
            catch (ignore) { }
            if (Object.getPrototypeOf(tmpObj1) === tmpObj2)
                return { set: set, level: 2 };
        }
        tmpObj1.__proto__ = tmpObj2;
        if (Object.getPrototypeOf(tmpObj1) === tmpObj2)
            return { level: 2 };
        tmpObj1 = {};
        tmpObj1.__proto__ = tmpObj2;
        if (Object.getPrototypeOf(tmpObj1) === tmpObj2)
            return { level: 1 };
        return false;
    })());
    require(77) /* ../create */;
},
/* es5-ext/object/is-object.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(9) /* ./is-value */;
    var map = { function: true, object: true };
    module.exports = function (value) { return (isValue(value) && map[typeof value]) || false; };
},
/* es5-ext/object/create.js */ function _(require, module, exports, __esModule, __esExport) {
    var create = Object.create, shim;
    if (!require(74) /* ./set-prototype-of/is-implemented */()) {
        shim = require(75) /* ./set-prototype-of/shim */;
    }
    module.exports = (function () {
        var nullObject, polyProps, desc;
        if (!shim)
            return create;
        if (shim.level !== 1)
            return create;
        nullObject = {};
        polyProps = {};
        desc = { configurable: false, enumerable: false, writable: true, value: undefined };
        Object.getOwnPropertyNames(Object.prototype).forEach(function (name) {
            if (name === "__proto__") {
                polyProps[name] = {
                    configurable: true,
                    enumerable: false,
                    writable: true,
                    value: undefined
                };
                return;
            }
            polyProps[name] = desc;
        });
        Object.defineProperties(nullObject, polyProps);
        Object.defineProperty(shim, "nullPolyfill", {
            configurable: false,
            enumerable: false,
            writable: false,
            value: nullObject
        });
        return function (prototype, props) {
            return create(prototype === null ? nullObject : prototype, props);
        };
    })();
},
/* event-emitter/index.js */ function _(require, module, exports, __esModule, __esExport) {
    var d = require(34) /* d */, callable = require(53) /* es5-ext/object/valid-callable */, apply = Function.prototype.apply, call = Function.prototype.call, create = Object.create, defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, hasOwnProperty = Object.prototype.hasOwnProperty, descriptor = { configurable: true, enumerable: false, writable: true }, on, once, off, emit, methods, descriptors, base;
    on = function (type, listener) {
        var data;
        callable(listener);
        if (!hasOwnProperty.call(this, '__ee__')) {
            data = descriptor.value = create(null);
            defineProperty(this, '__ee__', descriptor);
            descriptor.value = null;
        }
        else {
            data = this.__ee__;
        }
        if (!data[type])
            data[type] = listener;
        else if (typeof data[type] === 'object')
            data[type].push(listener);
        else
            data[type] = [data[type], listener];
        return this;
    };
    once = function (type, listener) {
        var once, self;
        callable(listener);
        self = this;
        on.call(this, type, once = function () {
            off.call(self, type, once);
            apply.call(listener, this, arguments);
        });
        once.__eeOnceListener__ = listener;
        return this;
    };
    off = function (type, listener) {
        var data, listeners, candidate, i;
        callable(listener);
        if (!hasOwnProperty.call(this, '__ee__'))
            return this;
        data = this.__ee__;
        if (!data[type])
            return this;
        listeners = data[type];
        if (typeof listeners === 'object') {
            for (i = 0; (candidate = listeners[i]); ++i) {
                if ((candidate === listener) ||
                    (candidate.__eeOnceListener__ === listener)) {
                    if (listeners.length === 2)
                        data[type] = listeners[i ? 0 : 1];
                    else
                        listeners.splice(i, 1);
                }
            }
        }
        else {
            if ((listeners === listener) ||
                (listeners.__eeOnceListener__ === listener)) {
                delete data[type];
            }
        }
        return this;
    };
    emit = function (type) {
        var i, l, listener, listeners, args;
        if (!hasOwnProperty.call(this, '__ee__'))
            return;
        listeners = this.__ee__[type];
        if (!listeners)
            return;
        if (typeof listeners === 'object') {
            l = arguments.length;
            args = new Array(l - 1);
            for (i = 1; i < l; ++i)
                args[i - 1] = arguments[i];
            listeners = listeners.slice();
            for (i = 0; (listener = listeners[i]); ++i) {
                apply.call(listener, this, args);
            }
        }
        else {
            switch (arguments.length) {
                case 1:
                    call.call(listeners, this);
                    break;
                case 2:
                    call.call(listeners, this, arguments[1]);
                    break;
                case 3:
                    call.call(listeners, this, arguments[1], arguments[2]);
                    break;
                default:
                    l = arguments.length;
                    args = new Array(l - 1);
                    for (i = 1; i < l; ++i) {
                        args[i - 1] = arguments[i];
                    }
                    apply.call(listeners, this, args);
            }
        }
    };
    methods = {
        on: on,
        once: once,
        off: off,
        emit: emit
    };
    descriptors = {
        on: d(on),
        once: d(once),
        off: d(off),
        emit: d(emit)
    };
    base = defineProperties({}, descriptors);
    module.exports = exports = function (o) {
        return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
    };
    exports.methods = methods;
},
/* es6-iterator/valid-iterable.js */ function _(require, module, exports, __esModule, __esExport) {
    var isIterable = require(80) /* ./is-iterable */;
    module.exports = function (value) {
        if (!isIterable(value))
            throw new TypeError(value + " is not iterable");
        return value;
    };
},
/* es6-iterator/is-iterable.js */ function _(require, module, exports, __esModule, __esExport) {
    var isArguments = require(50) /* es5-ext/function/is-arguments */, isValue = require(9) /* es5-ext/object/is-value */, isString = require(54) /* es5-ext/string/is-string */;
    var iteratorSymbol = require(28) /* es6-symbol */.iterator, isArray = Array.isArray;
    module.exports = function (value) {
        if (!isValue(value))
            return false;
        if (isArray(value))
            return true;
        if (isString(value))
            return true;
        if (isArguments(value))
            return true;
        return typeof value[iteratorSymbol] === "function";
    };
},
/* es6-iterator/for-of.js */ function _(require, module, exports, __esModule, __esExport) {
    var isArguments = require(50) /* es5-ext/function/is-arguments */, callable = require(53) /* es5-ext/object/valid-callable */, isString = require(54) /* es5-ext/string/is-string */, get = require(82) /* ./get */;
    var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some;
    module.exports = function (iterable, cb /*, thisArg*/) {
        var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
        if (isArray(iterable) || isArguments(iterable))
            mode = "array";
        else if (isString(iterable))
            mode = "string";
        else
            iterable = get(iterable);
        callable(cb);
        doBreak = function () {
            broken = true;
        };
        if (mode === "array") {
            some.call(iterable, function (value) {
                call.call(cb, thisArg, value, doBreak);
                return broken;
            });
            return;
        }
        if (mode === "string") {
            length = iterable.length;
            for (i = 0; i < length; ++i) {
                char = iterable[i];
                if (i + 1 < length) {
                    code = char.charCodeAt(0);
                    if (code >= 0xd800 && code <= 0xdbff)
                        char += iterable[++i];
                }
                call.call(cb, thisArg, char, doBreak);
                if (broken)
                    break;
            }
            return;
        }
        result = iterable.next();
        while (!result.done) {
            call.call(cb, thisArg, result.value, doBreak);
            if (broken)
                return;
            result = iterable.next();
        }
    };
},
/* es6-iterator/get.js */ function _(require, module, exports, __esModule, __esExport) {
    var isArguments = require(50) /* es5-ext/function/is-arguments */, isString = require(54) /* es5-ext/string/is-string */, ArrayIterator = require(83) /* ./array */, StringIterator = require(97) /* ./string */, iterable = require(79) /* ./valid-iterable */, iteratorSymbol = require(28) /* es6-symbol */.iterator;
    module.exports = function (obj) {
        if (typeof iterable(obj)[iteratorSymbol] === "function")
            return obj[iteratorSymbol]();
        if (isArguments(obj))
            return new ArrayIterator(obj);
        if (isString(obj))
            return new StringIterator(obj);
        return new ArrayIterator(obj);
    };
},
/* es6-iterator/array.js */ function _(require, module, exports, __esModule, __esExport) {
    var setPrototypeOf = require(73) /* es5-ext/object/set-prototype-of */, contains = require(42) /* es5-ext/string/#/contains */, d = require(34) /* d */, Symbol = require(28) /* es6-symbol */, Iterator = require(84) /* ./ */;
    var defineProperty = Object.defineProperty, ArrayIterator;
    ArrayIterator = module.exports = function (arr, kind) {
        if (!(this instanceof ArrayIterator))
            throw new TypeError("Constructor requires 'new'");
        Iterator.call(this, arr);
        if (!kind)
            kind = "value";
        else if (contains.call(kind, "key+value"))
            kind = "key+value";
        else if (contains.call(kind, "key"))
            kind = "key";
        else
            kind = "value";
        defineProperty(this, "__kind__", d("", kind));
    };
    if (setPrototypeOf)
        setPrototypeOf(ArrayIterator, Iterator);
    // Internal %ArrayIteratorPrototype% doesn't expose its constructor
    delete ArrayIterator.prototype.constructor;
    ArrayIterator.prototype = Object.create(Iterator.prototype, {
        _resolve: d(function (i) {
            if (this.__kind__ === "value")
                return this.__list__[i];
            if (this.__kind__ === "key+value")
                return [i, this.__list__[i]];
            return i;
        })
    });
    defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));
},
/* es6-iterator/index.js */ function _(require, module, exports, __esModule, __esExport) {
    var clear = require(68) /* es5-ext/array/#/clear */, assign = require(40) /* es5-ext/object/assign */, callable = require(53) /* es5-ext/object/valid-callable */, value = require(11) /* es5-ext/object/valid-value */, d = require(34) /* d */, autoBind = require(85) /* d/auto-bind */, Symbol = require(28) /* es6-symbol */;
    var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator;
    module.exports = Iterator = function (list, context) {
        if (!(this instanceof Iterator))
            throw new TypeError("Constructor requires 'new'");
        defineProperties(this, {
            __list__: d("w", value(list)),
            __context__: d("w", context),
            __nextIndex__: d("w", 0)
        });
        if (!context)
            return;
        callable(context.on);
        context.on("_add", this._onAdd);
        context.on("_delete", this._onDelete);
        context.on("_clear", this._onClear);
    };
    // Internal %IteratorPrototype% doesn't expose its constructor
    delete Iterator.prototype.constructor;
    defineProperties(Iterator.prototype, assign({
        _next: d(function () {
            var i;
            if (!this.__list__)
                return undefined;
            if (this.__redo__) {
                i = this.__redo__.shift();
                if (i !== undefined)
                    return i;
            }
            if (this.__nextIndex__ < this.__list__.length)
                return this.__nextIndex__++;
            this._unBind();
            return undefined;
        }),
        next: d(function () {
            return this._createResult(this._next());
        }),
        _createResult: d(function (i) {
            if (i === undefined)
                return { done: true, value: undefined };
            return { done: false, value: this._resolve(i) };
        }),
        _resolve: d(function (i) {
            return this.__list__[i];
        }),
        _unBind: d(function () {
            this.__list__ = null;
            delete this.__redo__;
            if (!this.__context__)
                return;
            this.__context__.off("_add", this._onAdd);
            this.__context__.off("_delete", this._onDelete);
            this.__context__.off("_clear", this._onClear);
            this.__context__ = null;
        }),
        toString: d(function () {
            return "[object " + (this[Symbol.toStringTag] || "Object") + "]";
        })
    }, autoBind({
        _onAdd: d(function (index) {
            if (index >= this.__nextIndex__)
                return;
            ++this.__nextIndex__;
            if (!this.__redo__) {
                defineProperty(this, "__redo__", d("c", [index]));
                return;
            }
            this.__redo__.forEach(function (redo, i) {
                if (redo >= index)
                    this.__redo__[i] = ++redo;
            }, this);
            this.__redo__.push(index);
        }),
        _onDelete: d(function (index) {
            var i;
            if (index >= this.__nextIndex__)
                return;
            --this.__nextIndex__;
            if (!this.__redo__)
                return;
            i = this.__redo__.indexOf(index);
            if (i !== -1)
                this.__redo__.splice(i, 1);
            this.__redo__.forEach(function (redo, j) {
                if (redo > index)
                    this.__redo__[j] = --redo;
            }, this);
        }),
        _onClear: d(function () {
            if (this.__redo__)
                clear.call(this.__redo__);
            this.__nextIndex__ = 0;
        })
    })));
    defineProperty(Iterator.prototype, Symbol.iterator, d(function () {
        return this;
    }));
},
/* d/auto-bind.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(35) /* type/value/is */, ensureValue = require(86) /* type/value/ensure */, ensurePlainFunction = require(91) /* type/plain-function/ensure */, copy = require(92) /* es5-ext/object/copy */, normalizeOptions = require(41) /* es5-ext/object/normalize-options */, map = require(94) /* es5-ext/object/map */;
    var bind = Function.prototype.bind, defineProperty = Object.defineProperty, hasOwnProperty = Object.prototype.hasOwnProperty, define;
    define = function (name, desc, options) {
        var value = ensureValue(desc) && ensurePlainFunction(desc.value), dgs;
        dgs = copy(desc);
        delete dgs.writable;
        delete dgs.value;
        dgs.get = function () {
            if (!options.overwriteDefinition && hasOwnProperty.call(this, name))
                return value;
            desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
            defineProperty(this, name, desc);
            return this[name];
        };
        return dgs;
    };
    module.exports = function (props /*, options*/) {
        var options = normalizeOptions(arguments[1]);
        if (isValue(options.resolveContext))
            ensurePlainFunction(options.resolveContext);
        return map(props, function (desc, name) { return define(name, desc, options); });
    };
},
/* type/value/ensure.js */ function _(require, module, exports, __esModule, __esExport) {
    var resolveException = require(87) /* ../lib/resolve-exception */, is = require(35) /* ./is */;
    module.exports = function (value /*, options*/) {
        if (is(value))
            return value;
        return resolveException(value, "Cannot use %v", arguments[1]);
    };
},
/* type/lib/resolve-exception.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(35) /* ../value/is */, isObject = require(39) /* ../object/is */, stringCoerce = require(88) /* ../string/coerce */, toShortString = require(89) /* ./to-short-string */;
    var resolveMessage = function (message, value) {
        return message.replace("%v", toShortString(value));
    };
    module.exports = function (value, defaultMessage, inputOptions) {
        if (!isObject(inputOptions))
            throw new TypeError(resolveMessage(defaultMessage, value));
        if (!isValue(value)) {
            if ("default" in inputOptions)
                return inputOptions["default"];
            if (inputOptions.isOptional)
                return null;
        }
        var errorMessage = stringCoerce(inputOptions.errorMessage);
        if (!isValue(errorMessage))
            errorMessage = defaultMessage;
        throw new TypeError(resolveMessage(errorMessage, value));
    };
},
/* type/string/coerce.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(35) /* ../value/is */, isObject = require(39) /* ../object/is */;
    var objectToString = Object.prototype.toString;
    module.exports = function (value) {
        if (!isValue(value))
            return null;
        if (isObject(value)) {
            // Reject Object.prototype.toString coercion
            var valueToString = value.toString;
            if (typeof valueToString !== "function")
                return null;
            if (valueToString === objectToString)
                return null;
            // Note: It can be object coming from other realm, still as there's no ES3 and CSP compliant
            // way to resolve its realm's Object.prototype.toString it's left as not addressed edge case
        }
        try {
            return "" + value; // Ensure implicit coercion
        }
        catch (error) {
            return null;
        }
    };
},
/* type/lib/to-short-string.js */ function _(require, module, exports, __esModule, __esExport) {
    var safeToString = require(90) /* ./safe-to-string */;
    var reNewLine = /[\n\r\u2028\u2029]/g;
    module.exports = function (value) {
        var string = safeToString(value);
        if (string === null)
            return "<Non-coercible to string value>";
        // Trim if too long
        if (string.length > 100)
            string = string.slice(0, 99) + "…";
        // Replace eventual new lines
        string = string.replace(reNewLine, function (char) {
            switch (char) {
                case "\n":
                    return "\\n";
                case "\r":
                    return "\\r";
                case "\u2028":
                    return "\\u2028";
                case "\u2029":
                    return "\\u2029";
                /* istanbul ignore next */
                default:
                    throw new Error("Unexpected character");
            }
        });
        return string;
    };
},
/* type/lib/safe-to-string.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function (value) {
        try {
            return value.toString();
        }
        catch (error) {
            try {
                return String(value);
            }
            catch (error2) {
                return null;
            }
        }
    };
},
/* type/plain-function/ensure.js */ function _(require, module, exports, __esModule, __esExport) {
    var resolveException = require(87) /* ../lib/resolve-exception */, is = require(36) /* ./is */;
    module.exports = function (value /*, options*/) {
        if (is(value))
            return value;
        return resolveException(value, "%v is not a plain function", arguments[1]);
    };
},
/* es5-ext/object/copy.js */ function _(require, module, exports, __esModule, __esExport) {
    var aFrom = require(93) /* ../array/from */, assign = require(40) /* ./assign */, value = require(11) /* ./valid-value */;
    module.exports = function (obj /*, propertyNames, options*/) {
        var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
        if (copy !== obj && !propertyNames)
            return copy;
        var result = {};
        if (propertyNames) {
            aFrom(propertyNames, function (propertyName) {
                if (options.ensure || propertyName in obj)
                    result[propertyName] = obj[propertyName];
            });
        }
        else {
            assign(result, obj);
        }
        return result;
    };
},
/* es5-ext/array/from/index.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(26) /* ./is-implemented */() ? Array.from : require(27) /* ./shim */;
},
/* es5-ext/object/map.js */ function _(require, module, exports, __esModule, __esExport) {
    var callable = require(53) /* ./valid-callable */, forEach = require(95) /* ./for-each */, call = Function.prototype.call;
    module.exports = function (obj, cb /*, thisArg*/) {
        var result = {}, thisArg = arguments[2];
        callable(cb);
        forEach(obj, function (value, key, targetObj, index) {
            result[key] = call.call(cb, thisArg, value, key, targetObj, index);
        });
        return result;
    };
},
/* es5-ext/object/for-each.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(96) /* ./_iterate */("forEach");
},
/* es5-ext/object/_iterate.js */ function _(require, module, exports, __esModule, __esExport) {
    var callable = require(53) /* ./valid-callable */, value = require(11) /* ./valid-value */, bind = Function.prototype.bind, call = Function.prototype.call, keys = Object.keys, objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
    module.exports = function (method, defVal) {
        return function (obj, cb /*, thisArg, compareFn*/) {
            var list, thisArg = arguments[2], compareFn = arguments[3];
            obj = Object(value(obj));
            callable(cb);
            list = keys(obj);
            if (compareFn) {
                list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined);
            }
            if (typeof method !== "function")
                method = list[method];
            return call.call(method, list, function (key, index) {
                if (!objPropertyIsEnumerable.call(obj, key))
                    return defVal;
                return call.call(cb, thisArg, obj[key], key, obj, index);
            });
        };
    };
},
/* es6-iterator/string.js */ function _(require, module, exports, __esModule, __esExport) {
    var setPrototypeOf = require(73) /* es5-ext/object/set-prototype-of */, d = require(34) /* d */, Symbol = require(28) /* es6-symbol */, Iterator = require(84) /* ./ */;
    var defineProperty = Object.defineProperty, StringIterator;
    StringIterator = module.exports = function (str) {
        if (!(this instanceof StringIterator))
            throw new TypeError("Constructor requires 'new'");
        str = String(str);
        Iterator.call(this, str);
        defineProperty(this, "__length__", d("", str.length));
    };
    if (setPrototypeOf)
        setPrototypeOf(StringIterator, Iterator);
    // Internal %ArrayIteratorPrototype% doesn't expose its constructor
    delete StringIterator.prototype.constructor;
    StringIterator.prototype = Object.create(Iterator.prototype, {
        _next: d(function () {
            if (!this.__list__)
                return undefined;
            if (this.__nextIndex__ < this.__length__)
                return this.__nextIndex__++;
            this._unBind();
            return undefined;
        }),
        _resolve: d(function (i) {
            var char = this.__list__[i], code;
            if (this.__nextIndex__ === this.__length__)
                return char;
            code = char.charCodeAt(0);
            if (code >= 0xd800 && code <= 0xdbff)
                return char + this.__list__[this.__nextIndex__++];
            return char;
        })
    });
    defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));
},
/* es6-set/lib/iterator.js */ function _(require, module, exports, __esModule, __esExport) {
    var setPrototypeOf = require(73) /* es5-ext/object/set-prototype-of */, contains = require(42) /* es5-ext/string/#/contains */, d = require(34) /* d */, Iterator = require(84) /* es6-iterator */, toStringTagSymbol = require(28) /* es6-symbol */.toStringTag, defineProperty = Object.defineProperty, SetIterator;
    SetIterator = module.exports = function (set, kind) {
        if (!(this instanceof SetIterator))
            return new SetIterator(set, kind);
        Iterator.call(this, set.__setData__, set);
        if (!kind)
            kind = 'value';
        else if (contains.call(kind, 'key+value'))
            kind = 'key+value';
        else
            kind = 'value';
        defineProperty(this, '__kind__', d('', kind));
    };
    if (setPrototypeOf)
        setPrototypeOf(SetIterator, Iterator);
    SetIterator.prototype = Object.create(Iterator.prototype, {
        constructor: d(SetIterator),
        _resolve: d(function (i) {
            if (this.__kind__ === 'value')
                return this.__list__[i];
            return [this.__list__[i], this.__list__[i]];
        }),
        toString: d(function () { return '[object Set Iterator]'; })
    });
    defineProperty(SetIterator.prototype, toStringTagSymbol, d('c', 'Set Iterator'));
},
/* es6-set/is-native-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = (function () {
        if (typeof Set === 'undefined')
            return false;
        return (Object.prototype.toString.call(Set.prototype) === '[object Set]');
    }());
},
/* es6-map/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(101) /* ./is-implemented */()) {
        Object.defineProperty(require(66) /* es5-ext/global */, 'Map', { value: require(102) /* ./polyfill */, configurable: true, enumerable: false,
            writable: true });
    }
},
/* es6-map/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var map, iterator, result;
        if (typeof Map !== 'function')
            return false;
        try {
            // WebKit doesn't support arguments and crashes
            map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]);
        }
        catch (e) {
            return false;
        }
        if (String(map) !== '[object Map]')
            return false;
        if (map.size !== 3)
            return false;
        if (typeof map.clear !== 'function')
            return false;
        if (typeof map.delete !== 'function')
            return false;
        if (typeof map.entries !== 'function')
            return false;
        if (typeof map.forEach !== 'function')
            return false;
        if (typeof map.get !== 'function')
            return false;
        if (typeof map.has !== 'function')
            return false;
        if (typeof map.keys !== 'function')
            return false;
        if (typeof map.set !== 'function')
            return false;
        if (typeof map.values !== 'function')
            return false;
        iterator = map.entries();
        result = iterator.next();
        if (result.done !== false)
            return false;
        if (!result.value)
            return false;
        if (result.value[0] !== 'raz')
            return false;
        if (result.value[1] !== 'one')
            return false;
        return true;
    };
},
/* es6-map/polyfill.js */ function _(require, module, exports, __esModule, __esExport) {
    var clear = require(68) /* es5-ext/array/#/clear */, eIndexOf = require(69) /* es5-ext/array/#/e-index-of */, setPrototypeOf = require(73) /* es5-ext/object/set-prototype-of */, callable = require(53) /* es5-ext/object/valid-callable */, validValue = require(11) /* es5-ext/object/valid-value */, d = require(34) /* d */, ee = require(78) /* event-emitter */, Symbol = require(28) /* es6-symbol */, iterator = require(79) /* es6-iterator/valid-iterable */, forOf = require(81) /* es6-iterator/for-of */, Iterator = require(103) /* ./lib/iterator */, isNative = require(106) /* ./is-native-implemented */, call = Function.prototype.call, defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf, MapPoly;
    module.exports = MapPoly = function ( /*iterable*/) {
        var iterable = arguments[0], keys, values, self;
        if (!(this instanceof MapPoly))
            throw new TypeError('Constructor requires \'new\'');
        if (isNative && setPrototypeOf && (Map !== MapPoly)) {
            self = setPrototypeOf(new Map(), getPrototypeOf(this));
        }
        else {
            self = this;
        }
        if (iterable != null)
            iterator(iterable);
        defineProperties(self, {
            __mapKeysData__: d('c', keys = []),
            __mapValuesData__: d('c', values = [])
        });
        if (!iterable)
            return self;
        forOf(iterable, function (value) {
            var key = validValue(value)[0];
            value = value[1];
            if (eIndexOf.call(keys, key) !== -1)
                return;
            keys.push(key);
            values.push(value);
        }, self);
        return self;
    };
    if (isNative) {
        if (setPrototypeOf)
            setPrototypeOf(MapPoly, Map);
        MapPoly.prototype = Object.create(Map.prototype, {
            constructor: d(MapPoly)
        });
    }
    ee(defineProperties(MapPoly.prototype, {
        clear: d(function () {
            if (!this.__mapKeysData__.length)
                return;
            clear.call(this.__mapKeysData__);
            clear.call(this.__mapValuesData__);
            this.emit('_clear');
        }),
        delete: d(function (key) {
            var index = eIndexOf.call(this.__mapKeysData__, key);
            if (index === -1)
                return false;
            this.__mapKeysData__.splice(index, 1);
            this.__mapValuesData__.splice(index, 1);
            this.emit('_delete', index, key);
            return true;
        }),
        entries: d(function () { return new Iterator(this, 'key+value'); }),
        forEach: d(function (cb /*, thisArg*/) {
            var thisArg = arguments[1], iterator, result;
            callable(cb);
            iterator = this.entries();
            result = iterator._next();
            while (result !== undefined) {
                call.call(cb, thisArg, this.__mapValuesData__[result], this.__mapKeysData__[result], this);
                result = iterator._next();
            }
        }),
        get: d(function (key) {
            var index = eIndexOf.call(this.__mapKeysData__, key);
            if (index === -1)
                return;
            return this.__mapValuesData__[index];
        }),
        has: d(function (key) {
            return (eIndexOf.call(this.__mapKeysData__, key) !== -1);
        }),
        keys: d(function () { return new Iterator(this, 'key'); }),
        set: d(function (key, value) {
            var index = eIndexOf.call(this.__mapKeysData__, key), emit;
            if (index === -1) {
                index = this.__mapKeysData__.push(key) - 1;
                emit = true;
            }
            this.__mapValuesData__[index] = value;
            if (emit)
                this.emit('_add', index, key);
            return this;
        }),
        size: d.gs(function () { return this.__mapKeysData__.length; }),
        values: d(function () { return new Iterator(this, 'value'); }),
        toString: d(function () { return '[object Map]'; })
    }));
    Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () {
        return this.entries();
    }));
    Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
},
/* es6-map/lib/iterator.js */ function _(require, module, exports, __esModule, __esExport) {
    var setPrototypeOf = require(73) /* es5-ext/object/set-prototype-of */, d = require(34) /* d */, Iterator = require(84) /* es6-iterator */, toStringTagSymbol = require(28) /* es6-symbol */.toStringTag, kinds = require(104) /* ./iterator-kinds */, defineProperties = Object.defineProperties, unBind = Iterator.prototype._unBind, MapIterator;
    MapIterator = module.exports = function (map, kind) {
        if (!(this instanceof MapIterator))
            return new MapIterator(map, kind);
        Iterator.call(this, map.__mapKeysData__, map);
        if (!kind || !kinds[kind])
            kind = 'key+value';
        defineProperties(this, {
            __kind__: d('', kind),
            __values__: d('w', map.__mapValuesData__)
        });
    };
    if (setPrototypeOf)
        setPrototypeOf(MapIterator, Iterator);
    MapIterator.prototype = Object.create(Iterator.prototype, {
        constructor: d(MapIterator),
        _resolve: d(function (i) {
            if (this.__kind__ === 'value')
                return this.__values__[i];
            if (this.__kind__ === 'key')
                return this.__list__[i];
            return [this.__list__[i], this.__values__[i]];
        }),
        _unBind: d(function () {
            this.__values__ = null;
            unBind.call(this);
        }),
        toString: d(function () { return '[object Map Iterator]'; })
    });
    Object.defineProperty(MapIterator.prototype, toStringTagSymbol, d('c', 'Map Iterator'));
},
/* es6-map/lib/iterator-kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(105) /* es5-ext/object/primitive-set */('key', 'value', 'key+value');
},
/* es5-ext/object/primitive-set.js */ function _(require, module, exports, __esModule, __esExport) {
    var forEach = Array.prototype.forEach, create = Object.create;
    // eslint-disable-next-line no-unused-vars
    module.exports = function (arg /*, …args*/) {
        var set = create(null);
        forEach.call(arguments, function (name) { set[name] = true; });
        return set;
    };
},
/* es6-map/is-native-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = (function () {
        if (typeof Map === 'undefined')
            return false;
        return (Object.prototype.toString.call(new Map()) === '[object Map]');
    }());
},
/* es6-weak-map/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(108) /* ./is-implemented */()) {
        Object.defineProperty(require(66) /* es5-ext/global */, "WeakMap", {
            value: require(109) /* ./polyfill */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es6-weak-map/is-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = function () {
        var weakMap, obj;
        if (typeof WeakMap !== "function")
            return false;
        try {
            // WebKit doesn't support arguments and crashes
            weakMap = new WeakMap([[obj = {}, "one"], [{}, "two"], [{}, "three"]]);
        }
        catch (e) {
            return false;
        }
        if (String(weakMap) !== "[object WeakMap]")
            return false;
        if (typeof weakMap.set !== "function")
            return false;
        if (weakMap.set({}, 1) !== weakMap)
            return false;
        if (typeof weakMap.delete !== "function")
            return false;
        if (typeof weakMap.has !== "function")
            return false;
        if (weakMap.get(obj) !== "one")
            return false;
        return true;
    };
},
/* es6-weak-map/polyfill.js */ function _(require, module, exports, __esModule, __esExport) {
    var isValue = require(9) /* es5-ext/object/is-value */, setPrototypeOf = require(73) /* es5-ext/object/set-prototype-of */, object = require(110) /* es5-ext/object/valid-object */, ensureValue = require(11) /* es5-ext/object/valid-value */, randomUniq = require(111) /* es5-ext/string/random-uniq */, d = require(34) /* d */, getIterator = require(82) /* es6-iterator/get */, forOf = require(81) /* es6-iterator/for-of */, toStringTagSymbol = require(28) /* es6-symbol */.toStringTag, isNative = require(112) /* ./is-native-implemented */, isArray = Array.isArray, defineProperty = Object.defineProperty, objHasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf, WeakMapPoly;
    module.exports = WeakMapPoly = function ( /* Iterable*/) {
        var iterable = arguments[0], self;
        if (!(this instanceof WeakMapPoly))
            throw new TypeError("Constructor requires 'new'");
        self = isNative && setPrototypeOf && (WeakMap !== WeakMapPoly)
            ? setPrototypeOf(new WeakMap(), getPrototypeOf(this)) : this;
        if (isValue(iterable)) {
            if (!isArray(iterable))
                iterable = getIterator(iterable);
        }
        defineProperty(self, "__weakMapData__", d("c", "$weakMap$" + randomUniq()));
        if (!iterable)
            return self;
        forOf(iterable, function (val) {
            ensureValue(val);
            self.set(val[0], val[1]);
        });
        return self;
    };
    if (isNative) {
        if (setPrototypeOf)
            setPrototypeOf(WeakMapPoly, WeakMap);
        WeakMapPoly.prototype = Object.create(WeakMap.prototype, { constructor: d(WeakMapPoly) });
    }
    Object.defineProperties(WeakMapPoly.prototype, {
        delete: d(function (key) {
            if (objHasOwnProperty.call(object(key), this.__weakMapData__)) {
                delete key[this.__weakMapData__];
                return true;
            }
            return false;
        }),
        get: d(function (key) {
            if (!objHasOwnProperty.call(object(key), this.__weakMapData__))
                return undefined;
            return key[this.__weakMapData__];
        }),
        has: d(function (key) {
            return objHasOwnProperty.call(object(key), this.__weakMapData__);
        }),
        set: d(function (key, value) {
            defineProperty(object(key), this.__weakMapData__, d("c", value));
            return this;
        }),
        toString: d(function () {
            return "[object WeakMap]";
        })
    });
    defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d("c", "WeakMap"));
},
/* es5-ext/object/valid-object.js */ function _(require, module, exports, __esModule, __esExport) {
    var isObject = require(76) /* ./is-object */;
    module.exports = function (value) {
        if (!isObject(value))
            throw new TypeError(value + " is not an Object");
        return value;
    };
},
/* es5-ext/string/random-uniq.js */ function _(require, module, exports, __esModule, __esExport) {
    var generated = Object.create(null), random = Math.random;
    module.exports = function () {
        var str;
        do {
            str = random().toString(36).slice(2);
        } while (generated[str]);
        return str;
    };
},
/* es6-weak-map/is-native-implemented.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = (function () {
        if (typeof WeakMap !== "function")
            return false;
        return Object.prototype.toString.call(new WeakMap()) === "[object WeakMap]";
    }());
},
/* es6-symbol/implement.js */ function _(require, module, exports, __esModule, __esExport) {
    if (!require(29) /* ./is-implemented */()) {
        Object.defineProperty(require(30) /* ext/global-this */, "Symbol", {
            value: require(33) /* ./polyfill */,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
},
/* es6-promise/auto.js */ function _(require, module, exports, __esModule, __esExport) {
    module.exports = require(115) /* ./ */.polyfill();
},
/* es6-promise/dist/es6-promise.js */ function _(require, module, exports, __esModule, __esExport) {
    /*!
     * @overview es6-promise - a tiny implementation of Promises/A+.
     * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
     * @license   Licensed under MIT license
     *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
     * @version   v4.2.8+1e68dce6
     */
    (function (global, factory) {
        typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
            typeof define === 'function' && define.amd ? define(factory) :
                (global.ES6Promise = factory());
    }(this, (function () {
        'use strict';
        function objectOrFunction(x) {
            var type = typeof x;
            return x !== null && (type === 'object' || type === 'function');
        }
        function isFunction(x) {
            return typeof x === 'function';
        }
        var _isArray = void 0;
        if (Array.isArray) {
            _isArray = Array.isArray;
        }
        else {
            _isArray = function (x) {
                return Object.prototype.toString.call(x) === '[object Array]';
            };
        }
        var isArray = _isArray;
        var len = 0;
        var vertxNext = void 0;
        var customSchedulerFn = void 0;
        var asap = function asap(callback, arg) {
            queue[len] = callback;
            queue[len + 1] = arg;
            len += 2;
            if (len === 2) {
                // If len is 2, that means that we need to schedule an async flush.
                // If additional callbacks are queued before the queue is flushed, they
                // will be processed by this flush that we are scheduling.
                if (customSchedulerFn) {
                    customSchedulerFn(flush);
                }
                else {
                    scheduleFlush();
                }
            }
        };
        function setScheduler(scheduleFn) {
            customSchedulerFn = scheduleFn;
        }
        function setAsap(asapFn) {
            asap = asapFn;
        }
        var browserWindow = typeof window !== 'undefined' ? window : undefined;
        var browserGlobal = browserWindow || {};
        var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
        var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
        // test for web worker but not in IE10
        var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
        // node
        function useNextTick() {
            // node version 0.10.x displays a deprecation warning when nextTick is used recursively
            // see https://github.com/cujojs/when/issues/410 for details
            return function () {
                return process.nextTick(flush);
            };
        }
        // vertx
        function useVertxTimer() {
            if (typeof vertxNext !== 'undefined') {
                return function () {
                    vertxNext(flush);
                };
            }
            return useSetTimeout();
        }
        function useMutationObserver() {
            var iterations = 0;
            var observer = new BrowserMutationObserver(flush);
            var node = document.createTextNode('');
            observer.observe(node, { characterData: true });
            return function () {
                node.data = iterations = ++iterations % 2;
            };
        }
        // web worker
        function useMessageChannel() {
            var channel = new MessageChannel();
            channel.port1.onmessage = flush;
            return function () {
                return channel.port2.postMessage(0);
            };
        }
        function useSetTimeout() {
            // Store setTimeout reference so es6-promise will be unaffected by
            // other code modifying setTimeout (like sinon.useFakeTimers())
            var globalSetTimeout = setTimeout;
            return function () {
                return globalSetTimeout(flush, 1);
            };
        }
        var queue = new Array(1000);
        function flush() {
            for (var i = 0; i < len; i += 2) {
                var callback = queue[i];
                var arg = queue[i + 1];
                callback(arg);
                queue[i] = undefined;
                queue[i + 1] = undefined;
            }
            len = 0;
        }
        function attemptVertx() {
            try {
                var vertx = Function('return this')().require('vertx');
                vertxNext = vertx.runOnLoop || vertx.runOnContext;
                return useVertxTimer();
            }
            catch (e) {
                return useSetTimeout();
            }
        }
        var scheduleFlush = void 0;
        // Decide what async method to use to triggering processing of queued callbacks:
        if (isNode) {
            scheduleFlush = useNextTick();
        }
        else if (BrowserMutationObserver) {
            scheduleFlush = useMutationObserver();
        }
        else if (isWorker) {
            scheduleFlush = useMessageChannel();
        }
        else if (browserWindow === undefined && typeof require === 'function') {
            scheduleFlush = attemptVertx();
        }
        else {
            scheduleFlush = useSetTimeout();
        }
        function then(onFulfillment, onRejection) {
            var parent = this;
            var child = new this.constructor(noop);
            if (child[PROMISE_ID] === undefined) {
                makePromise(child);
            }
            var _state = parent._state;
            if (_state) {
                var callback = arguments[_state - 1];
                asap(function () {
                    return invokeCallback(_state, child, callback, parent._result);
                });
            }
            else {
                subscribe(parent, child, onFulfillment, onRejection);
            }
            return child;
        }
        /**
          `Promise.resolve` returns a promise that will become resolved with the
          passed `value`. It is shorthand for the following:
        
          ```javascript
          let promise = new Promise(function(resolve, reject){
            resolve(1);
          });
        
          promise.then(function(value){
            // value === 1
          });
          ```
        
          Instead of writing the above, your code now simply becomes the following:
        
          ```javascript
          let promise = Promise.resolve(1);
        
          promise.then(function(value){
            // value === 1
          });
          ```
        
          @method resolve
          @static
          @param {Any} value value that the returned promise will be resolved with
          Useful for tooling.
          @return {Promise} a promise that will become fulfilled with the given
          `value`
        */
        function resolve$1(object) {
            /*jshint validthis:true */
            var Constructor = this;
            if (object && typeof object === 'object' && object.constructor === Constructor) {
                return object;
            }
            var promise = new Constructor(noop);
            resolve(promise, object);
            return promise;
        }
        var PROMISE_ID = Math.random().toString(36).substring(2);
        function noop() { }
        var PENDING = void 0;
        var FULFILLED = 1;
        var REJECTED = 2;
        function selfFulfillment() {
            return new TypeError("You cannot resolve a promise with itself");
        }
        function cannotReturnOwn() {
            return new TypeError('A promises callback cannot return that same promise.');
        }
        function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
            try {
                then$$1.call(value, fulfillmentHandler, rejectionHandler);
            }
            catch (e) {
                return e;
            }
        }
        function handleForeignThenable(promise, thenable, then$$1) {
            asap(function (promise) {
                var sealed = false;
                var error = tryThen(then$$1, thenable, function (value) {
                    if (sealed) {
                        return;
                    }
                    sealed = true;
                    if (thenable !== value) {
                        resolve(promise, value);
                    }
                    else {
                        fulfill(promise, value);
                    }
                }, function (reason) {
                    if (sealed) {
                        return;
                    }
                    sealed = true;
                    reject(promise, reason);
                }, 'Settle: ' + (promise._label || ' unknown promise'));
                if (!sealed && error) {
                    sealed = true;
                    reject(promise, error);
                }
            }, promise);
        }
        function handleOwnThenable(promise, thenable) {
            if (thenable._state === FULFILLED) {
                fulfill(promise, thenable._result);
            }
            else if (thenable._state === REJECTED) {
                reject(promise, thenable._result);
            }
            else {
                subscribe(thenable, undefined, function (value) {
                    return resolve(promise, value);
                }, function (reason) {
                    return reject(promise, reason);
                });
            }
        }
        function handleMaybeThenable(promise, maybeThenable, then$$1) {
            if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
                handleOwnThenable(promise, maybeThenable);
            }
            else {
                if (then$$1 === undefined) {
                    fulfill(promise, maybeThenable);
                }
                else if (isFunction(then$$1)) {
                    handleForeignThenable(promise, maybeThenable, then$$1);
                }
                else {
                    fulfill(promise, maybeThenable);
                }
            }
        }
        function resolve(promise, value) {
            if (promise === value) {
                reject(promise, selfFulfillment());
            }
            else if (objectOrFunction(value)) {
                var then$$1 = void 0;
                try {
                    then$$1 = value.then;
                }
                catch (error) {
                    reject(promise, error);
                    return;
                }
                handleMaybeThenable(promise, value, then$$1);
            }
            else {
                fulfill(promise, value);
            }
        }
        function publishRejection(promise) {
            if (promise._onerror) {
                promise._onerror(promise._result);
            }
            publish(promise);
        }
        function fulfill(promise, value) {
            if (promise._state !== PENDING) {
                return;
            }
            promise._result = value;
            promise._state = FULFILLED;
            if (promise._subscribers.length !== 0) {
                asap(publish, promise);
            }
        }
        function reject(promise, reason) {
            if (promise._state !== PENDING) {
                return;
            }
            promise._state = REJECTED;
            promise._result = reason;
            asap(publishRejection, promise);
        }
        function subscribe(parent, child, onFulfillment, onRejection) {
            var _subscribers = parent._subscribers;
            var length = _subscribers.length;
            parent._onerror = null;
            _subscribers[length] = child;
            _subscribers[length + FULFILLED] = onFulfillment;
            _subscribers[length + REJECTED] = onRejection;
            if (length === 0 && parent._state) {
                asap(publish, parent);
            }
        }
        function publish(promise) {
            var subscribers = promise._subscribers;
            var settled = promise._state;
            if (subscribers.length === 0) {
                return;
            }
            var child = void 0, callback = void 0, detail = promise._result;
            for (var i = 0; i < subscribers.length; i += 3) {
                child = subscribers[i];
                callback = subscribers[i + settled];
                if (child) {
                    invokeCallback(settled, child, callback, detail);
                }
                else {
                    callback(detail);
                }
            }
            promise._subscribers.length = 0;
        }
        function invokeCallback(settled, promise, callback, detail) {
            var hasCallback = isFunction(callback), value = void 0, error = void 0, succeeded = true;
            if (hasCallback) {
                try {
                    value = callback(detail);
                }
                catch (e) {
                    succeeded = false;
                    error = e;
                }
                if (promise === value) {
                    reject(promise, cannotReturnOwn());
                    return;
                }
            }
            else {
                value = detail;
            }
            if (promise._state !== PENDING) {
                // noop
            }
            else if (hasCallback && succeeded) {
                resolve(promise, value);
            }
            else if (succeeded === false) {
                reject(promise, error);
            }
            else if (settled === FULFILLED) {
                fulfill(promise, value);
            }
            else if (settled === REJECTED) {
                reject(promise, value);
            }
        }
        function initializePromise(promise, resolver) {
            try {
                resolver(function resolvePromise(value) {
                    resolve(promise, value);
                }, function rejectPromise(reason) {
                    reject(promise, reason);
                });
            }
            catch (e) {
                reject(promise, e);
            }
        }
        var id = 0;
        function nextId() {
            return id++;
        }
        function makePromise(promise) {
            promise[PROMISE_ID] = id++;
            promise._state = undefined;
            promise._result = undefined;
            promise._subscribers = [];
        }
        function validationError() {
            return new Error('Array Methods must be provided an Array');
        }
        var Enumerator = function () {
            function Enumerator(Constructor, input) {
                this._instanceConstructor = Constructor;
                this.promise = new Constructor(noop);
                if (!this.promise[PROMISE_ID]) {
                    makePromise(this.promise);
                }
                if (isArray(input)) {
                    this.length = input.length;
                    this._remaining = input.length;
                    this._result = new Array(this.length);
                    if (this.length === 0) {
                        fulfill(this.promise, this._result);
                    }
                    else {
                        this.length = this.length || 0;
                        this._enumerate(input);
                        if (this._remaining === 0) {
                            fulfill(this.promise, this._result);
                        }
                    }
                }
                else {
                    reject(this.promise, validationError());
                }
            }
            Enumerator.prototype._enumerate = function _enumerate(input) {
                for (var i = 0; this._state === PENDING && i < input.length; i++) {
                    this._eachEntry(input[i], i);
                }
            };
            Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
                var c = this._instanceConstructor;
                var resolve$$1 = c.resolve;
                if (resolve$$1 === resolve$1) {
                    var _then = void 0;
                    var error = void 0;
                    var didError = false;
                    try {
                        _then = entry.then;
                    }
                    catch (e) {
                        didError = true;
                        error = e;
                    }
                    if (_then === then && entry._state !== PENDING) {
                        this._settledAt(entry._state, i, entry._result);
                    }
                    else if (typeof _then !== 'function') {
                        this._remaining--;
                        this._result[i] = entry;
                    }
                    else if (c === Promise$1) {
                        var promise = new c(noop);
                        if (didError) {
                            reject(promise, error);
                        }
                        else {
                            handleMaybeThenable(promise, entry, _then);
                        }
                        this._willSettleAt(promise, i);
                    }
                    else {
                        this._willSettleAt(new c(function (resolve$$1) {
                            return resolve$$1(entry);
                        }), i);
                    }
                }
                else {
                    this._willSettleAt(resolve$$1(entry), i);
                }
            };
            Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
                var promise = this.promise;
                if (promise._state === PENDING) {
                    this._remaining--;
                    if (state === REJECTED) {
                        reject(promise, value);
                    }
                    else {
                        this._result[i] = value;
                    }
                }
                if (this._remaining === 0) {
                    fulfill(promise, this._result);
                }
            };
            Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
                var enumerator = this;
                subscribe(promise, undefined, function (value) {
                    return enumerator._settledAt(FULFILLED, i, value);
                }, function (reason) {
                    return enumerator._settledAt(REJECTED, i, reason);
                });
            };
            return Enumerator;
        }();
        /**
          `Promise.all` accepts an array of promises, and returns a new promise which
          is fulfilled with an array of fulfillment values for the passed promises, or
          rejected with the reason of the first passed promise to be rejected. It casts all
          elements of the passed iterable to promises as it runs this algorithm.
        
          Example:
        
          ```javascript
          let promise1 = resolve(1);
          let promise2 = resolve(2);
          let promise3 = resolve(3);
          let promises = [ promise1, promise2, promise3 ];
        
          Promise.all(promises).then(function(array){
            // The array here would be [ 1, 2, 3 ];
          });
          ```
        
          If any of the `promises` given to `all` are rejected, the first promise
          that is rejected will be given as an argument to the returned promises's
          rejection handler. For example:
        
          Example:
        
          ```javascript
          let promise1 = resolve(1);
          let promise2 = reject(new Error("2"));
          let promise3 = reject(new Error("3"));
          let promises = [ promise1, promise2, promise3 ];
        
          Promise.all(promises).then(function(array){
            // Code here never runs because there are rejected promises!
          }, function(error) {
            // error.message === "2"
          });
          ```
        
          @method all
          @static
          @param {Array} entries array of promises
          @param {String} label optional string for labeling the promise.
          Useful for tooling.
          @return {Promise} promise that is fulfilled when all `promises` have been
          fulfilled, or rejected if any of them become rejected.
          @static
        */
        function all(entries) {
            return new Enumerator(this, entries).promise;
        }
        /**
          `Promise.race` returns a new promise which is settled in the same way as the
          first passed promise to settle.
        
          Example:
        
          ```javascript
          let promise1 = new Promise(function(resolve, reject){
            setTimeout(function(){
              resolve('promise 1');
            }, 200);
          });
        
          let promise2 = new Promise(function(resolve, reject){
            setTimeout(function(){
              resolve('promise 2');
            }, 100);
          });
        
          Promise.race([promise1, promise2]).then(function(result){
            // result === 'promise 2' because it was resolved before promise1
            // was resolved.
          });
          ```
        
          `Promise.race` is deterministic in that only the state of the first
          settled promise matters. For example, even if other promises given to the
          `promises` array argument are resolved, but the first settled promise has
          become rejected before the other promises became fulfilled, the returned
          promise will become rejected:
        
          ```javascript
          let promise1 = new Promise(function(resolve, reject){
            setTimeout(function(){
              resolve('promise 1');
            }, 200);
          });
        
          let promise2 = new Promise(function(resolve, reject){
            setTimeout(function(){
              reject(new Error('promise 2'));
            }, 100);
          });
        
          Promise.race([promise1, promise2]).then(function(result){
            // Code here never runs
          }, function(reason){
            // reason.message === 'promise 2' because promise 2 became rejected before
            // promise 1 became fulfilled
          });
          ```
        
          An example real-world use case is implementing timeouts:
        
          ```javascript
          Promise.race([ajax('foo.json'), timeout(5000)])
          ```
        
          @method race
          @static
          @param {Array} promises array of promises to observe
          Useful for tooling.
          @return {Promise} a promise which settles in the same way as the first passed
          promise to settle.
        */
        function race(entries) {
            /*jshint validthis:true */
            var Constructor = this;
            if (!isArray(entries)) {
                return new Constructor(function (_, reject) {
                    return reject(new TypeError('You must pass an array to race.'));
                });
            }
            else {
                return new Constructor(function (resolve, reject) {
                    var length = entries.length;
                    for (var i = 0; i < length; i++) {
                        Constructor.resolve(entries[i]).then(resolve, reject);
                    }
                });
            }
        }
        /**
          `Promise.reject` returns a promise rejected with the passed `reason`.
          It is shorthand for the following:
        
          ```javascript
          let promise = new Promise(function(resolve, reject){
            reject(new Error('WHOOPS'));
          });
        
          promise.then(function(value){
            // Code here doesn't run because the promise is rejected!
          }, function(reason){
            // reason.message === 'WHOOPS'
          });
          ```
        
          Instead of writing the above, your code now simply becomes the following:
        
          ```javascript
          let promise = Promise.reject(new Error('WHOOPS'));
        
          promise.then(function(value){
            // Code here doesn't run because the promise is rejected!
          }, function(reason){
            // reason.message === 'WHOOPS'
          });
          ```
        
          @method reject
          @static
          @param {Any} reason value that the returned promise will be rejected with.
          Useful for tooling.
          @return {Promise} a promise rejected with the given `reason`.
        */
        function reject$1(reason) {
            /*jshint validthis:true */
            var Constructor = this;
            var promise = new Constructor(noop);
            reject(promise, reason);
            return promise;
        }
        function needsResolver() {
            throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
        }
        function needsNew() {
            throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
        }
        /**
          Promise objects represent the eventual result of an asynchronous operation. The
          primary way of interacting with a promise is through its `then` method, which
          registers callbacks to receive either a promise's eventual value or the reason
          why the promise cannot be fulfilled.
        
          Terminology
          -----------
        
          - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
          - `thenable` is an object or function that defines a `then` method.
          - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
          - `exception` is a value that is thrown using the throw statement.
          - `reason` is a value that indicates why a promise was rejected.
          - `settled` the final resting state of a promise, fulfilled or rejected.
        
          A promise can be in one of three states: pending, fulfilled, or rejected.
        
          Promises that are fulfilled have a fulfillment value and are in the fulfilled
          state.  Promises that are rejected have a rejection reason and are in the
          rejected state.  A fulfillment value is never a thenable.
        
          Promises can also be said to *resolve* a value.  If this value is also a
          promise, then the original promise's settled state will match the value's
          settled state.  So a promise that *resolves* a promise that rejects will
          itself reject, and a promise that *resolves* a promise that fulfills will
          itself fulfill.
        
        
          Basic Usage:
          ------------
        
          ```js
          let promise = new Promise(function(resolve, reject) {
            // on success
            resolve(value);
        
            // on failure
            reject(reason);
          });
        
          promise.then(function(value) {
            // on fulfillment
          }, function(reason) {
            // on rejection
          });
          ```
        
          Advanced Usage:
          ---------------
        
          Promises shine when abstracting away asynchronous interactions such as
          `XMLHttpRequest`s.
        
          ```js
          function getJSON(url) {
            return new Promise(function(resolve, reject){
              let xhr = new XMLHttpRequest();
        
              xhr.open('GET', url);
              xhr.onreadystatechange = handler;
              xhr.responseType = 'json';
              xhr.setRequestHeader('Accept', 'application/json');
              xhr.send();
        
              function handler() {
                if (this.readyState === this.DONE) {
                  if (this.status === 200) {
                    resolve(this.response);
                  } else {
                    reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
                  }
                }
              };
            });
          }
        
          getJSON('/posts.json').then(function(json) {
            // on fulfillment
          }, function(reason) {
            // on rejection
          });
          ```
        
          Unlike callbacks, promises are great composable primitives.
        
          ```js
          Promise.all([
            getJSON('/posts'),
            getJSON('/comments')
          ]).then(function(values){
            values[0] // => postsJSON
            values[1] // => commentsJSON
        
            return values;
          });
          ```
        
          @class Promise
          @param {Function} resolver
          Useful for tooling.
          @constructor
        */
        var Promise$1 = function () {
            function Promise(resolver) {
                this[PROMISE_ID] = nextId();
                this._result = this._state = undefined;
                this._subscribers = [];
                if (noop !== resolver) {
                    typeof resolver !== 'function' && needsResolver();
                    this instanceof Promise ? initializePromise(this, resolver) : needsNew();
                }
            }
            /**
            The primary way of interacting with a promise is through its `then` method,
            which registers callbacks to receive either a promise's eventual value or the
            reason why the promise cannot be fulfilled.
             ```js
            findUser().then(function(user){
              // user is available
            }, function(reason){
              // user is unavailable, and you are given the reason why
            });
            ```
             Chaining
            --------
             The return value of `then` is itself a promise.  This second, 'downstream'
            promise is resolved with the return value of the first promise's fulfillment
            or rejection handler, or rejected if the handler throws an exception.
             ```js
            findUser().then(function (user) {
              return user.name;
            }, function (reason) {
              return 'default name';
            }).then(function (userName) {
              // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
              // will be `'default name'`
            });
             findUser().then(function (user) {
              throw new Error('Found user, but still unhappy');
            }, function (reason) {
              throw new Error('`findUser` rejected and we're unhappy');
            }).then(function (value) {
              // never reached
            }, function (reason) {
              // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
              // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
            });
            ```
            If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
             ```js
            findUser().then(function (user) {
              throw new PedagogicalException('Upstream error');
            }).then(function (value) {
              // never reached
            }).then(function (value) {
              // never reached
            }, function (reason) {
              // The `PedgagocialException` is propagated all the way down to here
            });
            ```
             Assimilation
            ------------
             Sometimes the value you want to propagate to a downstream promise can only be
            retrieved asynchronously. This can be achieved by returning a promise in the
            fulfillment or rejection handler. The downstream promise will then be pending
            until the returned promise is settled. This is called *assimilation*.
             ```js
            findUser().then(function (user) {
              return findCommentsByAuthor(user);
            }).then(function (comments) {
              // The user's comments are now available
            });
            ```
             If the assimliated promise rejects, then the downstream promise will also reject.
             ```js
            findUser().then(function (user) {
              return findCommentsByAuthor(user);
            }).then(function (comments) {
              // If `findCommentsByAuthor` fulfills, we'll have the value here
            }, function (reason) {
              // If `findCommentsByAuthor` rejects, we'll have the reason here
            });
            ```
             Simple Example
            --------------
             Synchronous Example
             ```javascript
            let result;
             try {
              result = findResult();
              // success
            } catch(reason) {
              // failure
            }
            ```
             Errback Example
             ```js
            findResult(function(result, err){
              if (err) {
                // failure
              } else {
                // success
              }
            });
            ```
             Promise Example;
             ```javascript
            findResult().then(function(result){
              // success
            }, function(reason){
              // failure
            });
            ```
             Advanced Example
            --------------
             Synchronous Example
             ```javascript
            let author, books;
             try {
              author = findAuthor();
              books  = findBooksByAuthor(author);
              // success
            } catch(reason) {
              // failure
            }
            ```
             Errback Example
             ```js
             function foundBooks(books) {
             }
             function failure(reason) {
             }
             findAuthor(function(author, err){
              if (err) {
                failure(err);
                // failure
              } else {
                try {
                  findBoooksByAuthor(author, function(books, err) {
                    if (err) {
                      failure(err);
                    } else {
                      try {
                        foundBooks(books);
                      } catch(reason) {
                        failure(reason);
                      }
                    }
                  });
                } catch(error) {
                  failure(err);
                }
                // success
              }
            });
            ```
             Promise Example;
             ```javascript
            findAuthor().
              then(findBooksByAuthor).
              then(function(books){
                // found books
            }).catch(function(reason){
              // something went wrong
            });
            ```
             @method then
            @param {Function} onFulfilled
            @param {Function} onRejected
            Useful for tooling.
            @return {Promise}
            */
            /**
            `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
            as the catch block of a try/catch statement.
            ```js
            function findAuthor(){
            throw new Error('couldn't find that author');
            }
            // synchronous
            try {
            findAuthor();
            } catch(reason) {
            // something went wrong
            }
            // async with promises
            findAuthor().catch(function(reason){
            // something went wrong
            });
            ```
            @method catch
            @param {Function} onRejection
            Useful for tooling.
            @return {Promise}
            */
            Promise.prototype.catch = function _catch(onRejection) {
                return this.then(null, onRejection);
            };
            /**
              `finally` will be invoked regardless of the promise's fate just as native
              try/catch/finally behaves
            
              Synchronous example:
            
              ```js
              findAuthor() {
                if (Math.random() > 0.5) {
                  throw new Error();
                }
                return new Author();
              }
            
              try {
                return findAuthor(); // succeed or fail
              } catch(error) {
                return findOtherAuther();
              } finally {
                // always runs
                // doesn't affect the return value
              }
              ```
            
              Asynchronous example:
            
              ```js
              findAuthor().catch(function(reason){
                return findOtherAuther();
              }).finally(function(){
                // author was either found, or not
              });
              ```
            
              @method finally
              @param {Function} callback
              @return {Promise}
            */
            Promise.prototype.finally = function _finally(callback) {
                var promise = this;
                var constructor = promise.constructor;
                if (isFunction(callback)) {
                    return promise.then(function (value) {
                        return constructor.resolve(callback()).then(function () {
                            return value;
                        });
                    }, function (reason) {
                        return constructor.resolve(callback()).then(function () {
                            throw reason;
                        });
                    });
                }
                return promise.then(callback, callback);
            };
            return Promise;
        }();
        Promise$1.prototype.then = then;
        Promise$1.all = all;
        Promise$1.race = race;
        Promise$1.resolve = resolve$1;
        Promise$1.reject = reject$1;
        Promise$1._setScheduler = setScheduler;
        Promise$1._setAsap = setAsap;
        Promise$1._asap = asap;
        /*global self*/
        function polyfill() {
            var local = void 0;
            if (typeof global !== 'undefined') {
                local = global;
            }
            else if (typeof self !== 'undefined') {
                local = self;
            }
            else {
                try {
                    local = Function('return this')();
                }
                catch (e) {
                    throw new Error('polyfill failed because global object is unavailable in this environment');
                }
            }
            var P = local.Promise;
            if (P) {
                var promiseToString = null;
                try {
                    promiseToString = Object.prototype.toString.call(P.resolve());
                }
                catch (e) {
                    // silently ignored
                }
                if (promiseToString === '[object Promise]' && !P.cast) {
                    return;
                }
            }
            local.Promise = Promise$1;
        }
        // Strange compat..
        Promise$1.polyfill = polyfill;
        Promise$1.Promise = Promise$1;
        return Promise$1;
    })));
},
/* core/util/arrayable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var math_1 = require(117) /* ./math */;
    function is_empty(array) {
        return array.length == 0;
    }
    exports.is_empty = is_empty;
    function copy(array) {
        if (Array.isArray(array))
            return array.slice();
        else
            return new array.constructor(array);
    }
    exports.copy = copy;
    function splice(array, start, k) {
        var e_1, _a;
        var items = [];
        for (var _i = 3; _i < arguments.length; _i++) {
            items[_i - 3] = arguments[_i];
        }
        var len = array.length;
        if (start < 0)
            start += len;
        if (start < 0)
            start = 0;
        else if (start > len)
            start = len;
        if (k == null || k > len - start)
            k = len - start;
        else if (k < 0)
            k = 0;
        var n = len - k + items.length;
        var result = new array.constructor(n);
        var i = 0;
        for (; i < start; i++) {
            result[i] = array[i];
        }
        try {
            for (var items_1 = (0, tslib_1.__values)(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
                var item = items_1_1.value;
                result[i++] = item;
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (items_1_1 && !items_1_1.done && (_a = items_1.return))
                    _a.call(items_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        for (var j = start + k; j < len; j++) {
            result[i++] = array[j];
        }
        return result;
    }
    exports.splice = splice;
    function head(array, n) {
        return splice(array, n, array.length - n);
    }
    exports.head = head;
    function insert(array, item, i) {
        return splice(array, i, 0, item);
    }
    exports.insert = insert;
    function append(array, item) {
        return splice(array, array.length, 0, item);
    }
    exports.append = append;
    function prepend(array, item) {
        return splice(array, 0, 0, item);
    }
    exports.prepend = prepend;
    function indexOf(array, item) {
        for (var i = 0, n = array.length; i < n; i++) {
            if (array[i] === item)
                return i;
        }
        return -1;
    }
    exports.indexOf = indexOf;
    function subselect(array, indices) {
        var n = indices.length;
        var result = new array.constructor(n);
        for (var i = 0; i < n; i++) {
            result[i] = array[indices[i]];
        }
        return result;
    }
    exports.subselect = subselect;
    function mul(array, coeff, output) {
        var n = array.length;
        var result = output !== null && output !== void 0 ? output : new array.constructor(n);
        for (var i = 0; i < n; i++) {
            result[i] = array[i] * coeff;
        }
        return result;
    }
    exports.mul = mul;
    function map(array, fn) {
        var n = array.length;
        var result = new array.constructor(n);
        for (var i = 0; i < n; i++) {
            result[i] = fn(array[i], i, array);
        }
        return result;
    }
    exports.map = map;
    function inplace_map(array, fn, output) {
        var n = array.length;
        var result = output !== null && output !== void 0 ? output : array;
        for (var i = 0; i < n; i++) {
            result[i] = fn(array[i], i);
        }
    }
    exports.inplace_map = inplace_map;
    function filter(array, pred) {
        var n = array.length;
        var result = new array.constructor(n);
        var k = 0;
        for (var i = 0; i < n; i++) {
            var value = array[i];
            if (pred(value, i, array))
                result[k++] = value;
        }
        return head(result, k);
    }
    exports.filter = filter;
    function reduce(array, fn, initial) {
        var n = array.length;
        if (initial === undefined && n == 0)
            throw new Error("can't reduce an empty array without an initial value");
        var value;
        var i;
        if (initial === undefined) {
            value = array[0];
            i = 1;
        }
        else {
            value = initial;
            i = 0;
        }
        for (; i < n; i++) {
            value = fn(value, array[i], i, array);
        }
        return value;
    }
    exports.reduce = reduce;
    function min(array) {
        var value;
        var result = Infinity;
        for (var i = 0, length = array.length; i < length; i++) {
            value = array[i];
            if (!isNaN(value) && value < result) {
                result = value;
            }
        }
        return result;
    }
    exports.min = min;
    function max(array) {
        var value;
        var result = -Infinity;
        for (var i = 0, length = array.length; i < length; i++) {
            value = array[i];
            if (!isNaN(value) && value > result) {
                result = value;
            }
        }
        return result;
    }
    exports.max = max;
    function minmax(array) {
        var value;
        var min = +Infinity;
        var max = -Infinity;
        for (var i = 0, length = array.length; i < length; i++) {
            value = array[i];
            if (!isNaN(value)) {
                if (value < min) {
                    min = value;
                }
                if (value > max) {
                    max = value;
                }
            }
        }
        return [min, max];
    }
    exports.minmax = minmax;
    function minmax2(arr, brr) {
        var a;
        var b;
        var a_min = +Infinity;
        var a_max = -Infinity;
        var b_min = +Infinity;
        var b_max = -Infinity;
        var n = Math.min(arr.length, brr.length);
        for (var i = 0; i < n; i++) {
            a = arr[i];
            b = brr[i];
            if (!isNaN(a) && !isNaN(b)) {
                if (a < a_min)
                    a_min = a;
                if (a > a_max)
                    a_max = a;
                if (b < b_min)
                    b_min = b;
                if (b > b_max)
                    b_max = b;
            }
        }
        return [a_min, a_max, b_min, b_max];
    }
    exports.minmax2 = minmax2;
    function min_by(array, key) {
        if (array.length == 0)
            throw new Error("min_by() called with an empty array");
        var result = array[0];
        var resultComputed = key(result);
        for (var i = 1, length = array.length; i < length; i++) {
            var value = array[i];
            var computed = key(value);
            if (computed < resultComputed) {
                result = value;
                resultComputed = computed;
            }
        }
        return result;
    }
    exports.min_by = min_by;
    function max_by(array, key) {
        if (array.length == 0)
            throw new Error("max_by() called with an empty array");
        var result = array[0];
        var resultComputed = key(result);
        for (var i = 1, length = array.length; i < length; i++) {
            var value = array[i];
            var computed = key(value);
            if (computed > resultComputed) {
                result = value;
                resultComputed = computed;
            }
        }
        return result;
    }
    exports.max_by = max_by;
    function sum(array) {
        var result = 0;
        for (var i = 0, n = array.length; i < n; i++) {
            result += array[i];
        }
        return result;
    }
    exports.sum = sum;
    function cumsum(array) {
        var result = new array.constructor(array.length);
        reduce(array, function (a, b, i) { return result[i] = a + b; }, 0);
        return result;
    }
    exports.cumsum = cumsum;
    function every(array, predicate) {
        for (var i = 0, length = array.length; i < length; i++) {
            if (!predicate(array[i]))
                return false;
        }
        return true;
    }
    exports.every = every;
    function some(array, predicate) {
        for (var i = 0, length = array.length; i < length; i++) {
            if (predicate(array[i]))
                return true;
        }
        return false;
    }
    exports.some = some;
    function index_of(array, value) {
        for (var i = 0, length = array.length; i < length; i++) {
            if (array[i] === value)
                return i;
        }
        return -1;
    }
    exports.index_of = index_of;
    function _find_index(dir) {
        return function (array, predicate) {
            var length = array.length;
            var index = dir > 0 ? 0 : length - 1;
            for (; index >= 0 && index < length; index += dir) {
                if (predicate(array[index]))
                    return index;
            }
            return -1;
        };
    }
    exports.find_index = _find_index(1);
    exports.find_last_index = _find_index(-1);
    function find(array, predicate) {
        var index = (0, exports.find_index)(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    exports.find = find;
    function find_last(array, predicate) {
        var index = (0, exports.find_last_index)(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    exports.find_last = find_last;
    function sorted_index(array, value) {
        var low = 0;
        var high = array.length;
        while (low < high) {
            var mid = Math.floor((low + high) / 2);
            if (array[mid] < value)
                low = mid + 1;
            else
                high = mid;
        }
        return low;
    }
    exports.sorted_index = sorted_index;
    function bin_counts(data, bin_edges) {
        var nbins = bin_edges.length - 1;
        var counts = Array(nbins).fill(0);
        for (var i = 0; i < data.length; i++) {
            var sample = data[i];
            var index = sorted_index(bin_edges, sample);
            var bin = (0, math_1.clamp)(index - 1, 0, nbins - 1);
            counts[bin] += 1;
        }
        return counts;
    }
    exports.bin_counts = bin_counts;
    function interpolate(points, x_values, y_values) {
        // Implementation ported from np.interp
        var n = points.length;
        var results = new Array(n);
        for (var i = 0; i < n; i++) {
            var point = points[i];
            if (isNaN(point)) {
                results[i] = point;
                continue;
            }
            var index = left_edge_index(point, x_values);
            if (index == -1)
                results[i] = y_values[0];
            else if (index == x_values.length)
                results[i] = y_values[y_values.length - 1];
            else if (index == x_values.length - 1 || x_values[index] == point) {
                results[i] = y_values[index];
            }
            else {
                var x0 = x_values[index];
                var y0 = y_values[index];
                var x1 = x_values[index + 1];
                var y1 = y_values[index + 1];
                results[i] = lerp(point, x0, y0, x1, y1);
            }
        }
        return results;
    }
    exports.interpolate = interpolate;
    function lerp(x, x0, y0, x1, y1) {
        var slope = (y1 - y0) / (x1 - x0);
        var res = slope * (x - x0) + y0;
        if (!isFinite(res)) {
            res = slope * (x - x1) + y1;
            if (!isFinite(res) && (y0 == y1))
                res = y0;
        }
        return res;
    }
    function left_edge_index(point, intervals) {
        if (point < intervals[0])
            return -1;
        if (point > intervals[intervals.length - 1])
            return intervals.length;
        var leftEdgeIndex = 0;
        var rightEdgeIndex = intervals.length - 1;
        while (rightEdgeIndex - leftEdgeIndex != 1) {
            var indexOfNumberToCompare = leftEdgeIndex + Math.floor((rightEdgeIndex - leftEdgeIndex) / 2);
            if (point >= intervals[indexOfNumberToCompare])
                leftEdgeIndex = indexOfNumberToCompare;
            else
                rightEdgeIndex = indexOfNumberToCompare;
        }
        return leftEdgeIndex;
    }
    exports.left_edge_index = left_edge_index;
    function norm(array, start, end) {
        var span = end - start;
        return map(array, function (x) { return (x - start) / span; });
    }
    exports.norm = norm;
},
/* core/util/math.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var PI = Math.PI;
    function angle_norm(angle) {
        if (angle == 0) {
            return 0;
        }
        while (angle <= 0) {
            angle += 2 * PI;
        }
        while (angle > 2 * PI) {
            angle -= 2 * PI;
        }
        return angle;
    }
    exports.angle_norm = angle_norm;
    function angle_dist(lhs, rhs) {
        return angle_norm(lhs - rhs);
    }
    exports.angle_dist = angle_dist;
    function angle_between(mid, lhs, rhs, anticlock) {
        if (anticlock === void 0) {
            anticlock = false;
        }
        var d = angle_dist(lhs, rhs);
        if (d == 0)
            return false;
        if (d == 2 * PI)
            return true;
        var norm_mid = angle_norm(mid);
        var cond = angle_dist(lhs, norm_mid) <= d && angle_dist(norm_mid, rhs) <= d;
        return !anticlock ? cond : !cond;
    }
    exports.angle_between = angle_between;
    function random() {
        return Math.random();
    }
    exports.random = random;
    function randomIn(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        return min + Math.floor(Math.random() * (max - min + 1));
    }
    exports.randomIn = randomIn;
    function atan2(start, end) {
        /*
         * Calculate the angle between a line containing start and end points (composed
         * of [x, y] arrays) and the positive x-axis.
         */
        return Math.atan2(end[1] - start[1], end[0] - start[0]);
    }
    exports.atan2 = atan2;
    function radians(degrees) {
        return degrees * (PI / 180);
    }
    exports.radians = radians;
    function degrees(radians) {
        return radians / (PI / 180);
    }
    exports.degrees = degrees;
    function resolve_angle(angle, units) {
        /** Convert CCW angle with units to CW radians (canvas). */
        return -to_radians_coeff(units) * angle;
    }
    exports.resolve_angle = resolve_angle;
    function to_radians_coeff(units) {
        switch (units) {
            case "deg": return PI / 180;
            case "rad": return 1;
            case "grad": return PI / 200;
            case "turn": return 2 * PI;
        }
    }
    exports.to_radians_coeff = to_radians_coeff;
    // http://www2.econ.osaka-u.ac.jp/~tanizaki/class/2013/econome3/13.pdf (Page 432)
    function rnorm(mu, sigma) {
        // Generate a random normal with a mean of 0 and a sigma of 1
        var r1;
        var r2;
        while (true) {
            r1 = random();
            r2 = random();
            r2 = (2 * r2 - 1) * Math.sqrt(2 * (1 / Math.E));
            if (-4 * r1 * r1 * Math.log(r1) >= r2 * r2)
                break;
        }
        var rn = r2 / r1;
        // Transform the standard normal to meet the characteristics that we want (mu, sigma)
        rn = mu + sigma * rn;
        return rn;
    }
    exports.rnorm = rnorm;
    function clamp(val, min, max) {
        return val < min ? min : (val > max ? max : val);
    }
    exports.clamp = clamp;
    function log(x, base) {
        if (base === void 0) {
            base = Math.E;
        }
        return Math.log(x) / Math.log(base);
    }
    exports.log = log;
},
/* main.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    (0, tslib_1.__exportStar)(require(119) /* ./index */, exports);
},
/* index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var version_1 = require(120) /* ./version */;
    __esExport("version", version_1.version);
    var embed_1 = require(121) /* ./embed */;
    __esExport("index", embed_1.index);
    exports.embed = (0, tslib_1.__importStar)(require(121) /* ./embed */);
    exports.protocol = (0, tslib_1.__importStar)(require(521) /* ./protocol */);
    exports._testing = (0, tslib_1.__importStar)(require(522) /* ./testing */);
    var logging_1 = require(134) /* ./core/logging */;
    __esExport("logger", logging_1.logger);
    __esExport("set_log_level", logging_1.set_log_level);
    var settings_1 = require(143) /* ./core/settings */;
    __esExport("settings", settings_1.settings);
    var base_1 = require(124) /* ./base */;
    __esExport("Models", base_1.Models);
    var document_1 = require(122) /* ./document */;
    __esExport("documents", document_1.documents);
    var safely_1 = require(523) /* ./safely */;
    __esExport("safely", safely_1.safely);
},
/* version.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.version = "2.4.1";
},
/* embed/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var document_1 = require(122) /* ../document */;
    var logging_1 = require(134) /* ../core/logging */;
    var string_1 = require(149) /* ../core/util/string */;
    var object_1 = require(128) /* ../core/util/object */;
    var types_1 = require(125) /* ../core/util/types */;
    var defer_1 = require(131) /* ../core/util/defer */;
    var standalone_1 = require(512) /* ./standalone */;
    var server_1 = require(514) /* ./server */;
    var dom_1 = require(513) /* ./dom */;
    var standalone_2 = require(512) /* ./standalone */;
    __esExport("add_document_standalone", standalone_2.add_document_standalone);
    __esExport("index", standalone_2.index);
    var server_2 = require(514) /* ./server */;
    __esExport("add_document_from_session", server_2.add_document_from_session);
    var notebook_1 = require(519) /* ./notebook */;
    __esExport("embed_items_notebook", notebook_1.embed_items_notebook);
    __esExport("kernels", notebook_1.kernels);
    var dom_2 = require(513) /* ./dom */;
    __esExport("BOKEH_ROOT", dom_2.BOKEH_ROOT);
    function embed_item(item, target_id) {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var docs_json, doc_id, element, roots, render_item, _a, views;
            var _b;
            return (0, tslib_1.__generator)(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        docs_json = {};
                        doc_id = (0, string_1.uuid4)();
                        docs_json[doc_id] = item.doc;
                        if (target_id == null)
                            target_id = item.target_id;
                        element = document.getElementById(target_id);
                        if (element != null)
                            element.classList.add(dom_1.BOKEH_ROOT);
                        roots = (_b = {}, _b[item.root_id] = target_id, _b);
                        render_item = { roots: roots, root_ids: [item.root_id], docid: doc_id };
                        return [4 /*yield*/, (0, defer_1.defer)()];
                    case 1:
                        _c.sent();
                        return [4 /*yield*/, _embed_items(docs_json, [render_item])];
                    case 2:
                        _a = tslib_1.__read.apply(void 0, [_c.sent(), 1]), views = _a[0];
                        return [2 /*return*/, views];
                }
            });
        });
    }
    exports.embed_item = embed_item;
    // TODO (bev) this is currently clunky. Standalone embeds only provide
    // the first two args, whereas server provide the app_app, and *may* prove and
    // absolute_url as well if non-relative links are needed for resources. This function
    // should probably be split in to two pieces to reflect the different usage patterns
    function embed_items(docs_json, render_items, app_path, absolute_url) {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, (0, defer_1.defer)()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, _embed_items(docs_json, render_items, app_path, absolute_url)];
                }
            });
        });
    }
    exports.embed_items = embed_items;
    function _embed_items(docs_json, render_items, app_path, absolute_url) {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var docs, _a, _b, _c, docid, doc_json, views, render_items_1, render_items_1_1, item, element, roots, _d, _e, websocket_url, _f, _g, error_1, e_1_1;
            var e_2, _h, e_1, _j;
            return (0, tslib_1.__generator)(this, function (_k) {
                switch (_k.label) {
                    case 0:
                        if ((0, types_1.isString)(docs_json))
                            docs_json = JSON.parse((0, string_1.unescape)(docs_json));
                        docs = {};
                        try {
                            for (_a = (0, tslib_1.__values)((0, object_1.entries)(docs_json)), _b = _a.next(); !_b.done; _b = _a.next()) {
                                _c = (0, tslib_1.__read)(_b.value, 2), docid = _c[0], doc_json = _c[1];
                                docs[docid] = document_1.Document.from_json(doc_json);
                            }
                        }
                        catch (e_2_1) {
                            e_2 = { error: e_2_1 };
                        }
                        finally {
                            try {
                                if (_b && !_b.done && (_h = _a.return))
                                    _h.call(_a);
                            }
                            finally {
                                if (e_2)
                                    throw e_2.error;
                            }
                        }
                        views = [];
                        _k.label = 1;
                    case 1:
                        _k.trys.push([1, 12, 13, 14]);
                        render_items_1 = (0, tslib_1.__values)(render_items), render_items_1_1 = render_items_1.next();
                        _k.label = 2;
                    case 2:
                        if (!!render_items_1_1.done)
                            return [3 /*break*/, 11];
                        item = render_items_1_1.value;
                        element = (0, dom_1._resolve_element)(item);
                        roots = (0, dom_1._resolve_root_elements)(item);
                        if (!(item.docid != null))
                            return [3 /*break*/, 4];
                        _e = (_d = views).push;
                        return [4 /*yield*/, (0, standalone_1.add_document_standalone)(docs[item.docid], element, roots, item.use_for_title)];
                    case 3:
                        _e.apply(_d, [_k.sent()]);
                        return [3 /*break*/, 10];
                    case 4:
                        if (!(item.token != null))
                            return [3 /*break*/, 9];
                        websocket_url = (0, server_1._get_ws_url)(app_path, absolute_url);
                        logging_1.logger.debug("embed: computed ws url: " + websocket_url);
                        _k.label = 5;
                    case 5:
                        _k.trys.push([5, 7, , 8]);
                        _g = (_f = views).push;
                        return [4 /*yield*/, (0, server_1.add_document_from_session)(websocket_url, item.token, element, roots, item.use_for_title)];
                    case 6:
                        _g.apply(_f, [_k.sent()]);
                        console.log("Bokeh items were rendered successfully");
                        return [3 /*break*/, 8];
                    case 7:
                        error_1 = _k.sent();
                        console.log("Error rendering Bokeh items:", error_1);
                        return [3 /*break*/, 8];
                    case 8: return [3 /*break*/, 10];
                    case 9: throw new Error("Error rendering Bokeh items: either 'docid' or 'token' was expected.");
                    case 10:
                        render_items_1_1 = render_items_1.next();
                        return [3 /*break*/, 2];
                    case 11: return [3 /*break*/, 14];
                    case 12:
                        e_1_1 = _k.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 14];
                    case 13:
                        try {
                            if (render_items_1_1 && !render_items_1_1.done && (_j = render_items_1.return))
                                _j.call(render_items_1);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                        return [7 /*endfinally*/];
                    case 14: return [2 /*return*/, views];
                }
            });
        });
    }
},
/* document/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    (0, tslib_1.__exportStar)(require(123) /* ./document */, exports);
    (0, tslib_1.__exportStar)(require(150) /* ./events */, exports);
},
/* document/document.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var base_1 = require(124) /* ../base */;
    var version_1 = require(120) /* ../version */;
    var logging_1 = require(134) /* ../core/logging */;
    var bokeh_events_1 = require(366) /* ../core/bokeh_events */;
    var has_props_1 = require(129) /* ../core/has_props */;
    var serializer_1 = require(145) /* ../core/serializer */;
    var signaling_1 = require(130) /* ../core/signaling */;
    var refs_1 = require(132) /* ../core/util/refs */;
    var serialization_1 = require(146) /* ../core/util/serialization */;
    var ndarray_1 = require(144) /* ../core/util/ndarray */;
    var array_1 = require(126) /* ../core/util/array */;
    var object_1 = require(128) /* ../core/util/object */;
    var sets = (0, tslib_1.__importStar)(require(192) /* ../core/util/set */);
    var eq_1 = require(141) /* ../core/util/eq */;
    var types_1 = require(125) /* ../core/util/types */;
    var layout_dom_1 = require(424) /* ../models/layouts/layout_dom */;
    var column_data_source_1 = require(190) /* ../models/sources/column_data_source */;
    var model_1 = require(168) /* ../model */;
    var defs_1 = require(511) /* ./defs */;
    var events_1 = require(150) /* ./events */;
    // Dispatches events to the subscribed models
    var EventManager = /** @class */ (function () {
        function EventManager(document) {
            this.document = document;
            this.session = null;
            this.subscribed_models = new Set();
        }
        EventManager.prototype.send_event = function (bokeh_event) {
            var event = new events_1.MessageSentEvent(this.document, "bokeh_event", bokeh_event.to_json());
            this.document._trigger_on_change(event);
        };
        EventManager.prototype.trigger = function (event) {
            var e_1, _a;
            try {
                for (var _b = (0, tslib_1.__values)(this.subscribed_models), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var model = _c.value;
                    if (event.origin != null && event.origin != model)
                        continue;
                    model._process_event(event);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        return EventManager;
    }());
    exports.EventManager = EventManager;
    EventManager.__name__ = "EventManager";
    exports.documents = [];
    exports.DEFAULT_TITLE = "Bokeh Application";
    // This class should match the API of the Python Document class
    // as much as possible.
    var Document = /** @class */ (function () {
        function Document(options) {
            var _a;
            exports.documents.push(this);
            this._init_timestamp = Date.now();
            this._resolver = (_a = options === null || options === void 0 ? void 0 : options.resolver) !== null && _a !== void 0 ? _a : new base_1.ModelResolver();
            this._title = exports.DEFAULT_TITLE;
            this._roots = [];
            this._all_models = new Map();
            this._all_models_freeze_count = 0;
            this._callbacks = new Map();
            this._message_callbacks = new Map();
            this.event_manager = new EventManager(this);
            this.idle = new signaling_1.Signal0(this, "idle");
            this._idle_roots = new WeakMap(); // TODO: WeakSet would be better
            this._interactive_timestamp = null;
            this._interactive_plot = null;
        }
        Object.defineProperty(Document.prototype, "layoutables", {
            get: function () {
                return this._roots.filter(function (root) { return root instanceof layout_dom_1.LayoutDOM; });
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Document.prototype, "is_idle", {
            get: function () {
                var e_2, _a;
                try {
                    for (var _b = (0, tslib_1.__values)(this.layoutables), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var root = _c.value;
                        if (!this._idle_roots.has(root))
                            return false;
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
                return true;
            },
            enumerable: false,
            configurable: true
        });
        Document.prototype.notify_idle = function (model) {
            this._idle_roots.set(model, true);
            if (this.is_idle) {
                logging_1.logger.info("document idle at " + (Date.now() - this._init_timestamp) + " ms");
                this.event_manager.send_event(new bokeh_events_1.DocumentReady());
                this.idle.emit();
            }
        };
        Document.prototype.clear = function () {
            this._push_all_models_freeze();
            try {
                while (this._roots.length > 0) {
                    this.remove_root(this._roots[0]);
                }
            }
            finally {
                this._pop_all_models_freeze();
            }
        };
        Document.prototype.interactive_start = function (plot, finalize) {
            if (finalize === void 0) {
                finalize = null;
            }
            if (this._interactive_plot == null) {
                this._interactive_plot = plot;
                this._interactive_plot.trigger_event(new bokeh_events_1.LODStart());
            }
            this._interactive_finalize = finalize;
            this._interactive_timestamp = Date.now();
        };
        Document.prototype.interactive_stop = function () {
            if (this._interactive_plot != null) {
                this._interactive_plot.trigger_event(new bokeh_events_1.LODEnd());
                if (this._interactive_finalize != null) {
                    this._interactive_finalize();
                }
            }
            this._interactive_plot = null;
            this._interactive_timestamp = null;
            this._interactive_finalize = null;
        };
        Document.prototype.interactive_duration = function () {
            if (this._interactive_timestamp == null)
                return -1;
            else
                return Date.now() - this._interactive_timestamp;
        };
        Document.prototype.destructively_move = function (dest_doc) {
            var e_3, _a, e_4, _b;
            if (dest_doc === this) {
                throw new Error("Attempted to overwrite a document with itself");
            }
            dest_doc.clear();
            // we have to remove ALL roots before adding any
            // to the new doc or else models referenced from multiple
            // roots could be in both docs at once, which isn't allowed.
            var roots = (0, array_1.copy)(this._roots);
            this.clear();
            try {
                for (var roots_1 = (0, tslib_1.__values)(roots), roots_1_1 = roots_1.next(); !roots_1_1.done; roots_1_1 = roots_1.next()) {
                    var root = roots_1_1.value;
                    if (root.document != null)
                        throw new Error("Somehow we didn't detach " + root);
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (roots_1_1 && !roots_1_1.done && (_a = roots_1.return))
                        _a.call(roots_1);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            if (this._all_models.size != 0) {
                throw new Error("this._all_models still had stuff in it: " + this._all_models);
            }
            try {
                for (var roots_2 = (0, tslib_1.__values)(roots), roots_2_1 = roots_2.next(); !roots_2_1.done; roots_2_1 = roots_2.next()) {
                    var root = roots_2_1.value;
                    dest_doc.add_root(root);
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (roots_2_1 && !roots_2_1.done && (_b = roots_2.return))
                        _b.call(roots_2);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            dest_doc.set_title(this._title);
        };
        // TODO other fields of doc
        Document.prototype._push_all_models_freeze = function () {
            this._all_models_freeze_count += 1;
        };
        Document.prototype._pop_all_models_freeze = function () {
            this._all_models_freeze_count -= 1;
            if (this._all_models_freeze_count === 0) {
                this._recompute_all_models();
            }
        };
        /*protected*/ Document.prototype._invalidate_all_models = function () {
            logging_1.logger.debug("invalidating document models");
            // if freeze count is > 0, we'll recompute on unfreeze
            if (this._all_models_freeze_count === 0) {
                this._recompute_all_models();
            }
        };
        Document.prototype._recompute_all_models = function () {
            var e_5, _a, e_6, _b, e_7, _c, e_8, _d;
            var new_all_models_set = new Set();
            try {
                for (var _e = (0, tslib_1.__values)(this._roots), _f = _e.next(); !_f.done; _f = _e.next()) {
                    var r = _f.value;
                    new_all_models_set = sets.union(new_all_models_set, r.references());
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_f && !_f.done && (_a = _e.return))
                        _a.call(_e);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            var old_all_models_set = new Set(this._all_models.values());
            var to_detach = sets.difference(old_all_models_set, new_all_models_set);
            var to_attach = sets.difference(new_all_models_set, old_all_models_set);
            var recomputed = new Map();
            try {
                for (var new_all_models_set_1 = (0, tslib_1.__values)(new_all_models_set), new_all_models_set_1_1 = new_all_models_set_1.next(); !new_all_models_set_1_1.done; new_all_models_set_1_1 = new_all_models_set_1.next()) {
                    var model = new_all_models_set_1_1.value;
                    recomputed.set(model.id, model);
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (new_all_models_set_1_1 && !new_all_models_set_1_1.done && (_b = new_all_models_set_1.return))
                        _b.call(new_all_models_set_1);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            try {
                for (var to_detach_1 = (0, tslib_1.__values)(to_detach), to_detach_1_1 = to_detach_1.next(); !to_detach_1_1.done; to_detach_1_1 = to_detach_1.next()) {
                    var d = to_detach_1_1.value;
                    d.detach_document();
                }
            }
            catch (e_7_1) {
                e_7 = { error: e_7_1 };
            }
            finally {
                try {
                    if (to_detach_1_1 && !to_detach_1_1.done && (_c = to_detach_1.return))
                        _c.call(to_detach_1);
                }
                finally {
                    if (e_7)
                        throw e_7.error;
                }
            }
            try {
                for (var to_attach_1 = (0, tslib_1.__values)(to_attach), to_attach_1_1 = to_attach_1.next(); !to_attach_1_1.done; to_attach_1_1 = to_attach_1.next()) {
                    var a = to_attach_1_1.value;
                    a.attach_document(this);
                }
            }
            catch (e_8_1) {
                e_8 = { error: e_8_1 };
            }
            finally {
                try {
                    if (to_attach_1_1 && !to_attach_1_1.done && (_d = to_attach_1.return))
                        _d.call(to_attach_1);
                }
                finally {
                    if (e_8)
                        throw e_8.error;
                }
            }
            this._all_models = recomputed;
        };
        Document.prototype.roots = function () {
            return this._roots;
        };
        Document.prototype.add_root = function (model, setter_id) {
            logging_1.logger.debug("Adding root: " + model);
            if ((0, array_1.includes)(this._roots, model))
                return;
            this._push_all_models_freeze();
            try {
                this._roots.push(model);
            }
            finally {
                this._pop_all_models_freeze();
            }
            this._trigger_on_change(new events_1.RootAddedEvent(this, model, setter_id));
        };
        Document.prototype.remove_root = function (model, setter_id) {
            var i = this._roots.indexOf(model);
            if (i < 0)
                return;
            this._push_all_models_freeze();
            try {
                this._roots.splice(i, 1);
            }
            finally {
                this._pop_all_models_freeze();
            }
            this._trigger_on_change(new events_1.RootRemovedEvent(this, model, setter_id));
        };
        Document.prototype.title = function () {
            return this._title;
        };
        Document.prototype.set_title = function (title, setter_id) {
            if (title !== this._title) {
                this._title = title;
                this._trigger_on_change(new events_1.TitleChangedEvent(this, title, setter_id));
            }
        };
        Document.prototype.get_model_by_id = function (model_id) {
            var _a;
            return (_a = this._all_models.get(model_id)) !== null && _a !== void 0 ? _a : null;
        };
        Document.prototype.get_model_by_name = function (name) {
            var e_9, _a;
            var found = [];
            try {
                for (var _b = (0, tslib_1.__values)(this._all_models.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var model = _c.value;
                    if (model instanceof model_1.Model && model.name == name)
                        found.push(model);
                }
            }
            catch (e_9_1) {
                e_9 = { error: e_9_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_9)
                        throw e_9.error;
                }
            }
            switch (found.length) {
                case 0:
                    return null;
                case 1:
                    return found[0];
                default:
                    throw new Error("Multiple models are named '" + name + "'");
            }
        };
        Document.prototype.on_message = function (msg_type, callback) {
            var message_callbacks = this._message_callbacks.get(msg_type);
            if (message_callbacks == null)
                this._message_callbacks.set(msg_type, new Set([callback]));
            else
                message_callbacks.add(callback);
        };
        Document.prototype.remove_on_message = function (msg_type, callback) {
            var _a;
            (_a = this._message_callbacks.get(msg_type)) === null || _a === void 0 ? void 0 : _a.delete(callback);
        };
        Document.prototype._trigger_on_message = function (msg_type, msg_data) {
            var e_10, _a;
            var message_callbacks = this._message_callbacks.get(msg_type);
            if (message_callbacks != null) {
                try {
                    for (var message_callbacks_1 = (0, tslib_1.__values)(message_callbacks), message_callbacks_1_1 = message_callbacks_1.next(); !message_callbacks_1_1.done; message_callbacks_1_1 = message_callbacks_1.next()) {
                        var cb = message_callbacks_1_1.value;
                        cb(msg_data);
                    }
                }
                catch (e_10_1) {
                    e_10 = { error: e_10_1 };
                }
                finally {
                    try {
                        if (message_callbacks_1_1 && !message_callbacks_1_1.done && (_a = message_callbacks_1.return))
                            _a.call(message_callbacks_1);
                    }
                    finally {
                        if (e_10)
                            throw e_10.error;
                    }
                }
            }
        };
        Document.prototype.on_change = function (callback, allow_batches) {
            if (allow_batches === void 0) {
                allow_batches = false;
            }
            if (!this._callbacks.has(callback)) {
                this._callbacks.set(callback, allow_batches);
            }
        };
        Document.prototype.remove_on_change = function (callback) {
            this._callbacks.delete(callback);
        };
        Document.prototype._trigger_on_change = function (event) {
            var e_11, _a, e_12, _b;
            try {
                for (var _c = (0, tslib_1.__values)(this._callbacks), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), callback = _e[0], allow_batches = _e[1];
                    if (!allow_batches && event instanceof events_1.DocumentEventBatch) {
                        try {
                            for (var _f = (e_12 = void 0, (0, tslib_1.__values)(event.events)), _g = _f.next(); !_g.done; _g = _f.next()) {
                                var ev = _g.value;
                                callback(ev);
                            }
                        }
                        catch (e_12_1) {
                            e_12 = { error: e_12_1 };
                        }
                        finally {
                            try {
                                if (_g && !_g.done && (_b = _f.return))
                                    _b.call(_f);
                            }
                            finally {
                                if (e_12)
                                    throw e_12.error;
                            }
                        }
                    }
                    else {
                        callback(event); // TODO
                    }
                }
            }
            catch (e_11_1) {
                e_11 = { error: e_11_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return))
                        _a.call(_c);
                }
                finally {
                    if (e_11)
                        throw e_11.error;
                }
            }
        };
        Document.prototype._notify_change = function (model, attr, old_value, new_value, options) {
            this._trigger_on_change(new events_1.ModelChangedEvent(this, model, attr, old_value, new_value, options === null || options === void 0 ? void 0 : options.setter_id, options === null || options === void 0 ? void 0 : options.hint));
        };
        Document._instantiate_object = function (obj_id, obj_type, obj_attrs, resolver) {
            var full_attrs = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, obj_attrs), { id: obj_id, __deferred__: true });
            var model = resolver.get(obj_type);
            return new model(full_attrs);
        };
        // given a JSON representation of all models in a graph, return a
        // dict of new model objects
        Document._instantiate_references_json = function (references_json, existing_models, resolver) {
            var e_13, _a;
            var _b;
            // Create all instances, but without setting their props
            var references = new Map();
            try {
                for (var references_json_1 = (0, tslib_1.__values)(references_json), references_json_1_1 = references_json_1.next(); !references_json_1_1.done; references_json_1_1 = references_json_1.next()) {
                    var obj = references_json_1_1.value;
                    var obj_id = obj.id;
                    var obj_type = obj.type;
                    var obj_attrs = (_b = obj.attributes) !== null && _b !== void 0 ? _b : {};
                    var instance = existing_models.get(obj_id);
                    if (instance == null) {
                        instance = Document._instantiate_object(obj_id, obj_type, obj_attrs, resolver);
                        if (obj.subtype != null)
                            instance.set_subtype(obj.subtype);
                    }
                    references.set(instance.id, instance);
                }
            }
            catch (e_13_1) {
                e_13 = { error: e_13_1 };
            }
            finally {
                try {
                    if (references_json_1_1 && !references_json_1_1.done && (_a = references_json_1.return))
                        _a.call(references_json_1);
                }
                finally {
                    if (e_13)
                        throw e_13.error;
                }
            }
            return references;
        };
        // if v looks like a ref, or a collection, resolve it, otherwise return it unchanged
        // recurse into collections but not into HasProps
        Document._resolve_refs = function (value, old_references, new_references, buffers) {
            function resolve_ref(v) {
                var _a;
                if ((0, refs_1.is_ref)(v)) {
                    var obj = (_a = old_references.get(v.id)) !== null && _a !== void 0 ? _a : new_references.get(v.id);
                    if (obj != null)
                        return obj;
                    else
                        throw new Error("reference " + JSON.stringify(v) + " isn't known (not in Document?)");
                }
                else if ((0, serialization_1.is_NDArray_ref)(v)) {
                    var _b = (0, serialization_1.decode_NDArray)(v, buffers), buffer = _b.buffer, dtype = _b.dtype, shape = _b.shape;
                    return (0, ndarray_1.ndarray)(buffer, { dtype: dtype, shape: shape });
                }
                else if ((0, types_1.isArray)(v))
                    return resolve_array(v);
                else if ((0, types_1.isPlainObject)(v))
                    return resolve_dict(v);
                else
                    return v;
            }
            function resolve_array(array) {
                var e_14, _a;
                var results = [];
                try {
                    for (var array_2 = (0, tslib_1.__values)(array), array_2_1 = array_2.next(); !array_2_1.done; array_2_1 = array_2.next()) {
                        var v = array_2_1.value;
                        results.push(resolve_ref(v));
                    }
                }
                catch (e_14_1) {
                    e_14 = { error: e_14_1 };
                }
                finally {
                    try {
                        if (array_2_1 && !array_2_1.done && (_a = array_2.return))
                            _a.call(array_2);
                    }
                    finally {
                        if (e_14)
                            throw e_14.error;
                    }
                }
                return results;
            }
            function resolve_dict(dict) {
                var e_15, _a;
                var resolved = {};
                try {
                    for (var _b = (0, tslib_1.__values)((0, object_1.entries)(dict)), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var _d = (0, tslib_1.__read)(_c.value, 2), k = _d[0], v = _d[1];
                        resolved[k] = resolve_ref(v);
                    }
                }
                catch (e_15_1) {
                    e_15 = { error: e_15_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_15)
                            throw e_15.error;
                    }
                }
                return resolved;
            }
            return resolve_ref(value);
        };
        // given a JSON representation of all models in a graph and new
        // model instances, set the properties on the models from the
        // JSON
        Document._initialize_references_json = function (references_json, old_references, new_references, buffers) {
            var e_16, _a, e_17, _b, e_18, _c;
            var to_update = new Map();
            try {
                for (var references_json_2 = (0, tslib_1.__values)(references_json), references_json_2_1 = references_json_2.next(); !references_json_2_1.done; references_json_2_1 = references_json_2.next()) {
                    var _d = references_json_2_1.value, id = _d.id, attributes = _d.attributes;
                    var is_new = !old_references.has(id);
                    var instance = is_new ? new_references.get(id) : old_references.get(id);
                    // replace references with actual instances in obj_attrs
                    var resolved_attrs = Document._resolve_refs(attributes, old_references, new_references, buffers);
                    instance.setv(resolved_attrs, { silent: true });
                    to_update.set(id, { instance: instance, is_new: is_new });
                }
            }
            catch (e_16_1) {
                e_16 = { error: e_16_1 };
            }
            finally {
                try {
                    if (references_json_2_1 && !references_json_2_1.done && (_a = references_json_2.return))
                        _a.call(references_json_2);
                }
                finally {
                    if (e_16)
                        throw e_16.error;
                }
            }
            var ordered_instances = [];
            var handled = new Set();
            function finalize_all_by_dfs(v) {
                var e_19, _a, e_20, _b, e_21, _c;
                if (v instanceof has_props_1.HasProps) {
                    // note that we ignore instances that aren't updated (not in to_update)
                    if (to_update.has(v.id) && !handled.has(v.id)) {
                        handled.add(v.id);
                        var _d = to_update.get(v.id), instance = _d.instance, is_new = _d.is_new;
                        var attributes = instance.attributes;
                        try {
                            for (var _e = (0, tslib_1.__values)((0, object_1.values)(attributes)), _f = _e.next(); !_f.done; _f = _e.next()) {
                                var value = _f.value;
                                finalize_all_by_dfs(value);
                            }
                        }
                        catch (e_19_1) {
                            e_19 = { error: e_19_1 };
                        }
                        finally {
                            try {
                                if (_f && !_f.done && (_a = _e.return))
                                    _a.call(_e);
                            }
                            finally {
                                if (e_19)
                                    throw e_19.error;
                            }
                        }
                        if (is_new) {
                            // Finalizing here just to avoid iterating
                            // over `ordered_instances` twice.
                            instance.finalize();
                            // Preserving an ordered collection of instances
                            // to avoid having to go through DFS again.
                            ordered_instances.push(instance);
                        }
                    }
                }
                else if ((0, types_1.isArray)(v)) {
                    try {
                        for (var v_1 = (0, tslib_1.__values)(v), v_1_1 = v_1.next(); !v_1_1.done; v_1_1 = v_1.next()) {
                            var e = v_1_1.value;
                            finalize_all_by_dfs(e);
                        }
                    }
                    catch (e_20_1) {
                        e_20 = { error: e_20_1 };
                    }
                    finally {
                        try {
                            if (v_1_1 && !v_1_1.done && (_b = v_1.return))
                                _b.call(v_1);
                        }
                        finally {
                            if (e_20)
                                throw e_20.error;
                        }
                    }
                }
                else if ((0, types_1.isPlainObject)(v)) {
                    try {
                        for (var _g = (0, tslib_1.__values)((0, object_1.values)(v)), _h = _g.next(); !_h.done; _h = _g.next()) {
                            var value = _h.value;
                            finalize_all_by_dfs(value);
                        }
                    }
                    catch (e_21_1) {
                        e_21 = { error: e_21_1 };
                    }
                    finally {
                        try {
                            if (_h && !_h.done && (_c = _g.return))
                                _c.call(_g);
                        }
                        finally {
                            if (e_21)
                                throw e_21.error;
                        }
                    }
                }
            }
            try {
                for (var _e = (0, tslib_1.__values)(to_update.values()), _f = _e.next(); !_f.done; _f = _e.next()) {
                    var item = _f.value;
                    finalize_all_by_dfs(item.instance);
                }
            }
            catch (e_17_1) {
                e_17 = { error: e_17_1 };
            }
            finally {
                try {
                    if (_f && !_f.done && (_b = _e.return))
                        _b.call(_e);
                }
                finally {
                    if (e_17)
                        throw e_17.error;
                }
            }
            try {
                // `connect_signals` has to be executed last because it
                // may rely on properties of dependencies that are initialized
                // only in `finalize`. It's a problem that appears when
                // there are circular references, e.g. as in
                // CDS -> CustomJS (on data change) -> GlyphRenderer (in args) -> CDS.
                for (var ordered_instances_1 = (0, tslib_1.__values)(ordered_instances), ordered_instances_1_1 = ordered_instances_1.next(); !ordered_instances_1_1.done; ordered_instances_1_1 = ordered_instances_1.next()) {
                    var instance = ordered_instances_1_1.value;
                    instance.connect_signals();
                }
            }
            catch (e_18_1) {
                e_18 = { error: e_18_1 };
            }
            finally {
                try {
                    if (ordered_instances_1_1 && !ordered_instances_1_1.done && (_c = ordered_instances_1.return))
                        _c.call(ordered_instances_1);
                }
                finally {
                    if (e_18)
                        throw e_18.error;
                }
            }
        };
        //////
        ///{{{
        Document._event_for_attribute_change = function (changed_obj, key, new_value, doc, value_refs) {
            var changed_model = doc.get_model_by_id(changed_obj.id); // XXX!
            if (!changed_model.property(key).syncable)
                return null;
            else {
                var event = {
                    kind: "ModelChanged",
                    model: { id: changed_obj.id },
                    attr: key,
                    new: new_value,
                };
                has_props_1.HasProps._json_record_references(doc, new_value, value_refs, { recursive: true });
                return event;
            }
        };
        Document._events_to_sync_objects = function (from_obj, to_obj, to_doc, value_refs) {
            var e_22, _a, e_23, _b, e_24, _c;
            var from_keys = Object.keys(from_obj.attributes); //XXX!
            var to_keys = Object.keys(to_obj.attributes); //XXX!
            var removed = (0, array_1.difference)(from_keys, to_keys);
            var added = (0, array_1.difference)(to_keys, from_keys);
            var shared = (0, array_1.intersection)(from_keys, to_keys);
            var events = [];
            try {
                for (var removed_1 = (0, tslib_1.__values)(removed), removed_1_1 = removed_1.next(); !removed_1_1.done; removed_1_1 = removed_1.next()) {
                    var key = removed_1_1.value;
                    // we don't really have a "remove" event - not sure this ever
                    // happens even. One way this could happen is if the server
                    // does include_defaults=True and we do
                    // include_defaults=false ... in that case it'd be best to
                    // just ignore this probably. Warn about it, could mean
                    // there's a bug if we don't have a key that the server sent.
                    logging_1.logger.warn("Server sent key " + key + " but we don't seem to have it in our JSON");
                }
            }
            catch (e_22_1) {
                e_22 = { error: e_22_1 };
            }
            finally {
                try {
                    if (removed_1_1 && !removed_1_1.done && (_a = removed_1.return))
                        _a.call(removed_1);
                }
                finally {
                    if (e_22)
                        throw e_22.error;
                }
            }
            try {
                for (var added_1 = (0, tslib_1.__values)(added), added_1_1 = added_1.next(); !added_1_1.done; added_1_1 = added_1.next()) {
                    var key = added_1_1.value;
                    var new_value = to_obj.attributes[key]; // XXX!
                    events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
                }
            }
            catch (e_23_1) {
                e_23 = { error: e_23_1 };
            }
            finally {
                try {
                    if (added_1_1 && !added_1_1.done && (_b = added_1.return))
                        _b.call(added_1);
                }
                finally {
                    if (e_23)
                        throw e_23.error;
                }
            }
            try {
                for (var shared_1 = (0, tslib_1.__values)(shared), shared_1_1 = shared_1.next(); !shared_1_1.done; shared_1_1 = shared_1.next()) {
                    var key = shared_1_1.value;
                    var old_value = from_obj.attributes[key]; // XXX!
                    var new_value = to_obj.attributes[key]; // XXX!
                    if (old_value == null && new_value == null) {
                    }
                    else if (old_value == null || new_value == null) {
                        events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
                    }
                    else {
                        if (!(0, eq_1.is_equal)(old_value, new_value))
                            events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
                    }
                }
            }
            catch (e_24_1) {
                e_24 = { error: e_24_1 };
            }
            finally {
                try {
                    if (shared_1_1 && !shared_1_1.done && (_c = shared_1.return))
                        _c.call(shared_1);
                }
                finally {
                    if (e_24)
                        throw e_24.error;
                }
            }
            return events.filter(function (e) { return e != null; });
        };
        // we use this to detect changes during document deserialization
        // (in model constructors and initializers)
        Document._compute_patch_since_json = function (from_json, to_doc) {
            var e_25, _a, e_26, _b, e_27, _c;
            var to_json = to_doc.to_json(false); // include_defaults=false
            function refs(json) {
                var e_28, _a;
                var result = new Map();
                try {
                    for (var _b = (0, tslib_1.__values)(json.roots.references), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var obj = _c.value;
                        result.set(obj.id, obj);
                    }
                }
                catch (e_28_1) {
                    e_28 = { error: e_28_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_28)
                            throw e_28.error;
                    }
                }
                return result;
            }
            var from_references = refs(from_json);
            var from_roots = new Map();
            var from_root_ids = [];
            try {
                for (var _d = (0, tslib_1.__values)(from_json.roots.root_ids), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var r = _e.value;
                    from_roots.set(r, from_references.get(r));
                    from_root_ids.push(r);
                }
            }
            catch (e_25_1) {
                e_25 = { error: e_25_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_a = _d.return))
                        _a.call(_d);
                }
                finally {
                    if (e_25)
                        throw e_25.error;
                }
            }
            var to_references = refs(to_json);
            var to_roots = new Map();
            var to_root_ids = [];
            try {
                for (var _f = (0, tslib_1.__values)(to_json.roots.root_ids), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var r = _g.value;
                    to_roots.set(r, to_references.get(r));
                    to_root_ids.push(r);
                }
            }
            catch (e_26_1) {
                e_26 = { error: e_26_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_b = _f.return))
                        _b.call(_f);
                }
                finally {
                    if (e_26)
                        throw e_26.error;
                }
            }
            from_root_ids.sort();
            to_root_ids.sort();
            if ((0, array_1.difference)(from_root_ids, to_root_ids).length > 0 ||
                (0, array_1.difference)(to_root_ids, from_root_ids).length > 0) {
                // this would arise if someone does add_root/remove_root during
                // document deserialization, hopefully they won't ever do so.
                throw new Error("Not implemented: computing add/remove of document roots");
            }
            var value_refs = new Set();
            var events = [];
            try {
                for (var _h = (0, tslib_1.__values)(to_doc._all_models.keys()), _j = _h.next(); !_j.done; _j = _h.next()) {
                    var id = _j.value;
                    if (from_references.has(id)) {
                        var update_model_events = Document._events_to_sync_objects(from_references.get(id), to_references.get(id), to_doc, value_refs);
                        events = events.concat(update_model_events);
                    }
                }
            }
            catch (e_27_1) {
                e_27 = { error: e_27_1 };
            }
            finally {
                try {
                    if (_j && !_j.done && (_c = _h.return))
                        _c.call(_h);
                }
                finally {
                    if (e_27)
                        throw e_27.error;
                }
            }
            var serializer = new serializer_1.Serializer({ include_defaults: false });
            serializer.to_serializable((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(value_refs), false));
            return {
                references: (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(serializer.definitions), false),
                events: events,
            };
        };
        ///}}}
        //////
        Document.prototype.to_json_string = function (include_defaults) {
            if (include_defaults === void 0) {
                include_defaults = true;
            }
            return JSON.stringify(this.to_json(include_defaults));
        };
        Document.prototype.to_json = function (include_defaults) {
            if (include_defaults === void 0) {
                include_defaults = true;
            }
            var serializer = new serializer_1.Serializer({ include_defaults: include_defaults });
            var roots = serializer.to_serializable(this._roots);
            return {
                version: version_1.version,
                title: this._title,
                roots: {
                    root_ids: roots.map(function (r) { return r.id; }),
                    references: (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(serializer.definitions), false),
                },
            };
        };
        Document.from_json_string = function (s) {
            var json = JSON.parse(s);
            return Document.from_json(json);
        };
        Document.from_json = function (json) {
            var e_29, _a;
            logging_1.logger.debug("Creating Document from JSON");
            function pyify(version) {
                return version.replace(/-(dev|rc)\./, "$1");
            }
            var py_version = json.version; // XXX!
            var is_dev = py_version.indexOf("+") !== -1 || py_version.indexOf("-") !== -1;
            var versions_string = "Library versions: JS (" + version_1.version + ") / Python (" + py_version + ")";
            if (!is_dev && pyify(version_1.version) != py_version) {
                logging_1.logger.warn("JS/Python version mismatch");
                logging_1.logger.warn(versions_string);
            }
            else
                logging_1.logger.debug(versions_string);
            var resolver = new base_1.ModelResolver();
            if (json.defs != null) {
                (0, defs_1.resolve_defs)(json.defs, resolver);
            }
            var roots_json = json.roots;
            var root_ids = roots_json.root_ids;
            var references_json = roots_json.references;
            var references = Document._instantiate_references_json(references_json, new Map(), resolver);
            Document._initialize_references_json(references_json, new Map(), references, new Map());
            var doc = new Document({ resolver: resolver });
            try {
                for (var root_ids_1 = (0, tslib_1.__values)(root_ids), root_ids_1_1 = root_ids_1.next(); !root_ids_1_1.done; root_ids_1_1 = root_ids_1.next()) {
                    var id = root_ids_1_1.value;
                    var root = references.get(id);
                    if (root != null) {
                        doc.add_root(root); // XXX: HasProps
                    }
                }
            }
            catch (e_29_1) {
                e_29 = { error: e_29_1 };
            }
            finally {
                try {
                    if (root_ids_1_1 && !root_ids_1_1.done && (_a = root_ids_1.return))
                        _a.call(root_ids_1);
                }
                finally {
                    if (e_29)
                        throw e_29.error;
                }
            }
            doc.set_title(json.title); // XXX!
            return doc;
        };
        Document.prototype.replace_with_json = function (json) {
            var replacement = Document.from_json(json);
            replacement.destructively_move(this);
        };
        /** @deprecated */
        Document.prototype.create_json_patch_string = function (events) {
            return JSON.stringify(this.create_json_patch(events));
        };
        Document.prototype.create_json_patch = function (events) {
            var e_30, _a, e_31, _b;
            try {
                for (var events_2 = (0, tslib_1.__values)(events), events_2_1 = events_2.next(); !events_2_1.done; events_2_1 = events_2.next()) {
                    var event = events_2_1.value;
                    if (event.document != this)
                        throw new Error("Cannot create a patch using events from a different document");
                }
            }
            catch (e_30_1) {
                e_30 = { error: e_30_1 };
            }
            finally {
                try {
                    if (events_2_1 && !events_2_1.done && (_a = events_2.return))
                        _a.call(events_2);
                }
                finally {
                    if (e_30)
                        throw e_30.error;
                }
            }
            var serializer = new serializer_1.Serializer();
            var events_repr = serializer.to_serializable(events);
            try {
                // TODO: We need a proper differential serializer. For now just remove known
                // definitions. We are doing this after a complete serialization, so that all
                // new objects are recorded.
                for (var _c = (0, tslib_1.__values)(this._all_models.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var model = _d.value;
                    serializer.remove_def(model);
                }
            }
            catch (e_31_1) {
                e_31 = { error: e_31_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_31)
                        throw e_31.error;
                }
            }
            return {
                events: events_repr,
                references: (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(serializer.definitions), false),
            };
        };
        Document.prototype.apply_json_patch = function (patch, buffers, setter_id) {
            var e_32, _a, e_33, _b, e_34, _c, _d;
            if (buffers === void 0) {
                buffers = new Map();
            }
            var references_json = patch.references;
            var events_json = patch.events;
            var references = Document._instantiate_references_json(references_json, this._all_models, this._resolver);
            if (!(buffers instanceof Map)) {
                buffers = new Map(buffers);
            }
            try {
                // The model being changed isn't always in references so add it in
                for (var events_json_1 = (0, tslib_1.__values)(events_json), events_json_1_1 = events_json_1.next(); !events_json_1_1.done; events_json_1_1 = events_json_1.next()) {
                    var event_json = events_json_1_1.value;
                    switch (event_json.kind) {
                        case "RootAdded":
                        case "RootRemoved":
                        case "ModelChanged": {
                            var model_id = event_json.model.id;
                            var model = this._all_models.get(model_id);
                            if (model != null) {
                                references.set(model_id, model);
                            }
                            else if (!references.has(model_id)) {
                                logging_1.logger.warn("Got an event for unknown model " + event_json.model + "\"");
                                throw new Error("event model wasn't known");
                            }
                            break;
                        }
                    }
                }
            }
            catch (e_32_1) {
                e_32 = { error: e_32_1 };
            }
            finally {
                try {
                    if (events_json_1_1 && !events_json_1_1.done && (_a = events_json_1.return))
                        _a.call(events_json_1);
                }
                finally {
                    if (e_32)
                        throw e_32.error;
                }
            }
            // split references into old and new so we know whether to initialize or update
            var old_references = new Map(this._all_models);
            var new_references = new Map();
            try {
                for (var references_1 = (0, tslib_1.__values)(references), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) {
                    var _e = (0, tslib_1.__read)(references_1_1.value, 2), id = _e[0], value = _e[1];
                    if (!old_references.has(id))
                        new_references.set(id, value);
                }
            }
            catch (e_33_1) {
                e_33 = { error: e_33_1 };
            }
            finally {
                try {
                    if (references_1_1 && !references_1_1.done && (_b = references_1.return))
                        _b.call(references_1);
                }
                finally {
                    if (e_33)
                        throw e_33.error;
                }
            }
            Document._initialize_references_json(references_json, old_references, new_references, buffers);
            try {
                for (var events_json_2 = (0, tslib_1.__values)(events_json), events_json_2_1 = events_json_2.next(); !events_json_2_1.done; events_json_2_1 = events_json_2.next()) {
                    var event_json = events_json_2_1.value;
                    switch (event_json.kind) {
                        case "MessageSent": {
                            var msg_type = event_json.msg_type, msg_data = event_json.msg_data;
                            var data = void 0;
                            if (msg_data === undefined) {
                                if (buffers.size == 1) {
                                    var _f = (0, tslib_1.__read)(buffers, 1), _g = (0, tslib_1.__read)(_f[0], 2), buffer = _g[1];
                                    data = buffer;
                                }
                                else {
                                    throw new Error("expected exactly one buffer");
                                }
                            }
                            else {
                                data = Document._resolve_refs(msg_data, old_references, new_references, buffers);
                            }
                            this._trigger_on_message(msg_type, data);
                            break;
                        }
                        case "ModelChanged": {
                            var patched_id = event_json.model.id;
                            var patched_obj = this._all_models.get(patched_id);
                            if (patched_obj == null) {
                                throw new Error("Cannot apply patch to " + patched_id + " which is not in the document");
                            }
                            var attr = event_json.attr;
                            var value = Document._resolve_refs(event_json.new, old_references, new_references, buffers);
                            patched_obj.setv((_d = {}, _d[attr] = value, _d), { setter_id: setter_id });
                            break;
                        }
                        case "ColumnDataChanged": {
                            var column_source_id = event_json.column_source.id;
                            var column_source = this._all_models.get(column_source_id);
                            if (column_source == null) {
                                throw new Error("Cannot stream to " + column_source_id + " which is not in the document");
                            }
                            var data = Document._resolve_refs(event_json.new, new Map(), new Map(), buffers);
                            if (event_json.cols != null) {
                                for (var k in column_source.data) {
                                    if (!(k in data)) {
                                        data[k] = column_source.data[k];
                                    }
                                }
                            }
                            column_source.setv({ data: data }, { setter_id: setter_id, check_eq: false });
                            break;
                        }
                        case "ColumnsStreamed": {
                            var column_source_id = event_json.column_source.id;
                            var column_source = this._all_models.get(column_source_id);
                            if (column_source == null) {
                                throw new Error("Cannot stream to " + column_source_id + " which is not in the document");
                            }
                            if (!(column_source instanceof column_data_source_1.ColumnDataSource)) {
                                throw new Error("Cannot stream to non-ColumnDataSource");
                            }
                            var data = event_json.data;
                            var rollover = event_json.rollover;
                            column_source.stream(data, rollover, setter_id);
                            break;
                        }
                        case "ColumnsPatched": {
                            var column_source_id = event_json.column_source.id;
                            var column_source = this._all_models.get(column_source_id);
                            if (column_source == null) {
                                throw new Error("Cannot patch " + column_source_id + " which is not in the document");
                            }
                            if (!(column_source instanceof column_data_source_1.ColumnDataSource)) {
                                throw new Error("Cannot patch non-ColumnDataSource");
                            }
                            var patches = event_json.patches;
                            column_source.patch(patches, setter_id);
                            break;
                        }
                        case "RootAdded": {
                            var root_id = event_json.model.id;
                            var root_obj = references.get(root_id);
                            this.add_root(root_obj, setter_id); // XXX: HasProps
                            break;
                        }
                        case "RootRemoved": {
                            var root_id = event_json.model.id;
                            var root_obj = references.get(root_id);
                            this.remove_root(root_obj, setter_id); // XXX: HasProps
                            break;
                        }
                        case "TitleChanged": {
                            this.set_title(event_json.title, setter_id);
                            break;
                        }
                        default:
                            throw new Error("Unknown patch event " + JSON.stringify(event_json));
                    }
                }
            }
            catch (e_34_1) {
                e_34 = { error: e_34_1 };
            }
            finally {
                try {
                    if (events_json_2_1 && !events_json_2_1.done && (_c = events_json_2.return))
                        _c.call(events_json_2);
                }
                finally {
                    if (e_34)
                        throw e_34.error;
                }
            }
        };
        return Document;
    }());
    exports.Document = Document;
    Document.__name__ = "Document";
},
/* base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var types_1 = require(125) /* ./core/util/types */;
    var object_1 = require(128) /* ./core/util/object */;
    var has_props_1 = require(129) /* ./core/has_props */;
    exports.overrides = {};
    var _all_models = new Map();
    exports.Models = (function (name) {
        var model = exports.Models.get(name);
        if (model != null)
            return model;
        else
            throw new Error("Model '" + name + "' does not exist. This could be due to a widget or a custom model not being registered before first usage.");
    });
    exports.Models.get = function (name) {
        var _a;
        return (_a = exports.overrides[name]) !== null && _a !== void 0 ? _a : _all_models.get(name);
    };
    exports.Models.register = function (name, model) {
        exports.overrides[name] = model;
    };
    exports.Models.unregister = function (name) {
        delete exports.overrides[name];
    };
    function is_HasProps(obj) {
        return (0, types_1.isObject)(obj) && obj.prototype instanceof has_props_1.HasProps;
    }
    exports.Models.register_models = function (models, force, errorFn) {
        var e_1, _a;
        if (force === void 0) {
            force = false;
        }
        if (models == null)
            return;
        try {
            for (var _b = (0, tslib_1.__values)((0, types_1.isArray)(models) ? models : (0, object_1.values)(models)), _c = _b.next(); !_c.done; _c = _b.next()) {
                var model = _c.value;
                if (is_HasProps(model)) {
                    var qualified = model.__qualified__;
                    if (force || !_all_models.has(qualified))
                        _all_models.set(qualified, model);
                    else if (errorFn != null)
                        errorFn(qualified);
                    else
                        console.warn("Model '" + qualified + "' was already registered");
                }
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return))
                    _a.call(_b);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
    };
    exports.register_models = exports.Models.register_models;
    exports.Models.registered_names = function () { return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(_all_models.keys()), false); };
    var ModelResolver = /** @class */ (function () {
        function ModelResolver() {
            this._known_models = new Map();
        }
        ModelResolver.prototype.get = function (name, or_else) {
            var _a;
            var model = (_a = exports.Models.get(name)) !== null && _a !== void 0 ? _a : this._known_models.get(name);
            if (model != null)
                return model;
            else if (or_else !== undefined)
                return or_else;
            else
                throw new Error("Model '" + name + "' does not exist. This could be due to a widget or a custom model not being registered before first usage.");
        };
        ModelResolver.prototype.register = function (model) {
            var name = model.__qualified__;
            if (this.get(name, null) == null)
                this._known_models.set(name, model);
            else
                console.warn("Model '" + name + "' was already registered with this resolver");
        };
        return ModelResolver;
    }());
    exports.ModelResolver = ModelResolver;
    ModelResolver.__name__ = "ModelResolver";
    // TODO: this doesn't belong here, but it's easier this way for backwards compatibility
    var AllModels = (0, tslib_1.__importStar)(require(153) /* ./models */);
    (0, exports.register_models)(AllModels);
    var DOMModels = (0, tslib_1.__importStar)(require(507) /* ./models/dom */);
    (0, exports.register_models)(DOMModels);
},
/* core/util/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    //     Underscore.js 1.8.3
    //     http://underscorejs.org
    //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
    //     Underscore may be freely distributed under the MIT license.
    var array_1 = require(126) /* ./array */;
    var toString = Object.prototype.toString;
    function isBoolean(obj) {
        return obj === true || obj === false || toString.call(obj) === "[object Boolean]";
    }
    exports.isBoolean = isBoolean;
    function isNumber(obj) {
        return toString.call(obj) === "[object Number]";
    }
    exports.isNumber = isNumber;
    function isInteger(obj) {
        return isNumber(obj) && Number.isInteger(obj);
    }
    exports.isInteger = isInteger;
    function isString(obj) {
        return toString.call(obj) === "[object String]";
    }
    exports.isString = isString;
    function isSymbol(obj) {
        return typeof obj === "symbol";
    }
    exports.isSymbol = isSymbol;
    function isPrimitive(obj) {
        return obj === null || isBoolean(obj) || isNumber(obj) || isString(obj) || isSymbol(obj);
    }
    exports.isPrimitive = isPrimitive;
    function isFunction(obj) {
        return toString.call(obj) === "[object Function]";
    }
    exports.isFunction = isFunction;
    function isArray(obj) {
        return Array.isArray(obj);
    }
    exports.isArray = isArray;
    function isArrayOf(arr, predicate) {
        return (0, array_1.every)(arr, predicate);
    }
    exports.isArrayOf = isArrayOf;
    function isArrayableOf(arr, predicate) {
        for (var i = 0, end = arr.length; i < end; i++) {
            if (!predicate(arr[i]))
                return false;
        }
        return true;
    }
    exports.isArrayableOf = isArrayableOf;
    function isTypedArray(obj) {
        return ArrayBuffer.isView(obj) && !(obj instanceof DataView);
    }
    exports.isTypedArray = isTypedArray;
    function isObject(obj) {
        var tp = typeof obj;
        return tp === "function" || tp === "object" && !!obj;
    }
    exports.isObject = isObject;
    function isPlainObject(obj) {
        return isObject(obj) && (obj.constructor == null || obj.constructor === Object);
    }
    exports.isPlainObject = isPlainObject;
    function isIterable(obj) {
        return isObject(obj) && obj[Symbol.iterator] !== undefined;
    }
    exports.isIterable = isIterable;
    function isArrayable(obj) {
        return isIterable(obj) && "length" in obj;
    }
    exports.isArrayable = isArrayable;
},
/* core/util/array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    //     Underscore.js 1.8.3
    //     http://underscorejs.org
    //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
    //     Underscore may be freely distributed under the MIT license.
    var math_1 = require(117) /* ./math */;
    var assert_1 = require(127) /* ./assert */;
    var arrayable_1 = require(116) /* ./arrayable */;
    __esExport("map", arrayable_1.map);
    __esExport("reduce", arrayable_1.reduce);
    __esExport("min", arrayable_1.min);
    __esExport("min_by", arrayable_1.min_by);
    __esExport("max", arrayable_1.max);
    __esExport("max_by", arrayable_1.max_by);
    __esExport("sum", arrayable_1.sum);
    __esExport("cumsum", arrayable_1.cumsum);
    __esExport("every", arrayable_1.every);
    __esExport("some", arrayable_1.some);
    __esExport("find", arrayable_1.find);
    __esExport("find_last", arrayable_1.find_last);
    __esExport("find_index", arrayable_1.find_index);
    __esExport("find_last_index", arrayable_1.find_last_index);
    __esExport("sorted_index", arrayable_1.sorted_index);
    __esExport("is_empty", arrayable_1.is_empty);
    var slice = Array.prototype.slice;
    function head(array) {
        return array[0];
    }
    exports.head = head;
    function tail(array) {
        return array[array.length - 1];
    }
    exports.tail = tail;
    function last(array) {
        return array[array.length - 1];
    }
    exports.last = last;
    function copy(array) {
        return slice.call(array);
    }
    exports.copy = copy;
    function concat(arrays) {
        return [].concat.apply([], (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arrays), false));
    }
    exports.concat = concat;
    function includes(array, value) {
        return array.indexOf(value) !== -1;
    }
    exports.includes = includes;
    exports.contains = includes;
    function nth(array, index) {
        return array[index >= 0 ? index : array.length + index];
    }
    exports.nth = nth;
    function zip() {
        var arrays = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            arrays[_i] = arguments[_i];
        }
        if (arrays.length == 0)
            return [];
        var n = (0, arrayable_1.min)(arrays.map(function (a) { return a.length; }));
        var k = arrays.length;
        var result = new Array(n);
        for (var i = 0; i < n; i++) {
            result[i] = new Array(k);
            for (var j = 0; j < k; j++)
                result[i][j] = arrays[j][i];
        }
        return result;
    }
    exports.zip = zip;
    function unzip(array) {
        var n = array.length;
        var k = (0, arrayable_1.min)(array.map(function (a) { return a.length; }));
        var results = Array(k);
        for (var j = 0; j < k; j++)
            results[j] = new Array(n);
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < k; j++)
                results[j][i] = array[i][j];
        }
        return results;
    }
    exports.unzip = unzip;
    function range(start, stop, step) {
        if (step === void 0) {
            step = 1;
        }
        (0, assert_1.assert)(step > 0, "'step' must be a positive number");
        if (stop == null) {
            stop = start;
            start = 0;
        }
        var max = Math.max, ceil = Math.ceil, abs = Math.abs;
        var delta = start <= stop ? step : -step;
        var length = max(ceil(abs(stop - start) / step), 0);
        var range = new Array(length);
        for (var i = 0; i < length; i++, start += delta) {
            range[i] = start;
        }
        return range;
    }
    exports.range = range;
    function linspace(start, stop, num) {
        if (num === void 0) {
            num = 100;
        }
        var step = (stop - start) / (num - 1);
        var array = new Array(num);
        for (var i = 0; i < num; i++) {
            array[i] = start + step * i;
        }
        return array;
    }
    exports.linspace = linspace;
    function transpose(array) {
        var rows = array.length;
        var cols = array[0].length;
        var transposed = [];
        for (var j = 0; j < cols; j++) {
            transposed[j] = [];
            for (var i = 0; i < rows; i++) {
                transposed[j][i] = array[i][j];
            }
        }
        return transposed;
    }
    exports.transpose = transpose;
    function argmin(array) {
        return (0, arrayable_1.min_by)(range(array.length), function (i) { return array[i]; });
    }
    exports.argmin = argmin;
    function argmax(array) {
        return (0, arrayable_1.max_by)(range(array.length), function (i) { return array[i]; });
    }
    exports.argmax = argmax;
    function sort_by(array, key) {
        var tmp = array.map(function (value, index) {
            return { value: value, index: index, key: key(value) };
        });
        tmp.sort(function (left, right) {
            var a = left.key;
            var b = right.key;
            if (a !== b) {
                if (a > b || a === undefined)
                    return 1;
                if (a < b || b === undefined)
                    return -1;
            }
            return left.index - right.index;
        });
        return tmp.map(function (item) { return item.value; });
    }
    exports.sort_by = sort_by;
    function uniq(array) {
        var e_1, _a;
        var result = new Set();
        try {
            for (var array_1 = (0, tslib_1.__values)(array), array_1_1 = array_1.next(); !array_1_1.done; array_1_1 = array_1.next()) {
                var value = array_1_1.value;
                result.add(value);
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (array_1_1 && !array_1_1.done && (_a = array_1.return))
                    _a.call(array_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(result), false);
    }
    exports.uniq = uniq;
    function uniq_by(array, key) {
        var e_2, _a;
        var result = [];
        var seen = [];
        try {
            for (var array_2 = (0, tslib_1.__values)(array), array_2_1 = array_2.next(); !array_2_1.done; array_2_1 = array_2.next()) {
                var value = array_2_1.value;
                var computed = key(value);
                if (!includes(seen, computed)) {
                    seen.push(computed);
                    result.push(value);
                }
            }
        }
        catch (e_2_1) {
            e_2 = { error: e_2_1 };
        }
        finally {
            try {
                if (array_2_1 && !array_2_1.done && (_a = array_2.return))
                    _a.call(array_2);
            }
            finally {
                if (e_2)
                    throw e_2.error;
            }
        }
        return result;
    }
    exports.uniq_by = uniq_by;
    function union() {
        var e_3, _a, e_4, _b;
        var arrays = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            arrays[_i] = arguments[_i];
        }
        var result = new Set();
        try {
            for (var arrays_1 = (0, tslib_1.__values)(arrays), arrays_1_1 = arrays_1.next(); !arrays_1_1.done; arrays_1_1 = arrays_1.next()) {
                var array = arrays_1_1.value;
                try {
                    for (var array_3 = (e_4 = void 0, (0, tslib_1.__values)(array)), array_3_1 = array_3.next(); !array_3_1.done; array_3_1 = array_3.next()) {
                        var value = array_3_1.value;
                        result.add(value);
                    }
                }
                catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                }
                finally {
                    try {
                        if (array_3_1 && !array_3_1.done && (_b = array_3.return))
                            _b.call(array_3);
                    }
                    finally {
                        if (e_4)
                            throw e_4.error;
                    }
                }
            }
        }
        catch (e_3_1) {
            e_3 = { error: e_3_1 };
        }
        finally {
            try {
                if (arrays_1_1 && !arrays_1_1.done && (_a = arrays_1.return))
                    _a.call(arrays_1);
            }
            finally {
                if (e_3)
                    throw e_3.error;
            }
        }
        return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(result), false);
    }
    exports.union = union;
    function intersection(array) {
        var e_5, _a, e_6, _b;
        var arrays = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            arrays[_i - 1] = arguments[_i];
        }
        var result = [];
        try {
            top: for (var array_4 = (0, tslib_1.__values)(array), array_4_1 = array_4.next(); !array_4_1.done; array_4_1 = array_4.next()) {
                var item = array_4_1.value;
                if (includes(result, item))
                    continue;
                try {
                    for (var arrays_2 = (e_6 = void 0, (0, tslib_1.__values)(arrays)), arrays_2_1 = arrays_2.next(); !arrays_2_1.done; arrays_2_1 = arrays_2.next()) {
                        var other = arrays_2_1.value;
                        if (!includes(other, item))
                            continue top;
                    }
                }
                catch (e_6_1) {
                    e_6 = { error: e_6_1 };
                }
                finally {
                    try {
                        if (arrays_2_1 && !arrays_2_1.done && (_b = arrays_2.return))
                            _b.call(arrays_2);
                    }
                    finally {
                        if (e_6)
                            throw e_6.error;
                    }
                }
                result.push(item);
            }
        }
        catch (e_5_1) {
            e_5 = { error: e_5_1 };
        }
        finally {
            try {
                if (array_4_1 && !array_4_1.done && (_a = array_4.return))
                    _a.call(array_4);
            }
            finally {
                if (e_5)
                    throw e_5.error;
            }
        }
        return result;
    }
    exports.intersection = intersection;
    function difference(array) {
        var arrays = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            arrays[_i - 1] = arguments[_i];
        }
        var rest = concat(arrays);
        return array.filter(function (value) { return !includes(rest, value); });
    }
    exports.difference = difference;
    function remove_at(array, i) {
        var result = copy(array);
        result.splice(i, 1);
        return result;
    }
    exports.remove_at = remove_at;
    function remove_by(array, key) {
        for (var i = 0; i < array.length;) {
            if (key(array[i]))
                array.splice(i, 1);
            else
                i++;
        }
    }
    exports.remove_by = remove_by;
    // Shuffle a collection, using the modern version of the
    // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
    function shuffle(array) {
        var length = array.length;
        var shuffled = new Array(length);
        for (var i = 0; i < length; i++) {
            var rand = (0, math_1.randomIn)(0, i);
            if (rand !== i)
                shuffled[i] = shuffled[rand];
            shuffled[rand] = array[i];
        }
        return shuffled;
    }
    exports.shuffle = shuffle;
    function pairwise(array, fn) {
        var n = array.length;
        var result = new Array(n - 1);
        for (var i = 0; i < n - 1; i++) {
            result[i] = fn(array[i], array[i + 1]);
        }
        return result;
    }
    exports.pairwise = pairwise;
    function reversed(array) {
        var n = array.length;
        var result = new Array(n);
        for (var i = 0; i < n; i++) {
            result[n - i - 1] = array[i];
        }
        return result;
    }
    exports.reversed = reversed;
    function repeat(value, n) {
        var result = new Array(n);
        for (var i = 0; i < n; i++) {
            result[i] = value;
        }
        return result;
    }
    exports.repeat = repeat;
},
/* core/util/assert.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var AssertionError = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AssertionError, _super);
        function AssertionError() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return AssertionError;
    }(Error));
    exports.AssertionError = AssertionError;
    AssertionError.__name__ = "AssertionError";
    function assert(condition, message) {
        if (condition === true || (condition !== false && condition()))
            return;
        throw new AssertionError(message !== null && message !== void 0 ? message : "Assertion failed");
    }
    exports.assert = assert;
    function unreachable() {
        throw new Error("unreachable code");
    }
    exports.unreachable = unreachable;
},
/* core/util/object.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var array_1 = require(126) /* ./array */;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    exports.keys = Object.keys, exports.values = Object.values, exports.entries = Object.entries, exports.extend = Object.assign;
    function clone(obj) {
        return (0, tslib_1.__assign)({}, obj);
    }
    exports.clone = clone;
    function merge(obj1, obj2) {
        var e_1, _a;
        /*
         * Returns an object with the array values for obj1 and obj2 unioned by key.
         */
        var result = Object.create(Object.prototype);
        var keys = (0, array_1.concat)([Object.keys(obj1), Object.keys(obj2)]);
        try {
            for (var keys_1 = (0, tslib_1.__values)(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
                var key = keys_1_1.value;
                var arr1 = hasOwnProperty.call(obj1, key) ? obj1[key] : [];
                var arr2 = hasOwnProperty.call(obj2, key) ? obj2[key] : [];
                result[key] = (0, array_1.union)(arr1, arr2);
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return))
                    _a.call(keys_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return result;
    }
    exports.merge = merge;
    function size(obj) {
        return Object.keys(obj).length;
    }
    exports.size = size;
    function is_empty(obj) {
        return size(obj) == 0;
    }
    exports.is_empty = is_empty;
    /** @deprecated */
    exports.isEmpty = is_empty;
    function to_object(map) {
        var e_2, _a;
        var obj = {};
        try {
            for (var map_1 = (0, tslib_1.__values)(map), map_1_1 = map_1.next(); !map_1_1.done; map_1_1 = map_1.next()) {
                var _b = (0, tslib_1.__read)(map_1_1.value, 2), key = _b[0], val = _b[1];
                obj[key] = val;
            }
        }
        catch (e_2_1) {
            e_2 = { error: e_2_1 };
        }
        finally {
            try {
                if (map_1_1 && !map_1_1.done && (_a = map_1.return))
                    _a.call(map_1);
            }
            finally {
                if (e_2)
                    throw e_2.error;
            }
        }
        return obj;
    }
    exports.to_object = to_object;
},
/* core/has_props.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var signaling_1 = require(130) /* ./signaling */;
    var refs_1 = require(132) /* ./util/refs */;
    var p = (0, tslib_1.__importStar)(require(133) /* ./properties */);
    var k = (0, tslib_1.__importStar)(require(136) /* ./kinds */);
    var string_1 = require(149) /* ./util/string */;
    var object_1 = require(128) /* ./util/object */;
    var types_1 = require(125) /* ./util/types */;
    var eq_1 = require(141) /* ./util/eq */;
    var serializer_1 = require(145) /* ./serializer */;
    var events_1 = require(150) /* ../document/events */;
    var eq_2 = require(141) /* ./util/eq */;
    var pretty_1 = require(151) /* ./util/pretty */;
    var cloneable_1 = require(152) /* ./util/cloneable */;
    var kinds = (0, tslib_1.__importStar)(require(136) /* ./kinds */);
    var HasProps = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HasProps, _super);
        function HasProps(attrs) {
            var e_1, _b;
            if (attrs === void 0) {
                attrs = {};
            }
            var _c, _d;
            var _this = _super.call(this) || this;
            _this._subtype = undefined;
            _this.document = null;
            _this.destroyed = new signaling_1.Signal0(_this, "destroyed");
            _this.change = new signaling_1.Signal0(_this, "change");
            _this.transformchange = new signaling_1.Signal0(_this, "transformchange");
            _this.exprchange = new signaling_1.Signal0(_this, "exprchange");
            _this.properties = {};
            _this._watchers = new WeakMap();
            _this._pending = false;
            _this._changing = false;
            var get = attrs instanceof Map ? attrs.get.bind(attrs) : function (name) { return attrs[name]; };
            _this.id = (_c = get("id")) !== null && _c !== void 0 ? _c : (0, string_1.uniqueId)();
            var _loop_1 = function (name, type, default_value, options) {
                var property = void 0;
                if (type instanceof p.PropertyAlias) {
                    Object.defineProperty(this_1.properties, name, {
                        get: function () { return _this.properties[type.attr]; },
                        configurable: false,
                        enumerable: false,
                    });
                }
                else {
                    if (type instanceof k.Kind)
                        property = new p.PrimitiveProperty(this_1, name, type, default_value, get(name), options);
                    else
                        property = new type(this_1, name, k.Any, default_value, get(name), options);
                    this_1.properties[name] = property;
                }
            };
            var this_1 = this;
            try {
                for (var _e = (0, tslib_1.__values)((0, object_1.entries)(_this._props)), _f = _e.next(); !_f.done; _f = _e.next()) {
                    var _g = (0, tslib_1.__read)(_f.value, 2), name = _g[0], _h = _g[1], type = _h.type, default_value = _h.default_value, options = _h.options;
                    _loop_1(name, type, default_value, options);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_f && !_f.done && (_b = _e.return))
                        _b.call(_e);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            // allowing us to defer initialization when loading many models
            // when loading a bunch of models, we want to do initialization as a second pass
            // because other objects that this one depends on might not be loaded yet
            if (!((_d = get("__deferred__")) !== null && _d !== void 0 ? _d : false)) {
                _this.finalize();
                _this.connect_signals();
            }
            return _this;
        }
        Object.defineProperty(HasProps.prototype, "is_syncable", {
            get: function () {
                return true;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(HasProps.prototype, "type", {
            get: function () {
                return this.constructor.__qualified__;
            },
            // XXX: setter is only required for backwards compatibility
            set: function (name) {
                console.warn("prototype.type = 'ModelName' is deprecated, use static __name__ instead");
                this.constructor.__name__ = name;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(HasProps, "__qualified__", {
            get: function () {
                var _b = this, __module__ = _b.__module__, __name__ = _b.__name__;
                return __module__ != null ? __module__ + "." + __name__ : __name__;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(HasProps, Symbol.toStringTag, {
            get: function () {
                return this.__name__;
            },
            enumerable: false,
            configurable: true
        });
        HasProps._fix_default = function (default_value, _attr) {
            if (default_value === undefined || (0, types_1.isFunction)(default_value))
                return default_value;
            else if ((0, types_1.isPrimitive)(default_value))
                return function () { return default_value; };
            else {
                var cloner_1 = new cloneable_1.Cloner();
                return function () { return cloner_1.clone(default_value); };
            }
        };
        // TODO: don't use Partial<>, but exclude inherited properties
        HasProps.define = function (obj) {
            var e_2, _b;
            var _loop_2 = function (name, prop) {
                if (this_2.prototype._props[name] != null)
                    throw new Error("attempted to redefine property '" + this_2.prototype.type + "." + name + "'");
                if (this_2.prototype[name] != null)
                    throw new Error("attempted to redefine attribute '" + this_2.prototype.type + "." + name + "'");
                Object.defineProperty(this_2.prototype, name, {
                    // XXX: don't use tail calls in getters/setters due to https://bugs.webkit.org/show_bug.cgi?id=164306
                    get: function () {
                        var value = this.properties[name].get_value();
                        return value;
                    },
                    set: function (value) {
                        var _b;
                        this.setv((_b = {}, _b[name] = value, _b));
                        return this;
                    },
                    configurable: false,
                    enumerable: true,
                });
                var _f = (0, tslib_1.__read)(prop, 3), type = _f[0], default_value = _f[1], _g = _f[2], options = _g === void 0 ? {} : _g;
                var refined_prop = {
                    type: type,
                    default_value: this_2._fix_default(default_value, name),
                    options: options,
                };
                var props = (0, tslib_1.__assign)({}, this_2.prototype._props);
                props[name] = refined_prop;
                this_2.prototype._props = props;
            };
            var this_2 = this;
            try {
                for (var _c = (0, tslib_1.__values)((0, object_1.entries)((0, types_1.isFunction)(obj) ? obj(kinds) : obj)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), name = _e[0], prop = _e[1];
                    _loop_2(name, prop);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        };
        HasProps.internal = function (obj) {
            var e_3, _b;
            var _object = {};
            try {
                for (var _c = (0, tslib_1.__values)((0, object_1.entries)((0, types_1.isFunction)(obj) ? obj(kinds) : obj)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), name = _e[0], prop = _e[1];
                    var _f = (0, tslib_1.__read)(prop, 3), type = _f[0], default_value = _f[1], _g = _f[2], options = _g === void 0 ? {} : _g;
                    _object[name] = [type, default_value, (0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), { internal: true })];
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            this.define(_object);
        };
        HasProps.mixins = function (defs) {
            var e_4, _b;
            function rename(prefix, mixin) {
                var e_5, _b;
                var result = {};
                try {
                    for (var _c = (0, tslib_1.__values)((0, object_1.entries)(mixin)), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var _e = (0, tslib_1.__read)(_d.value, 2), name = _e[0], prop = _e[1];
                        result[prefix + name] = prop;
                    }
                }
                catch (e_5_1) {
                    e_5 = { error: e_5_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_b = _c.return))
                            _b.call(_c);
                    }
                    finally {
                        if (e_5)
                            throw e_5.error;
                    }
                }
                return result;
            }
            var mixin_defs = {};
            var mixins = [];
            try {
                for (var _c = (0, tslib_1.__values)((0, types_1.isArray)(defs) ? defs : [defs]), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var def = _d.value;
                    if ((0, types_1.isArray)(def)) {
                        var _e = (0, tslib_1.__read)(def, 2), prefix = _e[0], mixin = _e[1];
                        (0, object_1.extend)(mixin_defs, rename(prefix, mixin));
                        mixins.push([prefix, mixin]);
                    }
                    else {
                        var mixin = def;
                        (0, object_1.extend)(mixin_defs, mixin);
                        mixins.push(["", mixin]);
                    }
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            this.define(mixin_defs);
            this.prototype._mixins = (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.prototype._mixins), false), (0, tslib_1.__read)(mixins), false);
        };
        HasProps.override = function (obj) {
            var e_6, _b;
            try {
                for (var _c = (0, tslib_1.__values)((0, object_1.entries)(obj)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), name = _e[0], prop = _e[1];
                    var default_value = this._fix_default(prop, name);
                    var value = this.prototype._props[name];
                    if (value == null)
                        throw new Error("attempted to override nonexistent '" + this.prototype.type + "." + name + "'");
                    var props = (0, tslib_1.__assign)({}, this.prototype._props);
                    props[name] = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, value), { default_value: default_value });
                    this.prototype._props = props;
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
        };
        HasProps.prototype.toString = function () {
            return this.type + "(" + this.id + ")";
        };
        HasProps.prototype.property = function (name) {
            var prop = this.properties[name];
            if (prop != null)
                return prop;
            else
                throw new Error("unknown property " + this.type + "." + name);
        };
        Object.defineProperty(HasProps.prototype, "attributes", {
            get: function () {
                var e_7, _b;
                var attrs = {};
                try {
                    for (var _c = (0, tslib_1.__values)(this), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var prop = _d.value;
                        attrs[prop.attr] = prop.get_value();
                    }
                }
                catch (e_7_1) {
                    e_7 = { error: e_7_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_b = _c.return))
                            _b.call(_c);
                    }
                    finally {
                        if (e_7)
                            throw e_7.error;
                    }
                }
                return attrs;
            },
            enumerable: false,
            configurable: true
        });
        HasProps.prototype[cloneable_1.clone] = function (cloner) {
            var e_8, _b;
            var attrs = new Map();
            try {
                for (var _c = (0, tslib_1.__values)(this), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var prop = _d.value;
                    if (prop.dirty) {
                        attrs.set(prop.attr, cloner.clone(prop.get_value()));
                    }
                }
            }
            catch (e_8_1) {
                e_8 = { error: e_8_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_8)
                        throw e_8.error;
                }
            }
            return new this.constructor(attrs);
        };
        HasProps.prototype[eq_2.equals] = function (that, cmp) {
            var e_9, _b;
            try {
                for (var _c = (0, tslib_1.__values)(this), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var p0 = _d.value;
                    var p1 = that.property(p0.attr);
                    if (!cmp.eq(p0.get_value(), p1.get_value()))
                        return false;
                }
            }
            catch (e_9_1) {
                e_9 = { error: e_9_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_9)
                        throw e_9.error;
                }
            }
            return true;
        };
        HasProps.prototype[pretty_1.pretty] = function (printer) {
            var e_10, _b;
            var T = printer.token;
            var items = [];
            try {
                for (var _c = (0, tslib_1.__values)(this), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var prop = _d.value;
                    if (prop.dirty) {
                        var value = prop.get_value();
                        items.push("" + prop.attr + T(":") + " " + printer.to_string(value));
                    }
                }
            }
            catch (e_10_1) {
                e_10 = { error: e_10_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_10)
                        throw e_10.error;
                }
            }
            var cls = this.constructor.__qualified__;
            return "" + cls + T("(") + T("{") + items.join(T(",") + " ") + T("}") + T(")");
        };
        HasProps.prototype[serializer_1.serialize] = function (serializer) {
            var e_11, _b;
            var ref = this.ref();
            serializer.add_ref(this, ref);
            var struct = this.struct();
            try {
                for (var _c = (0, tslib_1.__values)(this), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var prop = _d.value;
                    if (prop.syncable && (serializer.include_defaults || prop.dirty)) {
                        struct.attributes[prop.attr] = serializer.to_serializable(prop.get_value());
                    }
                }
            }
            catch (e_11_1) {
                e_11 = { error: e_11_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_11)
                        throw e_11.error;
                }
            }
            serializer.add_def(this, struct);
            return ref;
        };
        HasProps.prototype.finalize = function () {
            var e_12, _b;
            var _this = this;
            try {
                for (var _c = (0, tslib_1.__values)(this), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var prop = _d.value;
                    if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                        continue;
                    var value = prop.get_value(); // XXX: T -> any under instanceof
                    if (value != null) {
                        var transform = value.transform, expr = value.expr;
                        if (transform != null)
                            this.connect(transform.change, function () { return _this.transformchange.emit(); });
                        if (expr != null)
                            this.connect(expr.change, function () { return _this.exprchange.emit(); });
                    }
                }
            }
            catch (e_12_1) {
                e_12 = { error: e_12_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_12)
                        throw e_12.error;
                }
            }
            this.initialize();
        };
        HasProps.prototype.initialize = function () { };
        HasProps.prototype.connect_signals = function () { };
        HasProps.prototype.disconnect_signals = function () {
            signaling_1.Signal.disconnectReceiver(this);
        };
        HasProps.prototype.destroy = function () {
            this.disconnect_signals();
            this.destroyed.emit();
        };
        // Create a new model with exact attribute values to this one, but new identity.
        HasProps.prototype.clone = function () {
            var cloner = new cloneable_1.Cloner();
            return cloner.clone(this);
        };
        HasProps.prototype.changed_for = function (obj) {
            var changed = this._watchers.get(obj);
            this._watchers.set(obj, false);
            return changed !== null && changed !== void 0 ? changed : true;
        };
        // Set a hash of model attributes on the object, firing `"change"`. This is
        // the core primitive operation of a model, updating the data and notifying
        // anyone who needs to know about the change in state. The heart of the beast.
        HasProps.prototype._setv = function (changes, options) {
            var e_13, _b, e_14, _c;
            // Extract attributes and options.
            var check_eq = options.check_eq;
            var changed = [];
            var changing = this._changing;
            this._changing = true;
            try {
                for (var changes_1 = (0, tslib_1.__values)(changes), changes_1_1 = changes_1.next(); !changes_1_1.done; changes_1_1 = changes_1.next()) {
                    var _d = (0, tslib_1.__read)(changes_1_1.value, 2), prop = _d[0], value = _d[1];
                    if (check_eq === false || !(0, eq_1.is_equal)(prop.get_value(), value)) {
                        prop.set_value(value);
                        changed.push(prop);
                    }
                }
            }
            catch (e_13_1) {
                e_13 = { error: e_13_1 };
            }
            finally {
                try {
                    if (changes_1_1 && !changes_1_1.done && (_b = changes_1.return))
                        _b.call(changes_1);
                }
                finally {
                    if (e_13)
                        throw e_13.error;
                }
            }
            // Trigger all relevant attribute changes.
            if (changed.length > 0) {
                this._watchers = new WeakMap();
                this._pending = true;
            }
            try {
                for (var changed_1 = (0, tslib_1.__values)(changed), changed_1_1 = changed_1.next(); !changed_1_1.done; changed_1_1 = changed_1.next()) {
                    var prop = changed_1_1.value;
                    prop.change.emit();
                }
            }
            catch (e_14_1) {
                e_14 = { error: e_14_1 };
            }
            finally {
                try {
                    if (changed_1_1 && !changed_1_1.done && (_c = changed_1.return))
                        _c.call(changed_1);
                }
                finally {
                    if (e_14)
                        throw e_14.error;
                }
            }
            // You might be wondering why there's a `while` loop here. Changes can
            // be recursively nested within `"change"` events.
            if (changing)
                return;
            if (!options.no_change) {
                while (this._pending) {
                    this._pending = false;
                    this.change.emit();
                }
            }
            this._pending = false;
            this._changing = false;
        };
        HasProps.prototype.setv = function (changed_attrs, options) {
            var e_15, _b, e_16, _c, e_17, _d, e_18, _e;
            if (options === void 0) {
                options = {};
            }
            var changes = (0, object_1.entries)(changed_attrs);
            if (changes.length == 0)
                return;
            if (options.silent === true) {
                this._watchers = new WeakMap();
                try {
                    for (var changes_2 = (0, tslib_1.__values)(changes), changes_2_1 = changes_2.next(); !changes_2_1.done; changes_2_1 = changes_2.next()) {
                        var _f = (0, tslib_1.__read)(changes_2_1.value, 2), attr = _f[0], value = _f[1];
                        this.properties[attr].set_value(value);
                    }
                }
                catch (e_15_1) {
                    e_15 = { error: e_15_1 };
                }
                finally {
                    try {
                        if (changes_2_1 && !changes_2_1.done && (_b = changes_2.return))
                            _b.call(changes_2);
                    }
                    finally {
                        if (e_15)
                            throw e_15.error;
                    }
                }
                return;
            }
            var changed = new Map();
            var previous = new Map();
            try {
                for (var changes_3 = (0, tslib_1.__values)(changes), changes_3_1 = changes_3.next(); !changes_3_1.done; changes_3_1 = changes_3.next()) {
                    var _g = (0, tslib_1.__read)(changes_3_1.value, 2), attr = _g[0], value = _g[1];
                    var prop = this.properties[attr];
                    changed.set(prop, value);
                    previous.set(prop, prop.get_value());
                }
            }
            catch (e_16_1) {
                e_16 = { error: e_16_1 };
            }
            finally {
                try {
                    if (changes_3_1 && !changes_3_1.done && (_c = changes_3.return))
                        _c.call(changes_3);
                }
                finally {
                    if (e_16)
                        throw e_16.error;
                }
            }
            this._setv(changed, options);
            var document = this.document;
            if (document != null) {
                var changed_3 = [];
                try {
                    for (var previous_1 = (0, tslib_1.__values)(previous), previous_1_1 = previous_1.next(); !previous_1_1.done; previous_1_1 = previous_1.next()) {
                        var _h = (0, tslib_1.__read)(previous_1_1.value, 2), prop = _h[0], value = _h[1];
                        changed_3.push([prop, value, prop.get_value()]);
                    }
                }
                catch (e_17_1) {
                    e_17 = { error: e_17_1 };
                }
                finally {
                    try {
                        if (previous_1_1 && !previous_1_1.done && (_d = previous_1.return))
                            _d.call(previous_1);
                    }
                    finally {
                        if (e_17)
                            throw e_17.error;
                    }
                }
                try {
                    for (var changed_2 = (0, tslib_1.__values)(changed_3), changed_2_1 = changed_2.next(); !changed_2_1.done; changed_2_1 = changed_2.next()) {
                        var _j = (0, tslib_1.__read)(changed_2_1.value, 3), old_value = _j[1], new_value = _j[2];
                        if (this._needs_invalidate(old_value, new_value)) {
                            document._invalidate_all_models();
                            break;
                        }
                    }
                }
                catch (e_18_1) {
                    e_18 = { error: e_18_1 };
                }
                finally {
                    try {
                        if (changed_2_1 && !changed_2_1.done && (_e = changed_2.return))
                            _e.call(changed_2);
                    }
                    finally {
                        if (e_18)
                            throw e_18.error;
                    }
                }
                this._push_changes(changed_3, options);
            }
        };
        /** @deprecated */
        HasProps.prototype.getv = function (name) {
            return this.property(name).get_value();
        };
        HasProps.prototype.ref = function () {
            return { id: this.id };
        };
        HasProps.prototype.struct = function () {
            var struct = {
                type: this.type,
                id: this.id,
                attributes: {},
            };
            if (this._subtype != null) {
                struct.subtype = this._subtype;
            }
            return struct;
        };
        // we only keep the subtype so we match Python;
        // only Python cares about this
        HasProps.prototype.set_subtype = function (subtype) {
            this._subtype = subtype;
        };
        HasProps.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_b) {
                switch (_b.label) {
                    case 0: return [5 /*yield**/, (0, tslib_1.__values)((0, object_1.values)(this.properties))];
                    case 1:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        };
        HasProps.prototype.syncable_properties = function () {
            var _b, _c, prop, e_19_1;
            var e_19, _d;
            return (0, tslib_1.__generator)(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        _e.trys.push([0, 5, 6, 7]);
                        _b = (0, tslib_1.__values)(this), _c = _b.next();
                        _e.label = 1;
                    case 1:
                        if (!!_c.done)
                            return [3 /*break*/, 4];
                        prop = _c.value;
                        if (!prop.syncable)
                            return [3 /*break*/, 3];
                        return [4 /*yield*/, prop];
                    case 2:
                        _e.sent();
                        _e.label = 3;
                    case 3:
                        _c = _b.next();
                        return [3 /*break*/, 1];
                    case 4: return [3 /*break*/, 7];
                    case 5:
                        e_19_1 = _e.sent();
                        e_19 = { error: e_19_1 };
                        return [3 /*break*/, 7];
                    case 6:
                        try {
                            if (_c && !_c.done && (_d = _b.return))
                                _d.call(_b);
                        }
                        finally {
                            if (e_19)
                                throw e_19.error;
                        }
                        return [7 /*endfinally*/];
                    case 7: return [2 /*return*/];
                }
            });
        };
        /** @deprecated */
        HasProps.prototype.serializable_attributes = function () {
            var e_20, _b;
            var attrs = {};
            try {
                for (var _c = (0, tslib_1.__values)(this.syncable_properties()), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var prop = _d.value;
                    attrs[prop.attr] = prop.get_value();
                }
            }
            catch (e_20_1) {
                e_20 = { error: e_20_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_20)
                        throw e_20.error;
                }
            }
            return attrs;
        };
        // this is like _value_record_references but expects to find refs
        // instead of models, and takes a doc to look up the refs in
        HasProps._json_record_references = function (doc, v, refs, options) {
            var e_21, _b, e_22, _c;
            var recursive = options.recursive;
            if ((0, refs_1.is_ref)(v)) {
                var model = doc.get_model_by_id(v.id);
                if (model != null && !refs.has(model)) {
                    HasProps._value_record_references(model, refs, { recursive: recursive });
                }
            }
            else if ((0, types_1.isArray)(v)) {
                try {
                    for (var v_1 = (0, tslib_1.__values)(v), v_1_1 = v_1.next(); !v_1_1.done; v_1_1 = v_1.next()) {
                        var elem = v_1_1.value;
                        HasProps._json_record_references(doc, elem, refs, { recursive: recursive });
                    }
                }
                catch (e_21_1) {
                    e_21 = { error: e_21_1 };
                }
                finally {
                    try {
                        if (v_1_1 && !v_1_1.done && (_b = v_1.return))
                            _b.call(v_1);
                    }
                    finally {
                        if (e_21)
                            throw e_21.error;
                    }
                }
            }
            else if ((0, types_1.isPlainObject)(v)) {
                try {
                    for (var _d = (0, tslib_1.__values)((0, object_1.values)(v)), _e = _d.next(); !_e.done; _e = _d.next()) {
                        var elem = _e.value;
                        HasProps._json_record_references(doc, elem, refs, { recursive: recursive });
                    }
                }
                catch (e_22_1) {
                    e_22 = { error: e_22_1 };
                }
                finally {
                    try {
                        if (_e && !_e.done && (_c = _d.return))
                            _c.call(_d);
                    }
                    finally {
                        if (e_22)
                            throw e_22.error;
                    }
                }
            }
        };
        // add all references from 'v' to 'result', if recurse
        // is true then descend into refs, if false only
        // descend into non-refs
        HasProps._value_record_references = function (v, refs, options) {
            var e_23, _b, e_24, _c, e_25, _d;
            var recursive = options.recursive;
            if (v instanceof HasProps) {
                if (!refs.has(v)) {
                    refs.add(v);
                    if (recursive) {
                        try {
                            for (var _e = (0, tslib_1.__values)(v.syncable_properties()), _f = _e.next(); !_f.done; _f = _e.next()) {
                                var prop = _f.value;
                                var value = prop.get_value();
                                HasProps._value_record_references(value, refs, { recursive: recursive });
                            }
                        }
                        catch (e_23_1) {
                            e_23 = { error: e_23_1 };
                        }
                        finally {
                            try {
                                if (_f && !_f.done && (_b = _e.return))
                                    _b.call(_e);
                            }
                            finally {
                                if (e_23)
                                    throw e_23.error;
                            }
                        }
                    }
                }
            }
            else if ((0, types_1.isArray)(v)) {
                try {
                    for (var v_2 = (0, tslib_1.__values)(v), v_2_1 = v_2.next(); !v_2_1.done; v_2_1 = v_2.next()) {
                        var elem = v_2_1.value;
                        HasProps._value_record_references(elem, refs, { recursive: recursive });
                    }
                }
                catch (e_24_1) {
                    e_24 = { error: e_24_1 };
                }
                finally {
                    try {
                        if (v_2_1 && !v_2_1.done && (_c = v_2.return))
                            _c.call(v_2);
                    }
                    finally {
                        if (e_24)
                            throw e_24.error;
                    }
                }
            }
            else if ((0, types_1.isPlainObject)(v)) {
                try {
                    for (var _g = (0, tslib_1.__values)((0, object_1.values)(v)), _h = _g.next(); !_h.done; _h = _g.next()) {
                        var elem = _h.value;
                        HasProps._value_record_references(elem, refs, { recursive: recursive });
                    }
                }
                catch (e_25_1) {
                    e_25 = { error: e_25_1 };
                }
                finally {
                    try {
                        if (_h && !_h.done && (_d = _g.return))
                            _d.call(_g);
                    }
                    finally {
                        if (e_25)
                            throw e_25.error;
                    }
                }
            }
        };
        HasProps.prototype.references = function () {
            var refs = new Set();
            HasProps._value_record_references(this, refs, { recursive: true });
            return refs;
        };
        HasProps.prototype._doc_attached = function () { };
        HasProps.prototype._doc_detached = function () { };
        HasProps.prototype.attach_document = function (doc) {
            // This should only be called by the Document implementation to set the document field
            if (this.document != null && this.document != doc)
                throw new Error("models must be owned by only a single document");
            this.document = doc;
            this._doc_attached();
        };
        HasProps.prototype.detach_document = function () {
            // This should only be called by the Document implementation to unset the document field
            this._doc_detached();
            this.document = null;
        };
        HasProps.prototype._needs_invalidate = function (old_value, new_value) {
            var e_26, _b, e_27, _c;
            var new_refs = new Set();
            HasProps._value_record_references(new_value, new_refs, { recursive: false });
            var old_refs = new Set();
            HasProps._value_record_references(old_value, old_refs, { recursive: false });
            try {
                for (var new_refs_1 = (0, tslib_1.__values)(new_refs), new_refs_1_1 = new_refs_1.next(); !new_refs_1_1.done; new_refs_1_1 = new_refs_1.next()) {
                    var new_id = new_refs_1_1.value;
                    if (!old_refs.has(new_id))
                        return true;
                }
            }
            catch (e_26_1) {
                e_26 = { error: e_26_1 };
            }
            finally {
                try {
                    if (new_refs_1_1 && !new_refs_1_1.done && (_b = new_refs_1.return))
                        _b.call(new_refs_1);
                }
                finally {
                    if (e_26)
                        throw e_26.error;
                }
            }
            try {
                for (var old_refs_1 = (0, tslib_1.__values)(old_refs), old_refs_1_1 = old_refs_1.next(); !old_refs_1_1.done; old_refs_1_1 = old_refs_1.next()) {
                    var old_id = old_refs_1_1.value;
                    if (!new_refs.has(old_id))
                        return true;
                }
            }
            catch (e_27_1) {
                e_27 = { error: e_27_1 };
            }
            finally {
                try {
                    if (old_refs_1_1 && !old_refs_1_1.done && (_c = old_refs_1.return))
                        _c.call(old_refs_1);
                }
                finally {
                    if (e_27)
                        throw e_27.error;
                }
            }
            return false;
        };
        HasProps.prototype._push_changes = function (changes, options) {
            var e_28, _b, _c;
            if (options === void 0) {
                options = {};
            }
            if (!this.is_syncable)
                return;
            var document = this.document;
            if (document == null)
                return;
            var setter_id = options.setter_id;
            var events = [];
            try {
                for (var changes_4 = (0, tslib_1.__values)(changes), changes_4_1 = changes_4.next(); !changes_4_1.done; changes_4_1 = changes_4.next()) {
                    var _d = (0, tslib_1.__read)(changes_4_1.value, 3), prop = _d[0], old_value = _d[1], new_value = _d[2];
                    if (prop.syncable)
                        events.push(new events_1.ModelChangedEvent(document, this, prop.attr, old_value, new_value, setter_id));
                }
            }
            catch (e_28_1) {
                e_28 = { error: e_28_1 };
            }
            finally {
                try {
                    if (changes_4_1 && !changes_4_1.done && (_b = changes_4.return))
                        _b.call(changes_4);
                }
                finally {
                    if (e_28)
                        throw e_28.error;
                }
            }
            if (events.length != 0) {
                var event = void 0;
                if (events.length == 1)
                    _c = (0, tslib_1.__read)(events, 1), event = _c[0];
                else
                    event = new events_1.DocumentEventBatch(document, events, setter_id);
                document._trigger_on_change(event);
            }
        };
        HasProps.prototype.on_change = function (properties, fn) {
            var e_29, _b;
            try {
                for (var _c = (0, tslib_1.__values)((0, types_1.isArray)(properties) ? properties : [properties]), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var property = _d.value;
                    this.connect(property.change, fn);
                }
            }
            catch (e_29_1) {
                e_29 = { error: e_29_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_29)
                        throw e_29.error;
                }
            }
        };
        return HasProps;
    }((0, signaling_1.Signalable)()));
    exports.HasProps = HasProps;
    _a = HasProps;
    (function () {
        _a.prototype._props = {};
        _a.prototype._mixins = [];
    })();
},
/* core/signaling.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    // Based on https://github.com/phosphorjs/phosphor/blob/master/packages/signaling/src/index.ts
    var defer_1 = require(131) /* ./util/defer */;
    var array_1 = require(126) /* ./util/array */;
    var Signal = /** @class */ (function () {
        function Signal(sender, name) {
            this.sender = sender;
            this.name = name;
        }
        Signal.prototype.connect = function (slot, context) {
            if (context === void 0) {
                context = null;
            }
            if (!receiversForSender.has(this.sender)) {
                receiversForSender.set(this.sender, []);
            }
            var receivers = receiversForSender.get(this.sender);
            if (find_connection(receivers, this, slot, context) != null) {
                return false;
            }
            var receiver = context !== null && context !== void 0 ? context : slot;
            if (!sendersForReceiver.has(receiver)) {
                sendersForReceiver.set(receiver, []);
            }
            var senders = sendersForReceiver.get(receiver);
            var connection = { signal: this, slot: slot, context: context };
            receivers.push(connection);
            senders.push(connection);
            return true;
        };
        Signal.prototype.disconnect = function (slot, context) {
            if (context === void 0) {
                context = null;
            }
            var receivers = receiversForSender.get(this.sender);
            if (receivers == null || receivers.length === 0) {
                return false;
            }
            var connection = find_connection(receivers, this, slot, context);
            if (connection == null) {
                return false;
            }
            var receiver = context !== null && context !== void 0 ? context : slot;
            var senders = sendersForReceiver.get(receiver);
            connection.signal = null;
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
            return true;
        };
        Signal.prototype.emit = function (args) {
            var e_1, _a;
            var _b;
            var receivers = (_b = receiversForSender.get(this.sender)) !== null && _b !== void 0 ? _b : [];
            try {
                for (var receivers_1 = (0, tslib_1.__values)(receivers), receivers_1_1 = receivers_1.next(); !receivers_1_1.done; receivers_1_1 = receivers_1.next()) {
                    var _c = receivers_1_1.value, signal = _c.signal, slot = _c.slot, context = _c.context;
                    if (signal === this) {
                        slot.call(context, args, this.sender);
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (receivers_1_1 && !receivers_1_1.done && (_a = receivers_1.return))
                        _a.call(receivers_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        return Signal;
    }());
    exports.Signal = Signal;
    Signal.__name__ = "Signal";
    var Signal0 = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Signal0, _super);
        function Signal0() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Signal0.prototype.emit = function () {
            _super.prototype.emit.call(this, undefined);
        };
        return Signal0;
    }(Signal));
    exports.Signal0 = Signal0;
    Signal0.__name__ = "Signal0";
    (function (Signal) {
        function disconnect_between(sender, receiver) {
            var e_2, _a;
            var receivers = receiversForSender.get(sender);
            if (receivers == null || receivers.length === 0)
                return;
            var senders = sendersForReceiver.get(receiver);
            if (senders == null || senders.length === 0)
                return;
            try {
                for (var senders_1 = (0, tslib_1.__values)(senders), senders_1_1 = senders_1.next(); !senders_1_1.done; senders_1_1 = senders_1.next()) {
                    var connection = senders_1_1.value;
                    if (connection.signal == null)
                        return;
                    if (connection.signal.sender === sender)
                        connection.signal = null;
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (senders_1_1 && !senders_1_1.done && (_a = senders_1.return))
                        _a.call(senders_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
        }
        Signal.disconnect_between = disconnect_between;
        function disconnect_sender(sender) {
            var e_3, _a;
            var _b;
            var receivers = receiversForSender.get(sender);
            if (receivers == null || receivers.length === 0)
                return;
            try {
                for (var receivers_2 = (0, tslib_1.__values)(receivers), receivers_2_1 = receivers_2.next(); !receivers_2_1.done; receivers_2_1 = receivers_2.next()) {
                    var connection = receivers_2_1.value;
                    if (connection.signal == null)
                        return;
                    var receiver = (_b = connection.context) !== null && _b !== void 0 ? _b : connection.slot;
                    connection.signal = null;
                    schedule_cleanup(sendersForReceiver.get(receiver));
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (receivers_2_1 && !receivers_2_1.done && (_a = receivers_2.return))
                        _a.call(receivers_2);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            schedule_cleanup(receivers);
        }
        Signal.disconnect_sender = disconnect_sender;
        function disconnect_receiver(receiver, slot, except_senders) {
            var e_4, _a;
            var senders = sendersForReceiver.get(receiver);
            if (senders == null || senders.length === 0)
                return;
            try {
                for (var senders_2 = (0, tslib_1.__values)(senders), senders_2_1 = senders_2.next(); !senders_2_1.done; senders_2_1 = senders_2.next()) {
                    var connection = senders_2_1.value;
                    if (connection.signal == null)
                        return;
                    if (slot != null && connection.slot != slot)
                        continue;
                    var sender = connection.signal.sender;
                    if (except_senders != null && except_senders.has(sender))
                        continue;
                    connection.signal = null;
                    schedule_cleanup(receiversForSender.get(sender));
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (senders_2_1 && !senders_2_1.done && (_a = senders_2.return))
                        _a.call(senders_2);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            schedule_cleanup(senders);
        }
        Signal.disconnect_receiver = disconnect_receiver;
        function disconnect_all(obj) {
            var e_5, _a, e_6, _b;
            var receivers = receiversForSender.get(obj);
            if (receivers != null && receivers.length !== 0) {
                try {
                    for (var receivers_3 = (0, tslib_1.__values)(receivers), receivers_3_1 = receivers_3.next(); !receivers_3_1.done; receivers_3_1 = receivers_3.next()) {
                        var connection = receivers_3_1.value;
                        connection.signal = null;
                    }
                }
                catch (e_5_1) {
                    e_5 = { error: e_5_1 };
                }
                finally {
                    try {
                        if (receivers_3_1 && !receivers_3_1.done && (_a = receivers_3.return))
                            _a.call(receivers_3);
                    }
                    finally {
                        if (e_5)
                            throw e_5.error;
                    }
                }
                schedule_cleanup(receivers);
            }
            var senders = sendersForReceiver.get(obj);
            if (senders != null && senders.length !== 0) {
                try {
                    for (var senders_3 = (0, tslib_1.__values)(senders), senders_3_1 = senders_3.next(); !senders_3_1.done; senders_3_1 = senders_3.next()) {
                        var connection = senders_3_1.value;
                        connection.signal = null;
                    }
                }
                catch (e_6_1) {
                    e_6 = { error: e_6_1 };
                }
                finally {
                    try {
                        if (senders_3_1 && !senders_3_1.done && (_b = senders_3.return))
                            _b.call(senders_3);
                    }
                    finally {
                        if (e_6)
                            throw e_6.error;
                    }
                }
                schedule_cleanup(senders);
            }
        }
        Signal.disconnect_all = disconnect_all;
        /** @deprecated */
        Signal.disconnectBetween = disconnect_between;
        /** @deprecated */
        Signal.disconnectSender = disconnect_sender;
        /** @deprecated */
        Signal.disconnectReceiver = disconnect_receiver;
        /** @deprecated */
        Signal.disconnectAll = disconnect_all;
    })(Signal || (exports.Signal = Signal = {}));
    function Signalable() {
        return /** @class */ (function () {
            function class_1() {
            }
            class_1.prototype.connect = function (signal, slot) {
                return signal.connect(slot, this);
            };
            class_1.prototype.disconnect = function (signal, slot) {
                return signal.disconnect(slot, this);
            };
            return class_1;
        }());
    }
    exports.Signalable = Signalable;
    var receiversForSender = new WeakMap();
    var sendersForReceiver = new WeakMap();
    function find_connection(conns, signal, slot, context) {
        return (0, array_1.find)(conns, function (conn) { return conn.signal === signal && conn.slot === slot && conn.context === context; });
    }
    var dirty_set = new Set();
    function schedule_cleanup(connections) {
        var _this = this;
        if (dirty_set.size === 0) {
            (function () {
                return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                    return (0, tslib_1.__generator)(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, (0, defer_1.defer)()];
                            case 1:
                                _a.sent();
                                cleanup_dirty_set();
                                return [2 /*return*/];
                        }
                    });
                });
            })();
        }
        dirty_set.add(connections);
    }
    function cleanup_dirty_set() {
        var e_7, _a;
        try {
            for (var dirty_set_1 = (0, tslib_1.__values)(dirty_set), dirty_set_1_1 = dirty_set_1.next(); !dirty_set_1_1.done; dirty_set_1_1 = dirty_set_1.next()) {
                var connections = dirty_set_1_1.value;
                (0, array_1.remove_by)(connections, function (connection) { return connection.signal == null; });
            }
        }
        catch (e_7_1) {
            e_7 = { error: e_7_1 };
        }
        finally {
            try {
                if (dirty_set_1_1 && !dirty_set_1_1.done && (_a = dirty_set_1.return))
                    _a.call(dirty_set_1);
            }
            finally {
                if (e_7)
                    throw e_7.error;
            }
        }
        dirty_set.clear();
    }
},
/* core/util/defer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var channel = new MessageChannel();
    var tasks = new Map();
    channel.port1.onmessage = function (event) {
        var handle = event.data;
        var fn = tasks.get(handle);
        if (fn != null) {
            try {
                fn();
            }
            finally {
                tasks.delete(handle);
            }
        }
    };
    var counter = 1;
    function defer() {
        return new Promise(function (resolve) {
            var handle = counter++;
            tasks.set(handle, resolve);
            channel.port2.postMessage(handle);
        });
    }
    exports.defer = defer;
    function wait(ms) {
        return new Promise(function (resolve) { return setTimeout(resolve, ms); });
    }
    exports.wait = wait;
},
/* core/util/refs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(125) /* ./types */;
    var object_1 = require(128) /* ./object */;
    // Determine whether an object has the proper format of a Bokeh reference
    //
    // @param arg [Object] the object to test
    // @return [bool] whether the object is a reference
    //
    // @note this function does not check that the id and types are valid,
    //   only that the format is correct (all required keys are present)
    //
    function is_ref(arg) {
        if ((0, types_1.isPlainObject)(arg)) {
            var attrs = (0, object_1.keys)(arg);
            return attrs.length == 1 && attrs[0] == "id";
        }
        return false;
    }
    exports.is_ref = is_ref;
},
/* core/properties.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.YCoordinateSeqSeqSeqSpec = exports.XCoordinateSeqSeqSeqSpec = exports.YCoordinateSeqSpec = exports.XCoordinateSeqSpec = exports.YCoordinateSpec = exports.XCoordinateSpec = exports.CoordinateSeqSeqSeqSpec = exports.CoordinateSeqSpec = exports.CoordinateSpec = exports.BaseCoordinateSpec = exports.NumberUnitsSpec = exports.UnitsSpec = exports.DataSpec = exports.VectorSpec = exports.TextBaselineScalar = exports.TextAlignScalar = exports.FontStyleScalar = exports.FontSizeScalar = exports.FontScalar = exports.LineDashScalar = exports.LineCapScalar = exports.LineJoinScalar = exports.ArrayScalar = exports.NullStringScalar = exports.StringScalar = exports.NumberScalar = exports.ColorScalar = exports.AnyScalar = exports.ScalarSpec = exports.VerticalAlign = exports.UpdateMode = exports.TooltipAttachment = exports.TickLabelOrientation = exports.TextureRepetition = exports.TextBaseline = exports.TextAlign = exports.TapBehavior = exports.StepMode = exports.StartEnd = exports.SpatialUnits = exports.Sort = exports.SizingMode = exports.Side = exports.RoundingFunction = exports.ResetPolicy = exports.RenderMode = exports.RenderLevel = exports.RadiusDimension = exports.PointPolicy = exports.Place = void 0;
    exports.TextBaselineSpec = exports.TextAlignSpec = exports.FontStyleSpec = exports.FontSizeSpec = exports.FontSpec = exports.LineDashSpec = exports.LineCapSpec = exports.LineJoinSpec = exports.MarkerSpec = exports.ArraySpec = exports.NullStringSpec = exports.StringSpec = exports.AnySpec = exports.NDArraySpec = exports.ColorSpec = exports.ScreenSizeSpec = exports.NumberSpec = exports.IntSpec = exports.BooleanSpec = exports.NullDistanceSpec = exports.DistanceSpec = exports.AngleSpec = void 0;
    var tslib_1 = require(1) /* tslib */;
    var signaling_1 = require(130) /* ./signaling */;
    var logging_1 = require(134) /* ./logging */;
    var enums = (0, tslib_1.__importStar)(require(135) /* ./enums */);
    var types_1 = require(139) /* ./types */;
    var array_1 = require(126) /* ./util/array */;
    var arrayable_1 = require(116) /* ./util/arrayable */;
    var math_1 = require(117) /* ./util/math */;
    var color_1 = require(137) /* ./util/color */;
    var platform_1 = require(142) /* ./util/platform */;
    var types_2 = require(125) /* ./util/types */;
    var settings_1 = require(143) /* ./settings */;
    var ndarray_1 = require(144) /* ./util/ndarray */;
    var uniforms_1 = require(148) /* ./uniforms */;
    __esExport("Uniform", uniforms_1.Uniform);
    __esExport("UniformScalar", uniforms_1.UniformScalar);
    __esExport("UniformVector", uniforms_1.UniformVector);
    function valueToString(value) {
        try {
            return JSON.stringify(value);
        }
        catch (_a) {
            return value.toString();
        }
    }
    function isSpec(obj) {
        return (0, types_2.isPlainObject)(obj) &&
            ((obj.value === undefined ? 0 : 1) +
                (obj.field === undefined ? 0 : 1) +
                (obj.expr === undefined ? 0 : 1) == 1); // garbage JS XOR
    }
    exports.isSpec = isSpec;
    var Property = /** @class */ (function () {
        function Property(obj, attr, kind, default_value, initial_value, options) {
            if (options === void 0) {
                options = {};
            }
            var _a;
            this.obj = obj;
            this.attr = attr;
            this.kind = kind;
            this.default_value = default_value;
            this._dirty = false;
            this.change = new signaling_1.Signal0(this.obj, "change");
            this.internal = (_a = options.internal) !== null && _a !== void 0 ? _a : false;
            this.convert = options.convert;
            this.on_update = options.on_update;
            var attr_value;
            if (initial_value !== undefined) {
                attr_value = initial_value;
                this._dirty = true;
            }
            else {
                var value = this._default_override();
                if (value !== undefined)
                    attr_value = value;
                else if (default_value !== undefined)
                    attr_value = default_value(obj);
                else {
                    // XXX: temporary and super sketchy, but affects only "readonly" and a few internal properties
                    // console.warn(`${this.obj}.${this.attr} has no value nor default`)
                    this.spec = { value: null };
                    return;
                }
            }
            this._update(attr_value);
        }
        Object.defineProperty(Property.prototype, "is_value", {
            get: function () {
                return this.spec.value !== undefined;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Property.prototype, "syncable", {
            get: function () {
                return !this.internal;
            },
            enumerable: false,
            configurable: true
        });
        Property.prototype.get_value = function () {
            return this.spec.value;
        };
        Property.prototype.set_value = function (val) {
            this._update(val);
            this._dirty = true;
        };
        // abstract _intrinsic_default(): T
        Property.prototype._default_override = function () {
            return undefined;
        };
        Object.defineProperty(Property.prototype, "dirty", {
            get: function () {
                return this._dirty;
            },
            enumerable: false,
            configurable: true
        });
        //protected abstract _update(attr_value: T): void
        Property.prototype._update = function (attr_value) {
            var _a;
            this.validate(attr_value);
            if (this.convert != null) {
                var converted = this.convert(attr_value);
                if (converted !== undefined)
                    attr_value = converted;
            }
            this.spec = { value: attr_value };
            (_a = this.on_update) === null || _a === void 0 ? void 0 : _a.call(this, attr_value, this.obj);
        };
        Property.prototype.toString = function () {
            /*${this.name}*/
            return "Prop(" + this.obj + "." + this.attr + ", spec: " + valueToString(this.spec) + ")";
        };
        // ----- customizable policies
        Property.prototype.normalize = function (values) {
            return values;
        };
        Property.prototype.validate = function (value) {
            if (!this.valid(value))
                throw new Error(this.obj + "." + this.attr + " given invalid value: " + valueToString(value));
        };
        Property.prototype.valid = function (value) {
            return this.kind.valid(value);
        };
        // ----- property accessors
        Property.prototype._value = function (do_spec_transform) {
            if (do_spec_transform === void 0) {
                do_spec_transform = true;
            }
            if (!this.is_value)
                throw new Error("attempted to retrieve property value for property without value specification");
            var ret = this.normalize([this.spec.value])[0];
            if (this.spec.transform != null && do_spec_transform)
                ret = this.spec.transform.compute(ret);
            return ret;
        };
        return Property;
    }());
    exports.Property = Property;
    Property.__name__ = "Property";
    var PropertyAlias = /** @class */ (function () {
        function PropertyAlias(attr) {
            this.attr = attr;
        }
        return PropertyAlias;
    }());
    exports.PropertyAlias = PropertyAlias;
    PropertyAlias.__name__ = "PropertyAlias";
    function Alias(attr) {
        return new PropertyAlias(attr);
    }
    exports.Alias = Alias;
    //
    // Primitive Properties
    //
    var PrimitiveProperty = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PrimitiveProperty, _super);
        function PrimitiveProperty() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return PrimitiveProperty;
    }(Property));
    exports.PrimitiveProperty = PrimitiveProperty;
    PrimitiveProperty.__name__ = "PrimitiveProperty";
    /** @deprecated */
    var Any = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Any, _super);
        function Any() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Any;
    }(Property));
    exports.Any = Any;
    Any.__name__ = "Any";
    /** @deprecated */
    var Array = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Array, _super);
        function Array() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Array.prototype.valid = function (value) {
            return (0, types_2.isArray)(value) || (0, types_2.isTypedArray)(value);
        };
        return Array;
    }(Property));
    exports.Array = Array;
    Array.__name__ = "Array";
    /** @deprecated */
    var Boolean = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Boolean, _super);
        function Boolean() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Boolean.prototype.valid = function (value) {
            return (0, types_2.isBoolean)(value);
        };
        return Boolean;
    }(Property));
    exports.Boolean = Boolean;
    Boolean.__name__ = "Boolean";
    /** @deprecated */
    var Color = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Color, _super);
        function Color() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Color.prototype.valid = function (value) {
            return (0, color_1.is_Color)(value);
        };
        return Color;
    }(Property));
    exports.Color = Color;
    Color.__name__ = "Color";
    /** @deprecated */
    var Instance = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Instance, _super);
        function Instance() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Instance;
    }(Property));
    exports.Instance = Instance;
    Instance.__name__ = "Instance";
    /** @deprecated */
    var Number = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Number, _super);
        function Number() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Number.prototype.valid = function (value) {
            return (0, types_2.isNumber)(value);
        };
        return Number;
    }(Property));
    exports.Number = Number;
    Number.__name__ = "Number";
    /** @deprecated */
    var Int = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Int, _super);
        function Int() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Int.prototype.valid = function (value) {
            return (0, types_2.isNumber)(value) && (value | 0) == value;
        };
        return Int;
    }(Number));
    exports.Int = Int;
    Int.__name__ = "Int";
    /** @deprecated */
    var Angle = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Angle, _super);
        function Angle() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Angle;
    }(Number));
    exports.Angle = Angle;
    Angle.__name__ = "Angle";
    /** @deprecated */
    var Percent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Percent, _super);
        function Percent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Percent.prototype.valid = function (value) {
            return (0, types_2.isNumber)(value) && 0 <= value && value <= 1.0;
        };
        return Percent;
    }(Number));
    exports.Percent = Percent;
    Percent.__name__ = "Percent";
    /** @deprecated */
    var String = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(String, _super);
        function String() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        String.prototype.valid = function (value) {
            return (0, types_2.isString)(value);
        };
        return String;
    }(Property));
    exports.String = String;
    String.__name__ = "String";
    /** @deprecated */
    var NullString = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NullString, _super);
        function NullString() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        NullString.prototype.valid = function (value) {
            return value === null || (0, types_2.isString)(value);
        };
        return NullString;
    }(Property));
    exports.NullString = NullString;
    NullString.__name__ = "NullString";
    /** @deprecated */
    var FontSize = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FontSize, _super);
        function FontSize() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return FontSize;
    }(String));
    exports.FontSize = FontSize;
    FontSize.__name__ = "FontSize";
    /** @deprecated */
    var Font = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Font, _super);
        function Font() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Font.prototype._default_override = function () {
            return settings_1.settings.dev ? "Bokeh" : undefined;
        };
        return Font;
    }(String));
    exports.Font = Font;
    Font.__name__ = "Font";
    //
    // Enum properties
    //
    /** @deprecated */
    var EnumProperty = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EnumProperty, _super);
        function EnumProperty() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        EnumProperty.prototype.valid = function (value) {
            return (0, types_2.isString)(value) && (0, array_1.includes)(this.enum_values, value);
        };
        return EnumProperty;
    }(Property));
    exports.EnumProperty = EnumProperty;
    EnumProperty.__name__ = "EnumProperty";
    /** @deprecated */
    function Enum(values) {
        return /** @class */ (function (_super) {
            (0, tslib_1.__extends)(class_1, _super);
            function class_1() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Object.defineProperty(class_1.prototype, "enum_values", {
                get: function () {
                    return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(values), false);
                },
                enumerable: false,
                configurable: true
            });
            return class_1;
        }(EnumProperty));
    }
    exports.Enum = Enum;
    var Direction = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Direction, _super);
        function Direction() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(Direction.prototype, "enum_values", {
            get: function () {
                return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(enums.Direction), false);
            },
            enumerable: false,
            configurable: true
        });
        Direction.prototype.normalize = function (values) {
            var result = new Uint8Array(values.length);
            for (var i = 0; i < values.length; i++) {
                switch (values[i]) {
                    case "clock":
                        result[i] = 0;
                        break;
                    case "anticlock":
                        result[i] = 1;
                        break;
                }
            }
            return result;
        };
        return Direction;
    }(EnumProperty));
    exports.Direction = Direction;
    Direction.__name__ = "Direction";
    /** @deprecated */ exports.Anchor = Enum(enums.Anchor);
    /** @deprecated */ exports.AngleUnits = Enum(enums.AngleUnits);
    /** @deprecated */ exports.BoxOrigin = Enum(enums.BoxOrigin);
    /** @deprecated */ exports.ButtonType = Enum(enums.ButtonType);
    /** @deprecated */ exports.CalendarPosition = Enum(enums.CalendarPosition);
    /** @deprecated */ exports.Dimension = Enum(enums.Dimension);
    /** @deprecated */ exports.Dimensions = Enum(enums.Dimensions);
    /** @deprecated */ exports.Distribution = Enum(enums.Distribution);
    /** @deprecated */ exports.FontStyle = Enum(enums.FontStyle);
    /** @deprecated */ exports.HatchPatternType = Enum(enums.HatchPatternType);
    /** @deprecated */ exports.HTTPMethod = Enum(enums.HTTPMethod);
    /** @deprecated */ exports.HexTileOrientation = Enum(enums.HexTileOrientation);
    /** @deprecated */ exports.HoverMode = Enum(enums.HoverMode);
    /** @deprecated */ exports.LatLon = Enum(enums.LatLon);
    /** @deprecated */ exports.LegendClickPolicy = Enum(enums.LegendClickPolicy);
    /** @deprecated */ exports.LegendLocation = Enum(enums.LegendLocation);
    /** @deprecated */ exports.LineCap = Enum(enums.LineCap);
    /** @deprecated */ exports.LineJoin = Enum(enums.LineJoin);
    /** @deprecated */ exports.LinePolicy = Enum(enums.LinePolicy);
    /** @deprecated */ exports.Location = Enum(enums.Location);
    /** @deprecated */ exports.Logo = Enum(enums.Logo);
    /** @deprecated */ exports.MarkerType = Enum(enums.MarkerType);
    /** @deprecated */ exports.MutedPolicy = Enum(enums.MutedPolicy);
    /** @deprecated */ exports.Orientation = Enum(enums.Orientation);
    /** @deprecated */ exports.OutputBackend = Enum(enums.OutputBackend);
    /** @deprecated */ exports.PaddingUnits = Enum(enums.PaddingUnits);
    /** @deprecated */ exports.Place = Enum(enums.Place);
    /** @deprecated */ exports.PointPolicy = Enum(enums.PointPolicy);
    /** @deprecated */ exports.RadiusDimension = Enum(enums.RadiusDimension);
    /** @deprecated */ exports.RenderLevel = Enum(enums.RenderLevel);
    /** @deprecated */ exports.RenderMode = Enum(enums.RenderMode);
    /** @deprecated */ exports.ResetPolicy = Enum(enums.ResetPolicy);
    /** @deprecated */ exports.RoundingFunction = Enum(enums.RoundingFunction);
    /** @deprecated */ exports.Side = Enum(enums.Side);
    /** @deprecated */ exports.SizingMode = Enum(enums.SizingMode);
    /** @deprecated */ exports.Sort = Enum(enums.Sort);
    /** @deprecated */ exports.SpatialUnits = Enum(enums.SpatialUnits);
    /** @deprecated */ exports.StartEnd = Enum(enums.StartEnd);
    /** @deprecated */ exports.StepMode = Enum(enums.StepMode);
    /** @deprecated */ exports.TapBehavior = Enum(enums.TapBehavior);
    /** @deprecated */ exports.TextAlign = Enum(enums.TextAlign);
    /** @deprecated */ exports.TextBaseline = Enum(enums.TextBaseline);
    /** @deprecated */ exports.TextureRepetition = Enum(enums.TextureRepetition);
    /** @deprecated */ exports.TickLabelOrientation = Enum(enums.TickLabelOrientation);
    /** @deprecated */ exports.TooltipAttachment = Enum(enums.TooltipAttachment);
    /** @deprecated */ exports.UpdateMode = Enum(enums.UpdateMode);
    /** @deprecated */ exports.VerticalAlign = Enum(enums.VerticalAlign);
    //
    // DataSpec properties
    //
    var ScalarSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ScalarSpec, _super);
        function ScalarSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ScalarSpec.prototype.get_value = function () {
            // XXX: denormalize value for serialization, because bokeh doens't support scalar properties
            var _a = this.spec, value = _a.value, expr = _a.expr, transform = _a.transform;
            return (expr != null || transform != null ? this.spec : value);
            // XXX: allow obj.x = null; obj.x == null
            // return this.spec.value === null ? null : this.spec as any
        };
        ScalarSpec.prototype._update = function (attr_value) {
            if (isSpec(attr_value))
                this.spec = attr_value;
            else
                this.spec = { value: attr_value };
            if (this.spec.value != null)
                this.validate(this.spec.value);
        };
        ScalarSpec.prototype.materialize = function (value) {
            return value;
        };
        ScalarSpec.prototype.scalar = function (value, n) {
            return new uniforms_1.UniformScalar(value, n);
        };
        ScalarSpec.prototype.uniform = function (source) {
            var _a;
            var _b = this.spec, expr = _b.expr, value = _b.value, transform = _b.transform;
            var n = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            if (expr != null) {
                var result = expr.compute(source);
                if (transform != null)
                    result = transform.compute(result);
                result = this.materialize(result);
                return this.scalar(result, n);
            }
            else {
                var result = value;
                if (transform != null)
                    result = transform.compute(result);
                result = this.materialize(result);
                return this.scalar(result, n);
            }
        };
        return ScalarSpec;
    }(Property));
    exports.ScalarSpec = ScalarSpec;
    ScalarSpec.__name__ = "ScalarSpec";
    var AnyScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AnyScalar, _super);
        function AnyScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return AnyScalar;
    }(ScalarSpec));
    exports.AnyScalar = AnyScalar;
    AnyScalar.__name__ = "AnyScalar";
    var ColorScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColorScalar, _super);
        function ColorScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ColorScalar;
    }(ScalarSpec));
    exports.ColorScalar = ColorScalar;
    ColorScalar.__name__ = "ColorScalar";
    var NumberScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NumberScalar, _super);
        function NumberScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return NumberScalar;
    }(ScalarSpec));
    exports.NumberScalar = NumberScalar;
    NumberScalar.__name__ = "NumberScalar";
    var StringScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(StringScalar, _super);
        function StringScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return StringScalar;
    }(ScalarSpec));
    exports.StringScalar = StringScalar;
    StringScalar.__name__ = "StringScalar";
    var NullStringScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NullStringScalar, _super);
        function NullStringScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return NullStringScalar;
    }(ScalarSpec));
    exports.NullStringScalar = NullStringScalar;
    NullStringScalar.__name__ = "NullStringScalar";
    var ArrayScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ArrayScalar, _super);
        function ArrayScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ArrayScalar;
    }(ScalarSpec));
    exports.ArrayScalar = ArrayScalar;
    ArrayScalar.__name__ = "ArrayScalar";
    var LineJoinScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineJoinScalar, _super);
        function LineJoinScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LineJoinScalar;
    }(ScalarSpec));
    exports.LineJoinScalar = LineJoinScalar;
    LineJoinScalar.__name__ = "LineJoinScalar";
    var LineCapScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineCapScalar, _super);
        function LineCapScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LineCapScalar;
    }(ScalarSpec));
    exports.LineCapScalar = LineCapScalar;
    LineCapScalar.__name__ = "LineCapScalar";
    var LineDashScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineDashScalar, _super);
        function LineDashScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LineDashScalar;
    }(ScalarSpec));
    exports.LineDashScalar = LineDashScalar;
    LineDashScalar.__name__ = "LineDashScalar";
    var FontScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FontScalar, _super);
        function FontScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        FontScalar.prototype._default_override = function () {
            return settings_1.settings.dev ? "Bokeh" : undefined;
        };
        return FontScalar;
    }(ScalarSpec));
    exports.FontScalar = FontScalar;
    FontScalar.__name__ = "FontScalar";
    var FontSizeScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FontSizeScalar, _super);
        function FontSizeScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return FontSizeScalar;
    }(ScalarSpec));
    exports.FontSizeScalar = FontSizeScalar;
    FontSizeScalar.__name__ = "FontSizeScalar";
    var FontStyleScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FontStyleScalar, _super);
        function FontStyleScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return FontStyleScalar;
    }(ScalarSpec));
    exports.FontStyleScalar = FontStyleScalar;
    FontStyleScalar.__name__ = "FontStyleScalar";
    var TextAlignScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextAlignScalar, _super);
        function TextAlignScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return TextAlignScalar;
    }(ScalarSpec));
    exports.TextAlignScalar = TextAlignScalar;
    TextAlignScalar.__name__ = "TextAlignScalar";
    var TextBaselineScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextBaselineScalar, _super);
        function TextBaselineScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return TextBaselineScalar;
    }(ScalarSpec));
    exports.TextBaselineScalar = TextBaselineScalar;
    TextBaselineScalar.__name__ = "TextBaselineScalar";
    var VectorSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VectorSpec, _super);
        function VectorSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        VectorSpec.prototype.get_value = function () {
            // XXX: allow obj.x = null; obj.x == null
            return this.spec.value === null ? null : this.spec;
        };
        VectorSpec.prototype._update = function (attr_value) {
            if (isSpec(attr_value))
                this.spec = attr_value;
            else
                this.spec = { value: attr_value };
            if (this.spec.value != null)
                this.validate(this.spec.value);
        };
        VectorSpec.prototype.materialize = function (value) {
            return value;
        };
        VectorSpec.prototype.v_materialize = function (values) {
            return values;
        };
        VectorSpec.prototype.scalar = function (value, n) {
            return new uniforms_1.UniformScalar(value, n);
        };
        VectorSpec.prototype.vector = function (values) {
            return new uniforms_1.UniformVector(values);
        };
        VectorSpec.prototype.uniform = function (source) {
            var _a;
            var _b = this.spec, field = _b.field, expr = _b.expr, value = _b.value, transform = _b.transform;
            var n = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            if (field != null) {
                var array = source.get_column(field);
                if (array != null) {
                    if (transform != null)
                        array = transform.v_compute(array);
                    array = this.v_materialize(array);
                    return this.vector(array);
                }
                else {
                    logging_1.logger.warn("attempted to retrieve property array for nonexistent field '" + field + "'");
                    return this.scalar(null, n);
                }
            }
            else if (expr != null) {
                var array = expr.v_compute(source);
                if (transform != null)
                    array = transform.v_compute(array);
                array = this.v_materialize(array);
                return this.vector(array);
            }
            else {
                var result = value;
                if (transform != null)
                    result = transform.compute(result);
                result = this.materialize(result);
                return this.scalar(result, n);
            }
        };
        VectorSpec.prototype.array = function (source) {
            var _a;
            var array;
            var length = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            if (this.spec.field != null) {
                var column = source.get_column(this.spec.field);
                if (column != null)
                    array = this.normalize(column);
                else {
                    logging_1.logger.warn("attempted to retrieve property array for nonexistent field '" + this.spec.field + "'");
                    var missing = new Float64Array(length);
                    missing.fill(NaN);
                    array = missing;
                }
            }
            else if (this.spec.expr != null) {
                array = this.normalize(this.spec.expr.v_compute(source));
            }
            else {
                var value = this._value(false); // don't apply any spec transform
                if ((0, types_2.isNumber)(value)) {
                    var values = new Float64Array(length);
                    values.fill(value);
                    array = values;
                }
                else
                    array = (0, array_1.repeat)(value, length);
            }
            if (this.spec.transform != null)
                array = this.spec.transform.v_compute(array);
            return array;
        };
        return VectorSpec;
    }(Property));
    exports.VectorSpec = VectorSpec;
    VectorSpec.__name__ = "VectorSpec";
    var DataSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DataSpec, _super);
        function DataSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return DataSpec;
    }(VectorSpec));
    exports.DataSpec = DataSpec;
    DataSpec.__name__ = "DataSpec";
    var UnitsSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UnitsSpec, _super);
        function UnitsSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        UnitsSpec.prototype._update = function (attr_value) {
            _super.prototype._update.call(this, attr_value);
            var units = this.spec.units;
            if (units != null && !(0, array_1.includes)(this.valid_units, units)) {
                throw new Error("units must be one of " + this.valid_units.join(", ") + "; got: " + units);
            }
        };
        Object.defineProperty(UnitsSpec.prototype, "units", {
            get: function () {
                var _a;
                return (_a = this.spec.units) !== null && _a !== void 0 ? _a : this.default_units;
            },
            set: function (units) {
                if (units != this.default_units)
                    this.spec.units = units;
                else
                    delete this.spec.units;
            },
            enumerable: false,
            configurable: true
        });
        return UnitsSpec;
    }(VectorSpec));
    exports.UnitsSpec = UnitsSpec;
    UnitsSpec.__name__ = "UnitsSpec";
    var NumberUnitsSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NumberUnitsSpec, _super);
        function NumberUnitsSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        NumberUnitsSpec.prototype.array = function (source) {
            return new Float64Array(_super.prototype.array.call(this, source));
        };
        return NumberUnitsSpec;
    }(UnitsSpec));
    exports.NumberUnitsSpec = NumberUnitsSpec;
    NumberUnitsSpec.__name__ = "NumberUnitsSpec";
    var BaseCoordinateSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BaseCoordinateSpec, _super);
        function BaseCoordinateSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return BaseCoordinateSpec;
    }(DataSpec));
    exports.BaseCoordinateSpec = BaseCoordinateSpec;
    BaseCoordinateSpec.__name__ = "BaseCoordinateSpec";
    var CoordinateSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CoordinateSpec, _super);
        function CoordinateSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return CoordinateSpec;
    }(BaseCoordinateSpec));
    exports.CoordinateSpec = CoordinateSpec;
    CoordinateSpec.__name__ = "CoordinateSpec";
    var CoordinateSeqSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CoordinateSeqSpec, _super);
        function CoordinateSeqSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return CoordinateSeqSpec;
    }(BaseCoordinateSpec));
    exports.CoordinateSeqSpec = CoordinateSeqSpec;
    CoordinateSeqSpec.__name__ = "CoordinateSeqSpec";
    var CoordinateSeqSeqSeqSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CoordinateSeqSeqSeqSpec, _super);
        function CoordinateSeqSeqSeqSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return CoordinateSeqSeqSeqSpec;
    }(BaseCoordinateSpec));
    exports.CoordinateSeqSeqSeqSpec = CoordinateSeqSeqSeqSpec;
    CoordinateSeqSeqSeqSpec.__name__ = "CoordinateSeqSeqSeqSpec";
    var XCoordinateSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(XCoordinateSpec, _super);
        function XCoordinateSpec() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.dimension = "x";
            return _this;
        }
        return XCoordinateSpec;
    }(CoordinateSpec));
    exports.XCoordinateSpec = XCoordinateSpec;
    XCoordinateSpec.__name__ = "XCoordinateSpec";
    var YCoordinateSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(YCoordinateSpec, _super);
        function YCoordinateSpec() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.dimension = "y";
            return _this;
        }
        return YCoordinateSpec;
    }(CoordinateSpec));
    exports.YCoordinateSpec = YCoordinateSpec;
    YCoordinateSpec.__name__ = "YCoordinateSpec";
    var XCoordinateSeqSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(XCoordinateSeqSpec, _super);
        function XCoordinateSeqSpec() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.dimension = "x";
            return _this;
        }
        return XCoordinateSeqSpec;
    }(CoordinateSeqSpec));
    exports.XCoordinateSeqSpec = XCoordinateSeqSpec;
    XCoordinateSeqSpec.__name__ = "XCoordinateSeqSpec";
    var YCoordinateSeqSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(YCoordinateSeqSpec, _super);
        function YCoordinateSeqSpec() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.dimension = "y";
            return _this;
        }
        return YCoordinateSeqSpec;
    }(CoordinateSeqSpec));
    exports.YCoordinateSeqSpec = YCoordinateSeqSpec;
    YCoordinateSeqSpec.__name__ = "YCoordinateSeqSpec";
    var XCoordinateSeqSeqSeqSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(XCoordinateSeqSeqSeqSpec, _super);
        function XCoordinateSeqSeqSeqSpec() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.dimension = "x";
            return _this;
        }
        return XCoordinateSeqSeqSeqSpec;
    }(CoordinateSeqSeqSeqSpec));
    exports.XCoordinateSeqSeqSeqSpec = XCoordinateSeqSeqSeqSpec;
    XCoordinateSeqSeqSeqSpec.__name__ = "XCoordinateSeqSeqSeqSpec";
    var YCoordinateSeqSeqSeqSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(YCoordinateSeqSeqSeqSpec, _super);
        function YCoordinateSeqSeqSeqSpec() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.dimension = "y";
            return _this;
        }
        return YCoordinateSeqSeqSeqSpec;
    }(CoordinateSeqSeqSeqSpec));
    exports.YCoordinateSeqSeqSeqSpec = YCoordinateSeqSeqSeqSpec;
    YCoordinateSeqSeqSeqSpec.__name__ = "YCoordinateSeqSeqSeqSpec";
    var AngleSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AngleSpec, _super);
        function AngleSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(AngleSpec.prototype, "default_units", {
            get: function () { return "rad"; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AngleSpec.prototype, "valid_units", {
            get: function () { return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(enums.AngleUnits), false); },
            enumerable: false,
            configurable: true
        });
        AngleSpec.prototype.materialize = function (value) {
            var coeff = -(0, math_1.to_radians_coeff)(this.units);
            return value * coeff;
        };
        AngleSpec.prototype.v_materialize = function (values) {
            var coeff = -(0, math_1.to_radians_coeff)(this.units);
            var result = new Float32Array(values.length);
            (0, arrayable_1.mul)(values, coeff, result); // TODO: in-place?
            return result;
        };
        AngleSpec.prototype.array = function (_source) {
            throw new Error("not supported");
        };
        return AngleSpec;
    }(NumberUnitsSpec));
    exports.AngleSpec = AngleSpec;
    AngleSpec.__name__ = "AngleSpec";
    var DistanceSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DistanceSpec, _super);
        function DistanceSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(DistanceSpec.prototype, "default_units", {
            get: function () { return "data"; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DistanceSpec.prototype, "valid_units", {
            get: function () { return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(enums.SpatialUnits), false); },
            enumerable: false,
            configurable: true
        });
        return DistanceSpec;
    }(NumberUnitsSpec));
    exports.DistanceSpec = DistanceSpec;
    DistanceSpec.__name__ = "DistanceSpec";
    var NullDistanceSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NullDistanceSpec, _super);
        function NullDistanceSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        NullDistanceSpec.prototype.materialize = function (value) {
            return value !== null && value !== void 0 ? value : NaN;
        };
        return NullDistanceSpec;
    }(DistanceSpec));
    exports.NullDistanceSpec = NullDistanceSpec;
    NullDistanceSpec.__name__ = "NullDistanceSpec";
    var BooleanSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BooleanSpec, _super);
        function BooleanSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BooleanSpec.prototype.v_materialize = function (values) {
            return new Uint8Array(values);
        };
        BooleanSpec.prototype.array = function (source) {
            return new Uint8Array(_super.prototype.array.call(this, source));
        };
        return BooleanSpec;
    }(DataSpec));
    exports.BooleanSpec = BooleanSpec;
    BooleanSpec.__name__ = "BooleanSpec";
    var IntSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(IntSpec, _super);
        function IntSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        IntSpec.prototype.v_materialize = function (values) {
            return (0, types_2.isTypedArray)(values) ? values : new Int32Array(values);
        };
        IntSpec.prototype.array = function (source) {
            return new Int32Array(_super.prototype.array.call(this, source));
        };
        return IntSpec;
    }(DataSpec));
    exports.IntSpec = IntSpec;
    IntSpec.__name__ = "IntSpec";
    var NumberSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NumberSpec, _super);
        function NumberSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        NumberSpec.prototype.v_materialize = function (values) {
            return (0, types_2.isTypedArray)(values) ? values : new Float64Array(values);
        };
        NumberSpec.prototype.array = function (source) {
            return new Float64Array(_super.prototype.array.call(this, source));
        };
        return NumberSpec;
    }(DataSpec));
    exports.NumberSpec = NumberSpec;
    NumberSpec.__name__ = "NumberSpec";
    var ScreenSizeSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ScreenSizeSpec, _super);
        function ScreenSizeSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ScreenSizeSpec.prototype.valid = function (value) {
            return (0, types_2.isNumber)(value) && value >= 0;
        };
        return ScreenSizeSpec;
    }(NumberSpec));
    exports.ScreenSizeSpec = ScreenSizeSpec;
    ScreenSizeSpec.__name__ = "ScreenSizeSpec";
    var ColorSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColorSpec, _super);
        function ColorSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ColorSpec.prototype.materialize = function (color) {
            return (0, color_1.encode_rgba)((0, color_1.color2rgba)(color));
        };
        ColorSpec.prototype.v_materialize = function (colors) {
            var e_1, _a, e_2, _b;
            if ((0, ndarray_1.is_NDArray)(colors)) {
                if (colors.dtype == "uint32" && colors.dimension == 1) {
                    return (0, platform_1.to_big_endian)(colors);
                }
                else if (colors.dtype == "uint8" && colors.dimension == 1) {
                    var _c = (0, tslib_1.__read)(colors.shape, 1), n = _c[0];
                    var array = new types_1.RGBAArray(4 * n);
                    var j = 0;
                    try {
                        for (var colors_1 = (0, tslib_1.__values)(colors), colors_1_1 = colors_1.next(); !colors_1_1.done; colors_1_1 = colors_1.next()) {
                            var gray = colors_1_1.value;
                            array[j++] = gray;
                            array[j++] = gray;
                            array[j++] = gray;
                            array[j++] = 255;
                        }
                    }
                    catch (e_1_1) {
                        e_1 = { error: e_1_1 };
                    }
                    finally {
                        try {
                            if (colors_1_1 && !colors_1_1.done && (_a = colors_1.return))
                                _a.call(colors_1);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                    }
                    return new types_1.ColorArray(array.buffer);
                }
                else if (colors.dtype == "uint8" && colors.dimension == 2) {
                    var _d = (0, tslib_1.__read)(colors.shape, 2), n = _d[0], d = _d[1];
                    if (d == 4) {
                        return new types_1.ColorArray(colors.buffer);
                    }
                    else if (d == 3) {
                        var array = new types_1.RGBAArray(4 * n);
                        for (var i = 0, j = 0; i < d * n;) {
                            array[j++] = colors[i++];
                            array[j++] = colors[i++];
                            array[j++] = colors[i++];
                            array[j++] = 255;
                        }
                        return new types_1.ColorArray(array.buffer);
                    }
                }
                else if ((colors.dtype == "float32" || colors.dtype == "float64") && colors.dimension == 2) {
                    var _e = (0, tslib_1.__read)(colors.shape, 2), n = _e[0], d = _e[1];
                    if (d == 3 || d == 4) {
                        var array = new types_1.RGBAArray(4 * n);
                        for (var i = 0, j = 0; i < d * n;) {
                            array[j++] = colors[i++] * 255;
                            array[j++] = colors[i++] * 255;
                            array[j++] = colors[i++] * 255;
                            array[j++] = (d == 3 ? 1 : colors[i++]) * 255;
                        }
                        return new types_1.ColorArray(array.buffer);
                    }
                }
            }
            else {
                var n = colors.length;
                var array = new types_1.RGBAArray(4 * n);
                var j = 0;
                try {
                    for (var colors_2 = (0, tslib_1.__values)(colors), colors_2_1 = colors_2.next(); !colors_2_1.done; colors_2_1 = colors_2.next()) {
                        var color = colors_2_1.value;
                        var _f = (0, tslib_1.__read)((0, color_1.color2rgba)(color), 4), r = _f[0], g = _f[1], b = _f[2], a = _f[3];
                        array[j++] = r;
                        array[j++] = g;
                        array[j++] = b;
                        array[j++] = a;
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (colors_2_1 && !colors_2_1.done && (_b = colors_2.return))
                            _b.call(colors_2);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
                return new types_1.ColorArray(array.buffer);
            }
            throw new Error("invalid color array");
        };
        ColorSpec.prototype.vector = function (values) {
            return new uniforms_1.ColorUniformVector(values);
        };
        return ColorSpec;
    }(DataSpec));
    exports.ColorSpec = ColorSpec;
    ColorSpec.__name__ = "ColorSpec";
    var NDArraySpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NDArraySpec, _super);
        function NDArraySpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return NDArraySpec;
    }(DataSpec));
    exports.NDArraySpec = NDArraySpec;
    NDArraySpec.__name__ = "NDArraySpec";
    var AnySpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AnySpec, _super);
        function AnySpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return AnySpec;
    }(DataSpec));
    exports.AnySpec = AnySpec;
    AnySpec.__name__ = "AnySpec";
    var StringSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(StringSpec, _super);
        function StringSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return StringSpec;
    }(DataSpec));
    exports.StringSpec = StringSpec;
    StringSpec.__name__ = "StringSpec";
    var NullStringSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NullStringSpec, _super);
        function NullStringSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return NullStringSpec;
    }(DataSpec));
    exports.NullStringSpec = NullStringSpec;
    NullStringSpec.__name__ = "NullStringSpec";
    var ArraySpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ArraySpec, _super);
        function ArraySpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ArraySpec;
    }(DataSpec));
    exports.ArraySpec = ArraySpec;
    ArraySpec.__name__ = "ArraySpec";
    var MarkerSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MarkerSpec, _super);
        function MarkerSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return MarkerSpec;
    }(DataSpec));
    exports.MarkerSpec = MarkerSpec;
    MarkerSpec.__name__ = "MarkerSpec";
    var LineJoinSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineJoinSpec, _super);
        function LineJoinSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LineJoinSpec;
    }(DataSpec));
    exports.LineJoinSpec = LineJoinSpec;
    LineJoinSpec.__name__ = "LineJoinSpec";
    var LineCapSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineCapSpec, _super);
        function LineCapSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LineCapSpec;
    }(DataSpec));
    exports.LineCapSpec = LineCapSpec;
    LineCapSpec.__name__ = "LineCapSpec";
    var LineDashSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineDashSpec, _super);
        function LineDashSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LineDashSpec;
    }(DataSpec));
    exports.LineDashSpec = LineDashSpec;
    LineDashSpec.__name__ = "LineDashSpec";
    var FontSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FontSpec, _super);
        function FontSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        FontSpec.prototype._default_override = function () {
            return settings_1.settings.dev ? "Bokeh" : undefined;
        };
        return FontSpec;
    }(DataSpec));
    exports.FontSpec = FontSpec;
    FontSpec.__name__ = "FontSpec";
    var FontSizeSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FontSizeSpec, _super);
        function FontSizeSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return FontSizeSpec;
    }(DataSpec));
    exports.FontSizeSpec = FontSizeSpec;
    FontSizeSpec.__name__ = "FontSizeSpec";
    var FontStyleSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FontStyleSpec, _super);
        function FontStyleSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return FontStyleSpec;
    }(DataSpec));
    exports.FontStyleSpec = FontStyleSpec;
    FontStyleSpec.__name__ = "FontStyleSpec";
    var TextAlignSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextAlignSpec, _super);
        function TextAlignSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return TextAlignSpec;
    }(DataSpec));
    exports.TextAlignSpec = TextAlignSpec;
    TextAlignSpec.__name__ = "TextAlignSpec";
    var TextBaselineSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextBaselineSpec, _super);
        function TextBaselineSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return TextBaselineSpec;
    }(DataSpec));
    exports.TextBaselineSpec = TextBaselineSpec;
    TextBaselineSpec.__name__ = "TextBaselineSpec";
},
/* core/logging.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    // This is based on https://github.com/pimterry/loglevel
    var types_1 = require(125) /* ./util/types */;
    var object_1 = require(128) /* ./util/object */;
    var _loggers = {};
    var LogLevel = /** @class */ (function () {
        function LogLevel(name, level) {
            this.name = name;
            this.level = level;
        }
        return LogLevel;
    }());
    exports.LogLevel = LogLevel;
    LogLevel.__name__ = "LogLevel";
    var Logger = /** @class */ (function () {
        function Logger(name, level) {
            if (level === void 0) {
                level = Logger.INFO;
            }
            this._name = name;
            this.set_level(level);
        }
        Object.defineProperty(Logger, "levels", {
            get: function () {
                return Object.keys(Logger.log_levels);
            },
            enumerable: false,
            configurable: true
        });
        Logger.get = function (name, level) {
            if (level === void 0) {
                level = Logger.INFO;
            }
            if (name.length > 0) {
                var logger_1 = _loggers[name];
                if (logger_1 == null)
                    _loggers[name] = logger_1 = new Logger(name, level);
                return logger_1;
            }
            else
                throw new TypeError("Logger.get() expects a non-empty string name and an optional log-level");
        };
        Object.defineProperty(Logger.prototype, "level", {
            get: function () {
                return this.get_level();
            },
            enumerable: false,
            configurable: true
        });
        Logger.prototype.get_level = function () {
            return this._log_level;
        };
        Logger.prototype.set_level = function (log_level) {
            var e_1, _a;
            if (log_level instanceof LogLevel)
                this._log_level = log_level;
            else if ((0, types_1.isString)(log_level) && Logger.log_levels[log_level] != null)
                this._log_level = Logger.log_levels[log_level];
            else
                throw new Error("Logger.set_level() expects a log-level object or a string name of a log-level");
            var logger_name = "[" + this._name + "]";
            try {
                for (var _b = (0, tslib_1.__values)((0, object_1.entries)(Logger.log_levels)), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var _d = (0, tslib_1.__read)(_c.value, 2), name = _d[0], log_level_1 = _d[1];
                    if (log_level_1.level < this._log_level.level || this._log_level.level === Logger.OFF.level)
                        this[name] = function () { };
                    else
                        this[name] = _method_factory(name, logger_name);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        Logger.prototype.trace = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
        };
        Logger.prototype.debug = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
        };
        Logger.prototype.info = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
        };
        Logger.prototype.warn = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
        };
        Logger.prototype.error = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
        };
        return Logger;
    }());
    exports.Logger = Logger;
    Logger.__name__ = "Logger";
    Logger.TRACE = new LogLevel("trace", 0);
    Logger.DEBUG = new LogLevel("debug", 1);
    Logger.INFO = new LogLevel("info", 2);
    Logger.WARN = new LogLevel("warn", 6);
    Logger.ERROR = new LogLevel("error", 7);
    Logger.FATAL = new LogLevel("fatal", 8);
    Logger.OFF = new LogLevel("off", 9);
    Logger.log_levels = {
        trace: Logger.TRACE,
        debug: Logger.DEBUG,
        info: Logger.INFO,
        warn: Logger.WARN,
        error: Logger.ERROR,
        fatal: Logger.FATAL,
        off: Logger.OFF,
    };
    function _method_factory(method_name, logger_name) {
        if (console[method_name] != null)
            return console[method_name].bind(console, logger_name);
        else if (console.log != null)
            return console.log.bind(console, logger_name);
        else
            return function () { };
    }
    exports.logger = Logger.get("bokeh");
    function set_log_level(level) {
        var previous_level = exports.logger.level;
        if ((0, types_1.isString)(level) && Logger.log_levels[level] == null) {
            console.log("[bokeh] unrecognized logging level '" + level + "' passed to Bokeh.set_log_level(), ignoring");
            console.log("[bokeh] valid log levels are: " + Logger.levels.join(", "));
        }
        else {
            console.log("[bokeh] setting log level to: '" + ((0, types_1.isString)(level) ? level : level.level) + "'");
            exports.logger.set_level(level);
        }
        return previous_level;
    }
    exports.set_log_level = set_log_level;
    function with_log_level(level, fn) {
        var original = set_log_level(level);
        try {
            fn();
        }
        finally {
            set_log_level(original);
        }
    }
    exports.with_log_level = with_log_level;
},
/* core/enums.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.VerticalAlign = void 0;
    var kinds_1 = require(136) /* ./kinds */;
    exports.Align = (0, kinds_1.Enum)("start", "center", "end");
    exports.Anchor = (0, kinds_1.Enum)("top_left", "top_center", "top_right", "center_left", "center_center", "center_right", "bottom_left", "bottom_center", "bottom_right", "top", "left", "center", "right", "bottom");
    exports.AngleUnits = (0, kinds_1.Enum)("deg", "rad", "grad", "turn");
    exports.BoxOrigin = (0, kinds_1.Enum)("corner", "center");
    exports.ButtonType = (0, kinds_1.Enum)("default", "primary", "success", "warning", "danger", "light");
    exports.CalendarPosition = (0, kinds_1.Enum)("auto", "above", "below");
    exports.Dimension = (0, kinds_1.Enum)("width", "height");
    exports.Dimensions = (0, kinds_1.Enum)("width", "height", "both");
    exports.Direction = (0, kinds_1.Enum)("clock", "anticlock");
    exports.Distribution = (0, kinds_1.Enum)("uniform", "normal");
    exports.FontStyle = (0, kinds_1.Enum)("normal", "italic", "bold", "bold italic");
    exports.HatchPatternType = (0, kinds_1.Enum)("blank", "dot", "ring", "horizontal_line", "vertical_line", "cross", "horizontal_dash", "vertical_dash", "spiral", "right_diagonal_line", "left_diagonal_line", "diagonal_cross", "right_diagonal_dash", "left_diagonal_dash", "horizontal_wave", "vertical_wave", "criss_cross", " ", ".", "o", "-", "|", "+", '"', ":", "@", "/", "\\", "x", ",", "`", "v", ">", "*");
    exports.HTTPMethod = (0, kinds_1.Enum)("POST", "GET");
    exports.HexTileOrientation = (0, kinds_1.Enum)("pointytop", "flattop");
    exports.HoverMode = (0, kinds_1.Enum)("mouse", "hline", "vline");
    exports.LatLon = (0, kinds_1.Enum)("lat", "lon");
    exports.LegendClickPolicy = (0, kinds_1.Enum)("none", "hide", "mute");
    exports.LegendLocation = exports.Anchor;
    exports.LineCap = (0, kinds_1.Enum)("butt", "round", "square");
    exports.LineJoin = (0, kinds_1.Enum)("miter", "round", "bevel");
    exports.LineDash = (0, kinds_1.Enum)("solid", "dashed", "dotted", "dotdash", "dashdot");
    exports.LinePolicy = (0, kinds_1.Enum)("prev", "next", "nearest", "interp", "none");
    exports.Location = (0, kinds_1.Enum)("above", "below", "left", "right");
    exports.Logo = (0, kinds_1.Enum)("normal", "grey");
    exports.MarkerType = (0, kinds_1.Enum)("asterisk", "circle", "circle_cross", "circle_dot", "circle_x", "circle_y", "cross", "dash", "diamond", "diamond_cross", "diamond_dot", "dot", "hex", "hex_dot", "inverted_triangle", "plus", "square", "square_cross", "square_dot", "square_pin", "square_x", "star", "star_dot", "triangle", "triangle_dot", "triangle_pin", "x", "y");
    exports.MutedPolicy = (0, kinds_1.Enum)("show", "ignore");
    exports.Orientation = (0, kinds_1.Enum)("vertical", "horizontal");
    exports.OutputBackend = (0, kinds_1.Enum)("canvas", "svg", "webgl");
    exports.PaddingUnits = (0, kinds_1.Enum)("percent", "absolute");
    exports.Place = (0, kinds_1.Enum)("above", "below", "left", "right", "center");
    exports.PointPolicy = (0, kinds_1.Enum)("snap_to_data", "follow_mouse", "none");
    exports.RadiusDimension = (0, kinds_1.Enum)("x", "y", "max", "min");
    exports.RenderLevel = (0, kinds_1.Enum)("image", "underlay", "glyph", "guide", "annotation", "overlay");
    exports.RenderMode = (0, kinds_1.Enum)("canvas", "css");
    exports.ResetPolicy = (0, kinds_1.Enum)("standard", "event_only");
    exports.RoundingFunction = (0, kinds_1.Enum)("round", "nearest", "floor", "rounddown", "ceil", "roundup");
    exports.SelectionMode = (0, kinds_1.Enum)("replace", "append", "intersect", "subtract");
    exports.Side = (0, kinds_1.Enum)("above", "below", "left", "right");
    exports.SizingMode = (0, kinds_1.Enum)("stretch_width", "stretch_height", "stretch_both", "scale_width", "scale_height", "scale_both", "fixed");
    exports.Sort = (0, kinds_1.Enum)("ascending", "descending");
    exports.SpatialUnits = (0, kinds_1.Enum)("screen", "data");
    exports.StartEnd = (0, kinds_1.Enum)("start", "end");
    exports.StepMode = (0, kinds_1.Enum)("after", "before", "center");
    exports.TapBehavior = (0, kinds_1.Enum)("select", "inspect");
    exports.TextAlign = (0, kinds_1.Enum)("left", "right", "center");
    exports.TextBaseline = (0, kinds_1.Enum)("top", "middle", "bottom", "alphabetic", "hanging", "ideographic");
    exports.TextureRepetition = (0, kinds_1.Enum)("repeat", "repeat_x", "repeat_y", "no_repeat");
    exports.TickLabelOrientation = (0, kinds_1.Enum)("vertical", "horizontal", "parallel", "normal");
    exports.TooltipAttachment = (0, kinds_1.Enum)("horizontal", "vertical", "left", "right", "above", "below");
    exports.UpdateMode = (0, kinds_1.Enum)("replace", "append");
    exports.VerticalAlign = (0, kinds_1.Enum)("top", "middle", "bottom");
},
/* core/kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var tp = (0, tslib_1.__importStar)(require(125) /* ./util/types */);
    var color_1 = require(137) /* ./util/color */;
    var object_1 = require(128) /* ./util/object */;
    var ESMap = window.Map;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var Kind = /** @class */ (function () {
        function Kind() {
        }
        return Kind;
    }());
    exports.Kind = Kind;
    Kind.__name__ = "Kind";
    (function (Kinds) {
        var Any = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Any, _super);
            function Any() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Any.prototype.valid = function (_value) {
                return true;
            };
            return Any;
        }(Kind));
        Any.__name__ = "Any";
        Kinds.Any = Any;
        var Unknown = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Unknown, _super);
            function Unknown() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Unknown.prototype.valid = function (_value) {
                return true;
            };
            return Unknown;
        }(Kind));
        Unknown.__name__ = "Unknown";
        Kinds.Unknown = Unknown;
        var Boolean = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Boolean, _super);
            function Boolean() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Boolean.prototype.valid = function (value) {
                return tp.isBoolean(value);
            };
            return Boolean;
        }(Kind));
        Boolean.__name__ = "Boolean";
        Kinds.Boolean = Boolean;
        var Ref = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Ref, _super);
            function Ref(obj_type) {
                var _this = _super.call(this) || this;
                _this.obj_type = obj_type;
                return _this;
            }
            Ref.prototype.valid = function (_value) {
                // XXX: disable validation for now, because object graph initialization depends on this.
                // return value instanceof this.obj_type
                return true;
            };
            return Ref;
        }(Kind));
        Ref.__name__ = "Ref";
        Kinds.Ref = Ref;
        var AnyRef = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(AnyRef, _super);
            function AnyRef() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            AnyRef.prototype.valid = function (_value) {
                // XXX: disable validation for now, because object graph initialization depends on this.
                // return tp.isObject(value)
                return true;
            };
            return AnyRef;
        }(Kind));
        AnyRef.__name__ = "AnyRef";
        Kinds.AnyRef = AnyRef;
        var Number = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Number, _super);
            function Number() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Number.prototype.valid = function (value) {
                return tp.isNumber(value);
            };
            return Number;
        }(Kind));
        Number.__name__ = "Number";
        Kinds.Number = Number;
        var Int = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Int, _super);
            function Int() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Int.prototype.valid = function (value) {
                return _super.prototype.valid.call(this, value) && tp.isInteger(value);
            };
            return Int;
        }(Number));
        Int.__name__ = "Int";
        Kinds.Int = Int;
        var Percent = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Percent, _super);
            function Percent() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Percent.prototype.valid = function (value) {
                return _super.prototype.valid.call(this, value) && 0 <= value && value <= 1;
            };
            return Percent;
        }(Number));
        Percent.__name__ = "Percent";
        Kinds.Percent = Percent;
        var Or = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Or, _super);
            function Or(types) {
                var _this = _super.call(this) || this;
                _this.types = types;
                _this.types = types;
                return _this;
            }
            Or.prototype.valid = function (value) {
                return this.types.some(function (type) { return type.valid(value); });
            };
            return Or;
        }(Kind));
        Or.__name__ = "Or";
        Kinds.Or = Or;
        var Tuple = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Tuple, _super);
            function Tuple(types) {
                var _this = _super.call(this) || this;
                _this.types = types;
                _this.types = types;
                return _this;
            }
            Tuple.prototype.valid = function (value) {
                if (!tp.isArray(value))
                    return false;
                for (var i = 0; i < this.types.length; i++) {
                    var type = this.types[i];
                    var item = value[i];
                    if (!type.valid(item))
                        return false;
                }
                return true;
            };
            return Tuple;
        }(Kind));
        Tuple.__name__ = "Tuple";
        Kinds.Tuple = Tuple;
        var Struct = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Struct, _super);
            function Struct(struct_type) {
                var _this = _super.call(this) || this;
                _this.struct_type = struct_type;
                return _this;
            }
            Struct.prototype.valid = function (value) {
                if (!tp.isPlainObject(value))
                    return false;
                var struct_type = this.struct_type;
                if ((0, object_1.size)(struct_type) != (0, object_1.size)(value))
                    return false;
                for (var key in struct_type) {
                    if (hasOwnProperty.call(struct_type, key)) {
                        if (!hasOwnProperty.call(value, key))
                            return false;
                        var item_type = struct_type[key];
                        var item = value[key];
                        if (!item_type.valid(item))
                            return false;
                    }
                }
                return true;
            };
            return Struct;
        }(Kind));
        Struct.__name__ = "Struct";
        Kinds.Struct = Struct;
        var Arrayable = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Arrayable, _super);
            function Arrayable() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Arrayable.prototype.valid = function (value) {
                return tp.isArray(value) || tp.isTypedArray(value); // TODO: too specific
            };
            return Arrayable;
        }(Kind));
        Arrayable.__name__ = "Arrayable";
        Kinds.Arrayable = Arrayable;
        var Array = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Array, _super);
            function Array(item_type) {
                var _this = _super.call(this) || this;
                _this.item_type = item_type;
                return _this;
            }
            Array.prototype.valid = function (value) {
                var _this = this;
                return tp.isArray(value) && value.every(function (item) { return _this.item_type.valid(item); });
            };
            return Array;
        }(Kind));
        Array.__name__ = "Array";
        Kinds.Array = Array;
        var Null = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Null, _super);
            function Null() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Null.prototype.valid = function (value) {
                return value === null;
            };
            return Null;
        }(Kind));
        Null.__name__ = "Null";
        Kinds.Null = Null;
        var Nullable = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Nullable, _super);
            function Nullable(base_type) {
                var _this = _super.call(this) || this;
                _this.base_type = base_type;
                return _this;
            }
            Nullable.prototype.valid = function (value) {
                return value === null || this.base_type.valid(value);
            };
            return Nullable;
        }(Kind));
        Nullable.__name__ = "Nullable";
        Kinds.Nullable = Nullable;
        var Opt = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Opt, _super);
            function Opt(base_type) {
                var _this = _super.call(this) || this;
                _this.base_type = base_type;
                return _this;
            }
            Opt.prototype.valid = function (value) {
                return value === undefined || this.base_type.valid(value);
            };
            return Opt;
        }(Kind));
        Opt.__name__ = "Opt";
        Kinds.Opt = Opt;
        var String = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(String, _super);
            function String() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            String.prototype.valid = function (value) {
                return tp.isString(value);
            };
            return String;
        }(Kind));
        String.__name__ = "String";
        Kinds.String = String;
        var Enum = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Enum, _super);
            function Enum(values) {
                var _this = _super.call(this) || this;
                _this.values = new Set(values);
                return _this;
            }
            Enum.prototype.valid = function (value) {
                return this.values.has(value);
            };
            Enum.prototype[Symbol.iterator] = function () {
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [5 /*yield**/, (0, tslib_1.__values)(this.values)];
                        case 1:
                            _a.sent();
                            return [2 /*return*/];
                    }
                });
            };
            return Enum;
        }(Kind));
        Enum.__name__ = "Enum";
        Kinds.Enum = Enum;
        var Dict = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Dict, _super);
            function Dict(item_type) {
                var _this = _super.call(this) || this;
                _this.item_type = item_type;
                return _this;
            }
            Dict.prototype.valid = function (value) {
                if (!tp.isPlainObject(value))
                    return false;
                for (var key in value) {
                    if (hasOwnProperty.call(value, key)) {
                        var item = value[key];
                        if (!this.item_type.valid(item))
                            return false;
                    }
                }
                return true;
            };
            return Dict;
        }(Kind));
        Dict.__name__ = "Dict";
        Kinds.Dict = Dict;
        var Map = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Map, _super);
            function Map(key_type, item_type) {
                var _this = _super.call(this) || this;
                _this.key_type = key_type;
                _this.item_type = item_type;
                return _this;
            }
            Map.prototype.valid = function (value) {
                var e_1, _a;
                if (!(value instanceof ESMap))
                    return false;
                try {
                    for (var _b = (0, tslib_1.__values)(value.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var _d = (0, tslib_1.__read)(_c.value, 2), key = _d[0], item = _d[1];
                        if (!(this.key_type.valid(key) && this.item_type.valid(item)))
                            return false;
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
                return true;
            };
            return Map;
        }(Kind));
        Map.__name__ = "Map";
        Kinds.Map = Map;
        var Color = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Color, _super);
            function Color() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Color.prototype.valid = function (value) {
                return (0, color_1.is_Color)(value);
            };
            return Color;
        }(Kind));
        Color.__name__ = "Color";
        Kinds.Color = Color;
        var Function = /** @class */ (function (_super) {
            (0, tslib_1.__extends)(Function, _super);
            function Function() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Function.prototype.valid = function (value) {
                return tp.isFunction(value);
            };
            return Function;
        }(Kind));
        Function.__name__ = "Function";
        Kinds.Function = Function;
    })(exports.Kinds || (exports.Kinds = {}));
    exports.Any = new exports.Kinds.Any();
    exports.Unknown = new exports.Kinds.Unknown();
    exports.Boolean = new exports.Kinds.Boolean();
    exports.Number = new exports.Kinds.Number();
    exports.Int = new exports.Kinds.Int();
    exports.String = new exports.Kinds.String();
    exports.Null = new exports.Kinds.Null();
    var Nullable = function (base_type) { return new exports.Kinds.Nullable(base_type); };
    exports.Nullable = Nullable;
    var Opt = function (base_type) { return new exports.Kinds.Opt(base_type); };
    exports.Opt = Opt;
    var Or = function () {
        var types = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            types[_i] = arguments[_i];
        }
        return new exports.Kinds.Or(types);
    };
    exports.Or = Or;
    var Tuple = function () {
        var types = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            types[_i] = arguments[_i];
        }
        return new exports.Kinds.Tuple(types);
    };
    exports.Tuple = Tuple;
    var Struct = function (struct_type) { return new exports.Kinds.Struct(struct_type); };
    exports.Struct = Struct;
    exports.Arrayable = new exports.Kinds.Arrayable();
    var Array = function (item_type) { return new exports.Kinds.Array(item_type); };
    exports.Array = Array;
    var Dict = function (item_type) { return new exports.Kinds.Dict(item_type); };
    exports.Dict = Dict;
    var Map = function (key_type, item_type) { return new exports.Kinds.Map(key_type, item_type); };
    exports.Map = Map;
    var Enum = function () {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return new exports.Kinds.Enum(values);
    };
    exports.Enum = Enum;
    var Ref = function (obj_type) { return new exports.Kinds.Ref(obj_type); };
    exports.Ref = Ref;
    var AnyRef = function () { return new exports.Kinds.AnyRef(); };
    exports.AnyRef = AnyRef;
    var Function = function () { return new exports.Kinds.Function(); };
    exports.Function = Function;
    exports.Percent = new exports.Kinds.Percent();
    exports.Alpha = exports.Percent;
    exports.Color = new exports.Kinds.Color();
    exports.Auto = (0, exports.Enum)("auto");
    exports.FontSize = exports.String;
    exports.Font = exports.String;
    exports.Angle = exports.Number;
},
/* core/util/color.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var svg_colors_1 = require(138) /* ./svg_colors */;
    var math_1 = require(117) /* ./math */;
    var types_1 = require(125) /* ./types */;
    var round = Math.round;
    function byte(v) {
        return (0, math_1.clamp)(round(v), 0, 255);
    }
    function transparent() {
        return [0, 0, 0, 0];
    }
    exports.transparent = transparent;
    function encode_rgba(_a) {
        var _b = (0, tslib_1.__read)(_a, 4), r = _b[0], g = _b[1], b = _b[2], a = _b[3];
        return r << 24 | g << 16 | b << 8 | a;
    }
    exports.encode_rgba = encode_rgba;
    function decode_rgba(rgba) {
        var r = (rgba >> 24) & 0xff;
        var g = (rgba >> 16) & 0xff;
        var b = (rgba >> 8) & 0xff;
        var a = rgba & 0xff;
        return [r, g, b, a];
    }
    exports.decode_rgba = decode_rgba;
    function compose_alpha(color, alpha) {
        if ((color & 0xff) == 255)
            return (color & 0xffffff00) | byte(alpha * 255);
        else
            return color;
    }
    exports.compose_alpha = compose_alpha;
    function color2rgba(color, alpha) {
        var _a, _b, _c, _d, _e;
        var _f;
        var r, g, b, a;
        if (color == null)
            _a = (0, tslib_1.__read)(transparent(), 4), r = _a[0], g = _a[1], b = _a[2], a = _a[3];
        else if ((0, types_1.isInteger)(color))
            _b = (0, tslib_1.__read)(decode_rgba(color), 4), r = _b[0], g = _b[1], b = _b[2], a = _b[3];
        else if ((0, types_1.isString)(color))
            _c = (0, tslib_1.__read)((_f = css4_parse(color)) !== null && _f !== void 0 ? _f : transparent(), 4), r = _c[0], g = _c[1], b = _c[2], a = _c[3];
        else {
            _d = (0, tslib_1.__read)(color, 4), r = _d[0], g = _d[1], b = _d[2], _e = _d[3], a = _e === void 0 ? 1.0 : _e;
            a = byte(a * 255);
        }
        if (a == 255 && alpha != null)
            a = byte(alpha * 255);
        return [r, g, b, a];
    }
    exports.color2rgba = color2rgba;
    var _hex_table = {
        0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9",
        10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f",
    };
    function hex(v) {
        return _hex_table[v >> 4] + _hex_table[v & 0xf];
    }
    function color2css(color, alpha) {
        var _a = (0, tslib_1.__read)(color2rgba(color, alpha), 4), r = _a[0], g = _a[1], b = _a[2], a = _a[3];
        return "rgba(" + r + ", " + g + ", " + b + ", " + a / 255 + ")";
    }
    exports.color2css = color2css;
    function color2hex(color, alpha) {
        var _a = (0, tslib_1.__read)(color2rgba(color, alpha), 4), r = _a[0], g = _a[1], b = _a[2], a = _a[3];
        var rgb = "#" + hex(r) + hex(g) + hex(b);
        return a == 255 ? rgb : "" + rgb + hex(a);
    }
    exports.color2hex = color2hex;
    function color2hexrgb(color) {
        var _a = (0, tslib_1.__read)(color2rgba(color), 3), r = _a[0], g = _a[1], b = _a[2];
        return "#" + hex(r) + hex(g) + hex(b);
    }
    exports.color2hexrgb = color2hexrgb;
    /*
    let _last_color = "transparent"
    let _last_alpha = 1.0
    let _last_rgba = transparent()
    
    export function _color2rgba(color: string | null, alpha: number = 1.0): RGBA {
      if (color == _last_color && alpha == _last_alpha)
        return [..._last_rgba]
    
      const [r, g, b, a] = parsed
      const rgba: RGBA = [r, g, b, a == 255 ? byte(alpha*255) : a]
      _last_color = color
      _last_alpha = alpha
      _last_rgba = rgba
      return rgba
    }
    */
    var rgb_modern = /^rgba?\(\s*([^\s,]+?)\s+([^\s,]+?)\s+([^\s,]+?)(?:\s*\/\s*([^\s,]+?))?\s*\)$/;
    var rgb_legacy = /^rgba?\(\s*([^\s,]+?)\s*,\s*([^\s,]+?)\s*,\s*([^\s,]+?)(?:\s*,\s*([^\s,]+?))?\s*\)$/;
    var css4_normalize = (function () {
        var canvas = document.createElement("canvas");
        canvas.width = 1;
        canvas.height = 1;
        var ctx = canvas.getContext("2d");
        var gradient = ctx.createLinearGradient(0, 0, 1, 1);
        return function (color) {
            ctx.fillStyle = gradient; // lgtm [js/useless-assignment-to-property]
            ctx.fillStyle = color;
            var style = ctx.fillStyle;
            return style != gradient ? style : null;
        };
    })();
    function css4_parse(color) {
        var _a;
        /**
          Parses CSS4 color strings:
      
          - transparent
          - named color
          - #RRGGBB[AA]
          - #RGB[A]
          - rgb[a](R G B[ / A])
          - rgb[a](R, G, B[, A])
          - other CSS4 syntax (browser dependent)
      
        */
        color = color.trim().toLowerCase();
        if (!color)
            return null;
        else if (color == "transparent")
            return transparent();
        else if ((0, svg_colors_1.is_named_color)(color)) {
            return decode_rgba(svg_colors_1.named_colors[color]);
        }
        else if (color[0] == "#") {
            var v = Number("0x" + color.substr(1));
            if (isNaN(v))
                return null;
            switch (color.length - 1) {
                case 3: {
                    var r = (v >> 8) & 0xf;
                    var g = (v >> 4) & 0xf;
                    var b = (v >> 0) & 0xf;
                    var rr = (r << 4) | r;
                    var gg = (g << 4) | g;
                    var bb = (b << 4) | b;
                    return [rr, gg, bb, 255];
                }
                case 4: {
                    var r = (v >> 12) & 0xf;
                    var g = (v >> 8) & 0xf;
                    var b = (v >> 4) & 0xf;
                    var a = (v >> 0) & 0xf;
                    var rr = (r << 4) | r;
                    var gg = (g << 4) | g;
                    var bb = (b << 4) | b;
                    var aa = (a << 4) | a;
                    return [rr, gg, bb, aa];
                }
                case 6: {
                    var rr = (v >> 16) & 0xff;
                    var gg = (v >> 8) & 0xff;
                    var bb = (v >> 0) & 0xff;
                    return [rr, gg, bb, 255];
                }
                case 8: {
                    var rr = (v >> 24) & 0xff;
                    var gg = (v >> 16) & 0xff;
                    var bb = (v >> 8) & 0xff;
                    var aa = (v >> 0) & 0xff;
                    return [rr, gg, bb, aa];
                }
            }
        }
        else if (color.startsWith("rgb")) {
            var result = (_a = color.match(rgb_modern)) !== null && _a !== void 0 ? _a : color.match(rgb_legacy);
            if (result != null) {
                var _b = (0, tslib_1.__read)(result, 5), r = _b[1], g = _b[2], b = _b[3], _c = _b[4], a = _c === void 0 ? "1" : _c; // XXX: use groups when IE is dropped
                var rp = r.endsWith("%");
                var gp = g.endsWith("%");
                var bp = b.endsWith("%");
                var ap = a.endsWith("%");
                if (!(rp && gp && bp || (!rp && !gp && !bp)))
                    return null;
                if (rp)
                    r = r.slice(0, -1);
                if (gp)
                    g = g.slice(0, -1);
                if (bp)
                    b = b.slice(0, -1);
                if (ap)
                    a = a.slice(0, -1);
                var R = Number(r);
                var G = Number(g);
                var B = Number(b);
                var A = Number(a);
                if (isNaN(R + G + B + A))
                    return null;
                if (rp)
                    R = 255 * (R / 100);
                if (gp)
                    G = 255 * (G / 100);
                if (bp)
                    B = 255 * (B / 100);
                A = 255 * (ap ? A / 100 : A);
                R = byte(R);
                G = byte(G);
                B = byte(B);
                A = byte(A);
                return [R, G, B, A];
            }
        }
        else {
            var style = css4_normalize(color);
            if (style != null)
                return css4_parse(style);
        }
        return null;
    }
    exports.css4_parse = css4_parse;
    function is_Color(value) {
        if ((0, types_1.isInteger)(value))
            return true;
        if ((0, types_1.isString)(value) && css4_parse(value) != null)
            return true;
        if ((0, types_1.isArray)(value) && (value.length == 3 || value.length == 4))
            return true;
        return false;
    }
    exports.is_Color = is_Color;
    function is_dark(_a) {
        var _b = (0, tslib_1.__read)(_a, 3), r = _b[0], g = _b[1], b = _b[2];
        var l = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        return l >= 0.6;
    }
    exports.is_dark = is_dark;
},
/* core/util/svg_colors.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var _named_colors = {
        aliceblue: 0xf0f8ffff,
        antiquewhite: 0xfaebd7ff,
        aqua: 0x00ffffff,
        aquamarine: 0x7fffd4ff,
        azure: 0xf0ffffff,
        beige: 0xf5f5dcff,
        bisque: 0xffe4c4ff,
        black: 0x000000ff,
        blanchedalmond: 0xffebcdff,
        blue: 0x0000ffff,
        blueviolet: 0x8a2be2ff,
        brown: 0xa52a2aff,
        burlywood: 0xdeb887ff,
        cadetblue: 0x5f9ea0ff,
        chartreuse: 0x7fff00ff,
        chocolate: 0xd2691eff,
        coral: 0xff7f50ff,
        cornflowerblue: 0x6495edff,
        cornsilk: 0xfff8dcff,
        crimson: 0xdc143cff,
        cyan: 0x00ffffff,
        darkblue: 0x00008bff,
        darkcyan: 0x008b8bff,
        darkgoldenrod: 0xb8860bff,
        darkgray: 0xa9a9a9ff,
        darkgreen: 0x006400ff,
        darkgrey: 0xa9a9a9ff,
        darkkhaki: 0xbdb76bff,
        darkmagenta: 0x8b008bff,
        darkolivegreen: 0x556b2fff,
        darkorange: 0xff8c00ff,
        darkorchid: 0x9932ccff,
        darkred: 0x8b0000ff,
        darksalmon: 0xe9967aff,
        darkseagreen: 0x8fbc8fff,
        darkslateblue: 0x483d8bff,
        darkslategray: 0x2f4f4fff,
        darkslategrey: 0x2f4f4fff,
        darkturquoise: 0x00ced1ff,
        darkviolet: 0x9400d3ff,
        deeppink: 0xff1493ff,
        deepskyblue: 0x00bfffff,
        dimgray: 0x696969ff,
        dimgrey: 0x696969ff,
        dodgerblue: 0x1e90ffff,
        firebrick: 0xb22222ff,
        floralwhite: 0xfffaf0ff,
        forestgreen: 0x228b22ff,
        fuchsia: 0xff00ffff,
        gainsboro: 0xdcdcdcff,
        ghostwhite: 0xf8f8ffff,
        gold: 0xffd700ff,
        goldenrod: 0xdaa520ff,
        gray: 0x808080ff,
        green: 0x008000ff,
        greenyellow: 0xadff2fff,
        grey: 0x808080ff,
        honeydew: 0xf0fff0ff,
        hotpink: 0xff69b4ff,
        indianred: 0xcd5c5cff,
        indigo: 0x4b0082ff,
        ivory: 0xfffff0ff,
        khaki: 0xf0e68cff,
        lavender: 0xe6e6faff,
        lavenderblush: 0xfff0f5ff,
        lawngreen: 0x7cfc00ff,
        lemonchiffon: 0xfffacdff,
        lightblue: 0xadd8e6ff,
        lightcoral: 0xf08080ff,
        lightcyan: 0xe0ffffff,
        lightgoldenrodyellow: 0xfafad2ff,
        lightgray: 0xd3d3d3ff,
        lightgreen: 0x90ee90ff,
        lightgrey: 0xd3d3d3ff,
        lightpink: 0xffb6c1ff,
        lightsalmon: 0xffa07aff,
        lightseagreen: 0x20b2aaff,
        lightskyblue: 0x87cefaff,
        lightslategray: 0x778899ff,
        lightslategrey: 0x778899ff,
        lightsteelblue: 0xb0c4deff,
        lightyellow: 0xffffe0ff,
        lime: 0x00ff00ff,
        limegreen: 0x32cd32ff,
        linen: 0xfaf0e6ff,
        magenta: 0xff00ffff,
        maroon: 0x800000ff,
        mediumaquamarine: 0x66cdaaff,
        mediumblue: 0x0000cdff,
        mediumorchid: 0xba55d3ff,
        mediumpurple: 0x9370dbff,
        mediumseagreen: 0x3cb371ff,
        mediumslateblue: 0x7b68eeff,
        mediumspringgreen: 0x00fa9aff,
        mediumturquoise: 0x48d1ccff,
        mediumvioletred: 0xc71585ff,
        midnightblue: 0x191970ff,
        mintcream: 0xf5fffaff,
        mistyrose: 0xffe4e1ff,
        moccasin: 0xffe4b5ff,
        navajowhite: 0xffdeadff,
        navy: 0x000080ff,
        oldlace: 0xfdf5e6ff,
        olive: 0x808000ff,
        olivedrab: 0x6b8e23ff,
        orange: 0xffa500ff,
        orangered: 0xff4500ff,
        orchid: 0xda70d6ff,
        palegoldenrod: 0xeee8aaff,
        palegreen: 0x98fb98ff,
        paleturquoise: 0xafeeeeff,
        palevioletred: 0xdb7093ff,
        papayawhip: 0xffefd5ff,
        peachpuff: 0xffdab9ff,
        peru: 0xcd853fff,
        pink: 0xffc0cbff,
        plum: 0xdda0ddff,
        powderblue: 0xb0e0e6ff,
        purple: 0x800080ff,
        rebeccapurple: 0x663399ff,
        red: 0xff0000ff,
        rosybrown: 0xbc8f8fff,
        royalblue: 0x4169e1ff,
        saddlebrown: 0x8b4513ff,
        salmon: 0xfa8072ff,
        sandybrown: 0xf4a460ff,
        seagreen: 0x2e8b57ff,
        seashell: 0xfff5eeff,
        sienna: 0xa0522dff,
        silver: 0xc0c0c0ff,
        skyblue: 0x87ceebff,
        slateblue: 0x6a5acdff,
        slategray: 0x708090ff,
        slategrey: 0x708090ff,
        snow: 0xfffafaff,
        springgreen: 0x00ff7fff,
        steelblue: 0x4682b4ff,
        tan: 0xd2b48cff,
        teal: 0x008080ff,
        thistle: 0xd8bfd8ff,
        tomato: 0xff6347ff,
        turquoise: 0x40e0d0ff,
        violet: 0xee82eeff,
        wheat: 0xf5deb3ff,
        white: 0xffffffff,
        whitesmoke: 0xf5f5f5ff,
        yellow: 0xffff00ff,
        yellowgreen: 0x9acd32ff,
    };
    exports.named_colors = _named_colors;
    function is_named_color(color) {
        return color in exports.named_colors;
    }
    exports.is_named_color = is_named_color;
},
/* core/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    exports.GeneratorFunction = Object.getPrototypeOf(function () {
        return (0, tslib_1.__generator)(this, function (_a) {
            return [2 /*return*/];
        });
    }).constructor;
    exports.ColorArray = Uint32Array;
    exports.RGBAArray = Uint8ClampedArray;
    function infer_type(a0, a1) {
        if (a0 instanceof Float64Array || a0 instanceof Array)
            return Float64Array;
        if (a1 instanceof Float64Array || a1 instanceof Array)
            return Float64Array;
        return Float32Array;
    }
    exports.infer_type = infer_type;
    exports.ScreenArray = Float32Array;
    function to_screen(array) {
        if (!(array instanceof Float32Array))
            return Float32Array.from(array);
        else
            return array;
    }
    exports.to_screen = to_screen;
    var bitset_1 = require(140) /* ./util/bitset */;
    __esExport("Indices", bitset_1.BitSet);
},
/* core/util/bitset.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var eq_1 = require(141) /* ./eq */;
    var assert_1 = require(127) /* ./assert */;
    var BitSet = /** @class */ (function () {
        function BitSet(size, init) {
            if (init === void 0) {
                init = 0;
            }
            this.size = size;
            this[_a] = "BitSet";
            this._count = null;
            this._nwords = Math.ceil(size / 32);
            if (init == 0 || init == 1) {
                this._array = new Uint32Array(this._nwords);
                if (init == 1) {
                    this._array.fill(0xffffffff);
                }
            }
            else {
                (0, assert_1.assert)(init.length == this._nwords, "Initializer size mismatch");
                this._array = init;
            }
        }
        BitSet.prototype.clone = function () {
            return new BitSet(this.size, new Uint32Array(this._array));
        };
        BitSet.prototype[(_a = Symbol.toStringTag, eq_1.equals)] = function (that, cmp) {
            if (!cmp.eq(this.size, that.size))
                return false;
            var _nwords = this._nwords;
            var trailing = this.size % _nwords;
            var n = trailing == 0 ? _nwords : _nwords - 1;
            for (var i = 0; i < n; i++) {
                if (this._array[i] != that._array[i])
                    return false;
            }
            if (trailing == 0)
                return true;
            else {
                var msb = 1 << (trailing - 1);
                var mask = (msb - 1) ^ msb;
                return (this._array[n] & mask) == (that._array[n] & mask);
            }
        };
        BitSet.all_set = function (size) {
            return new BitSet(size, 1);
        };
        BitSet.all_unset = function (size) {
            return new BitSet(size, 0);
        };
        BitSet.from_indices = function (size, indices) {
            var e_1, _b;
            var bits = new BitSet(size);
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    bits.set(i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return bits;
        };
        BitSet.from_booleans = function (size, booleans) {
            var bits = new BitSet(size);
            var n = Math.min(size, booleans.length);
            for (var i = 0; i < n; i++) {
                if (booleans[i])
                    bits.set(i);
            }
            return bits;
        };
        BitSet.prototype._check_bounds = function (k) {
            (0, assert_1.assert)(0 <= k && k < this.size, "Out of bounds: 0 <= " + k + " < " + this.size);
        };
        BitSet.prototype.get = function (k) {
            this._check_bounds(k);
            var i = k >>> 5; // Math.floor(k/32)
            var j = k & 0x1f; // k % 32
            return !!((this._array[i] >> j) & 0x1);
        };
        BitSet.prototype.set = function (k, v) {
            if (v === void 0) {
                v = true;
            }
            this._check_bounds(k);
            this._count = null;
            var i = k >>> 5; // Math.floor(k/32)
            var j = k & 0x1f; // k % 32
            if (v)
                this._array[i] |= 0x1 << j;
            else
                this._array[i] &= ~(0x1 << j);
        };
        BitSet.prototype.unset = function (k) {
            this.set(k, false);
        };
        BitSet.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_b) {
                switch (_b.label) {
                    case 0: return [5 /*yield**/, (0, tslib_1.__values)(this.ones())];
                    case 1:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        };
        Object.defineProperty(BitSet.prototype, "count", {
            get: function () {
                var count = this._count;
                if (count == null)
                    this._count = count = this._get_count();
                return count;
            },
            enumerable: false,
            configurable: true
        });
        BitSet.prototype._get_count = function () {
            var _b = this, _array = _b._array, _nwords = _b._nwords, size = _b.size;
            var c = 0;
            for (var k = 0, i = 0; i < _nwords; i++) {
                var word = _array[i];
                if (word == 0) {
                    k += 32;
                }
                else {
                    for (var j = 0; j < 32 && k < size; j++, k++) {
                        if ((word >>> j) & 0x1)
                            c += 1;
                    }
                }
            }
            return c;
        };
        BitSet.prototype.ones = function () {
            var _b, _array, _nwords, size, k, i, word, j;
            return (0, tslib_1.__generator)(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _b = this, _array = _b._array, _nwords = _b._nwords, size = _b.size;
                        k = 0, i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(i < _nwords))
                            return [3 /*break*/, 6];
                        word = _array[i];
                        if (word == 0) {
                            k += 32;
                            return [3 /*break*/, 5];
                        }
                        j = 0;
                        _c.label = 2;
                    case 2:
                        if (!(j < 32 && k < size))
                            return [3 /*break*/, 5];
                        if (!((word >>> j) & 0x1))
                            return [3 /*break*/, 4];
                        return [4 /*yield*/, k];
                    case 3:
                        _c.sent();
                        _c.label = 4;
                    case 4:
                        j++, k++;
                        return [3 /*break*/, 2];
                    case 5:
                        i++;
                        return [3 /*break*/, 1];
                    case 6: return [2 /*return*/];
                }
            });
        };
        BitSet.prototype.zeros = function () {
            var _b, _array, _nwords, size, k, i, word, j;
            return (0, tslib_1.__generator)(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _b = this, _array = _b._array, _nwords = _b._nwords, size = _b.size;
                        k = 0, i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(i < _nwords))
                            return [3 /*break*/, 6];
                        word = _array[i];
                        if (word == 0xffffffff) {
                            k += 32;
                            return [3 /*break*/, 5];
                        }
                        j = 0;
                        _c.label = 2;
                    case 2:
                        if (!(j < 32 && k < size))
                            return [3 /*break*/, 5];
                        if (!!((word >>> j) & 0x1))
                            return [3 /*break*/, 4];
                        return [4 /*yield*/, k];
                    case 3:
                        _c.sent();
                        _c.label = 4;
                    case 4:
                        j++, k++;
                        return [3 /*break*/, 2];
                    case 5:
                        i++;
                        return [3 /*break*/, 1];
                    case 6: return [2 /*return*/];
                }
            });
        };
        BitSet.prototype._check_size = function (other) {
            (0, assert_1.assert)(this.size == other.size, "Size mismatch");
        };
        BitSet.prototype.add = function (other) {
            this._check_size(other);
            for (var i = 0; i < this._nwords; i++) {
                this._array[i] |= other._array[i];
            }
        };
        BitSet.prototype.intersect = function (other) {
            this._check_size(other);
            for (var i = 0; i < this._nwords; i++) {
                this._array[i] &= other._array[i];
            }
        };
        BitSet.prototype.subtract = function (other) {
            this._check_size(other);
            for (var i = 0; i < this._nwords; i++) {
                var a = this._array[i];
                var b = other._array[i];
                this._array[i] = (a ^ b) & a;
            }
        };
        BitSet.prototype.union = function (other) {
            this._check_size(other);
            var result = this.clone();
            for (var i = 0; i < this._nwords; i++) {
                result._array[i] |= other._array[i];
            }
            return result;
        };
        BitSet.prototype.intersection = function (other) {
            this._check_size(other);
            var result = this.clone();
            for (var i = 0; i < this._nwords; i++) {
                result._array[i] &= other._array[i];
            }
            return result;
        };
        BitSet.prototype.difference = function (other) {
            this._check_size(other);
            var result = this.clone();
            for (var i = 0; i < this._nwords; i++) {
                var a = this._array[i];
                var b = other._array[i];
                result._array[i] = (a ^ b) & a;
            }
            return result;
        };
        BitSet.prototype.select = function (array) {
            var e_2, _b;
            (0, assert_1.assert)(this.size <= array.length, "Size mismatch");
            var n = this.count;
            var result = new array.constructor(n);
            var i = 0;
            try {
                for (var _c = (0, tslib_1.__values)(this), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var j = _d.value;
                    result[i++] = array[j];
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return result;
        };
        return BitSet;
    }());
    exports.BitSet = BitSet;
    BitSet.__name__ = "BitSet";
},
/* core/util/eq.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    // Based on Underscore.js 1.8.3 (http://underscorejs.org)
    var types_1 = require(125) /* ./types */;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    exports.equals = Symbol("equals");
    function is_Equatable(obj) {
        return (0, types_1.isObject)(obj) && obj[exports.equals] !== undefined;
    }
    exports.wildcard = Symbol("wildcard");
    var toString = Object.prototype.toString;
    var Comparator = /** @class */ (function () {
        function Comparator() {
            this.a_stack = [];
            this.b_stack = [];
        }
        Comparator.prototype.eq = function (a, b) {
            var _this = this;
            if (Object.is(a, b))
                return true;
            if (a === exports.wildcard || b === exports.wildcard)
                return true;
            if (a == null || b == null)
                return a === b;
            var class_name = toString.call(a);
            if (class_name != toString.call(b))
                return false;
            switch (class_name) {
                case "[object Number]":
                    return this.numbers(a, b);
                case "[object RegExp]":
                case "[object String]":
                    return "" + a == "" + b;
                case "[object Date]":
                case "[object Boolean]":
                    return +a === +b;
            }
            // Assume equality for cyclic structures. The algorithm for detecting cyclic
            // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
            // Initializing stack of traversed objects.
            // It's done here since we only need them for objects and arrays comparison.
            var _a = this, a_stack = _a.a_stack, b_stack = _a.b_stack;
            var length = a_stack.length;
            while (length--) {
                // Linear search. Performance is inversely proportional to the number of
                // unique nested structures.
                if (a_stack[length] === a)
                    return b_stack[length] === b;
            }
            a_stack.push(a);
            b_stack.push(b);
            var result = (function () {
                if (is_Equatable(a) && is_Equatable(b)) {
                    return a[exports.equals](b, _this);
                }
                switch (class_name) {
                    case "[object Array]":
                    case "[object Uint8Array]":
                    case "[object Int8Array]":
                    case "[object Uint16Array]":
                    case "[object Int16Array]":
                    case "[object Uint32Array]":
                    case "[object Int32Array]":
                    case "[object Float32Array]":
                    case "[object Float64Array]": {
                        return _this.arrays(a, b);
                    }
                    case "[object Map]":
                        return _this.maps(a, b);
                    case "[object Set]":
                        return _this.sets(a, b);
                    case "[object Object]": {
                        if (a.constructor == b.constructor && (a.constructor == null || a.constructor === Object)) {
                            return _this.objects(a, b);
                        }
                    }
                    case "[object Function]": {
                        if (a.constructor == b.constructor && a.constructor === Function) {
                            return _this.eq("" + a, "" + b);
                        }
                    }
                }
                if (a instanceof Node) {
                    return _this.nodes(a, b);
                }
                throw Error("can't compare objects of type " + class_name);
            })();
            a_stack.pop();
            b_stack.pop();
            return result;
        };
        Comparator.prototype.numbers = function (a, b) {
            return Object.is(a, b);
        };
        Comparator.prototype.arrays = function (a, b) {
            var length = a.length;
            if (length != b.length)
                return false;
            for (var i = 0; i < length; i++) {
                if (!this.eq(a[i], b[i]))
                    return false;
            }
            return true;
        };
        Comparator.prototype.iterables = function (a, b) {
            var ai = a[Symbol.iterator]();
            var bi = b[Symbol.iterator]();
            while (true) {
                var an = ai.next();
                var bn = bi.next();
                if (an.done && bn.done)
                    return true;
                if (an.done || bn.done)
                    return false;
                if (!this.eq(an.value, bn.value))
                    return false;
            }
        };
        Comparator.prototype.maps = function (a, b) {
            var e_1, _a;
            if (a.size != b.size)
                return false;
            try {
                for (var a_1 = (0, tslib_1.__values)(a), a_1_1 = a_1.next(); !a_1_1.done; a_1_1 = a_1.next()) {
                    var _b = (0, tslib_1.__read)(a_1_1.value, 2), key = _b[0], val = _b[1];
                    if (!b.has(key) || !this.eq(val, b.get(key)))
                        return false;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (a_1_1 && !a_1_1.done && (_a = a_1.return))
                        _a.call(a_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return true;
        };
        Comparator.prototype.sets = function (a, b) {
            var e_2, _a;
            if (a.size != b.size)
                return false;
            try {
                for (var a_2 = (0, tslib_1.__values)(a), a_2_1 = a_2.next(); !a_2_1.done; a_2_1 = a_2.next()) {
                    var key = a_2_1.value;
                    if (!b.has(key))
                        return false;
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (a_2_1 && !a_2_1.done && (_a = a_2.return))
                        _a.call(a_2);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return true;
        };
        Comparator.prototype.objects = function (a, b) {
            var e_3, _a;
            var keys = Object.keys(a);
            if (keys.length != Object.keys(b).length)
                return false;
            try {
                for (var keys_1 = (0, tslib_1.__values)(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
                    var key = keys_1_1.value;
                    if (!hasOwnProperty.call(b, key) || !this.eq(a[key], b[key]))
                        return false;
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return))
                        _a.call(keys_1);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return true;
        };
        Comparator.prototype.nodes = function (a, b) {
            if (a.nodeType != b.nodeType)
                return false;
            if (a.textContent != b.textContent)
                return false;
            if (!this.iterables(a.childNodes, b.childNodes))
                return false;
            return true;
        };
        return Comparator;
    }());
    exports.Comparator = Comparator;
    Comparator.__name__ = "Comparator";
    var abs = Math.abs;
    var SimilarComparator = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SimilarComparator, _super);
        function SimilarComparator(tolerance) {
            if (tolerance === void 0) {
                tolerance = 1e-4;
            }
            var _this = _super.call(this) || this;
            _this.tolerance = tolerance;
            return _this;
        }
        SimilarComparator.prototype.numbers = function (a, b) {
            return _super.prototype.numbers.call(this, a, b) || abs(a - b) < this.tolerance;
        };
        return SimilarComparator;
    }(Comparator));
    exports.SimilarComparator = SimilarComparator;
    SimilarComparator.__name__ = "SimilarComparator";
    function is_equal(a, b) {
        var comparator = new Comparator();
        return comparator.eq(a, b);
    }
    exports.is_equal = is_equal;
    function is_similar(a, b, tolerance) {
        var comparator = new SimilarComparator(tolerance);
        return comparator.eq(a, b);
    }
    exports.is_similar = is_similar;
    /** @deprecated */
    exports.isEqual = is_equal;
},
/* core/util/platform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    exports.is_windows = (function () {
        return navigator.appVersion.includes("Windows");
    })();
    exports.is_ie = (function () {
        var ua = navigator.userAgent;
        return ua.includes("MSIE") || ua.includes("Trident") || ua.includes("Edge");
    })();
    exports.is_mobile = (function () {
        return typeof window !== "undefined" && ("ontouchstart" in window || navigator.maxTouchPoints > 0);
    })();
    exports.is_little_endian = (function () {
        var buf = new ArrayBuffer(4);
        var buf8 = new Uint8Array(buf);
        var buf32 = new Uint32Array(buf);
        buf32[1] = 0x0a0b0c0d;
        var little_endian = true;
        if (buf8[4] == 0x0a && buf8[5] == 0x0b && buf8[6] == 0x0c && buf8[7] == 0x0d) {
            little_endian = false;
        }
        return little_endian;
    })();
    exports.BYTE_ORDER = exports.is_little_endian ? "little" : "big";
    function to_big_endian(values) {
        var e_1, _a;
        if (exports.is_little_endian) {
            var result = new Uint32Array(values.length);
            var view = new DataView(result.buffer);
            var j = 0;
            try {
                for (var values_1 = (0, tslib_1.__values)(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
                    var color = values_1_1.value;
                    view.setUint32(j, color);
                    j += 4;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (values_1_1 && !values_1_1.done && (_a = values_1.return))
                        _a.call(values_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return result;
        }
        else
            return values;
    }
    exports.to_big_endian = to_big_endian;
},
/* core/settings.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var Settings = /** @class */ (function () {
        function Settings() {
            this._dev = false;
            this._wireframe = false;
        }
        Object.defineProperty(Settings.prototype, "dev", {
            get: function () {
                return this._dev;
            },
            set: function (dev) {
                this._dev = dev;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Settings.prototype, "wireframe", {
            get: function () {
                return this._wireframe;
            },
            set: function (wireframe) {
                this._wireframe = wireframe;
            },
            enumerable: false,
            configurable: true
        });
        return Settings;
    }());
    exports.Settings = Settings;
    Settings.__name__ = "Settings";
    exports.settings = new Settings();
},
/* core/util/ndarray.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b, _c, _d, _e, _f, _g, _h;
    var types_1 = require(125) /* ./types */;
    var assert_1 = require(127) /* ./assert */;
    var eq_1 = require(141) /* ./eq */;
    var serializer_1 = require(145) /* ../serializer */;
    var serialization_1 = require(146) /* ./serialization */;
    var __ndarray__ = Symbol("__ndarray__");
    var Uint8NDArray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Uint8NDArray, _super);
        function Uint8NDArray(seq, shape) {
            var _this = new _super(seq);
            _this[_a] = true;
            _this.dtype = "uint8";
            _this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [_this.length]);
            _this.dimension = _this.shape.length;
            // TODO: remove this when IE/legacy is dropped
            if (_this[eq_1.equals] == null) {
                _this[eq_1.equals] = function (that, cmp) {
                    return Uint8NDArray.prototype[eq_1.equals].call(_this, that, cmp);
                };
            }
            if (_this[serializer_1.serialize] == null) {
                _this[serializer_1.serialize] = function (serializer) {
                    return Uint8NDArray.prototype[serializer_1.serialize].call(_this, serializer);
                };
            }
            return _this;
        }
        Uint8NDArray.prototype[(_a = __ndarray__, eq_1.equals)] = function (that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        };
        Uint8NDArray.prototype[serializer_1.serialize] = function (_serializer) {
            return (0, serialization_1.encode_NDArray)(this);
        };
        return Uint8NDArray;
    }(Uint8Array));
    exports.Uint8NDArray = Uint8NDArray;
    Uint8NDArray.__name__ = "Uint8NDArray";
    var Int8NDArray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Int8NDArray, _super);
        function Int8NDArray(seq, shape) {
            var _this = new _super(seq);
            _this[_b] = true;
            _this.dtype = "int8";
            _this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [_this.length]);
            _this.dimension = _this.shape.length;
            // TODO: remove this when IE/legacy is dropped
            if (_this[eq_1.equals] == null) {
                _this[eq_1.equals] = function (that, cmp) {
                    return Int8NDArray.prototype[eq_1.equals].call(_this, that, cmp);
                };
            }
            if (_this[serializer_1.serialize] == null) {
                _this[serializer_1.serialize] = function (serializer) {
                    return Int8NDArray.prototype[serializer_1.serialize].call(_this, serializer);
                };
            }
            return _this;
        }
        Int8NDArray.prototype[(_b = __ndarray__, eq_1.equals)] = function (that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        };
        Int8NDArray.prototype[serializer_1.serialize] = function (_serializer) {
            return (0, serialization_1.encode_NDArray)(this);
        };
        return Int8NDArray;
    }(Int8Array));
    exports.Int8NDArray = Int8NDArray;
    Int8NDArray.__name__ = "Int8NDArray";
    var Uint16NDArray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Uint16NDArray, _super);
        function Uint16NDArray(seq, shape) {
            var _this = new _super(seq);
            _this[_c] = true;
            _this.dtype = "uint16";
            _this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [_this.length]);
            _this.dimension = _this.shape.length;
            // TODO: remove this when IE/legacy is dropped
            if (_this[eq_1.equals] == null) {
                _this[eq_1.equals] = function (that, cmp) {
                    return Uint16NDArray.prototype[eq_1.equals].call(_this, that, cmp);
                };
            }
            if (_this[serializer_1.serialize] == null) {
                _this[serializer_1.serialize] = function (serializer) {
                    return Uint16NDArray.prototype[serializer_1.serialize].call(_this, serializer);
                };
            }
            return _this;
        }
        Uint16NDArray.prototype[(_c = __ndarray__, eq_1.equals)] = function (that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        };
        Uint16NDArray.prototype[serializer_1.serialize] = function (_serializer) {
            return (0, serialization_1.encode_NDArray)(this);
        };
        return Uint16NDArray;
    }(Uint16Array));
    exports.Uint16NDArray = Uint16NDArray;
    Uint16NDArray.__name__ = "Uint16NDArray";
    var Int16NDArray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Int16NDArray, _super);
        function Int16NDArray(seq, shape) {
            var _this = new _super(seq);
            _this[_d] = true;
            _this.dtype = "int16";
            _this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [_this.length]);
            _this.dimension = _this.shape.length;
            // TODO: remove this when IE/legacy is dropped
            if (_this[eq_1.equals] == null) {
                _this[eq_1.equals] = function (that, cmp) {
                    return Int16NDArray.prototype[eq_1.equals].call(_this, that, cmp);
                };
            }
            if (_this[serializer_1.serialize] == null) {
                _this[serializer_1.serialize] = function (serializer) {
                    return Int16NDArray.prototype[serializer_1.serialize].call(_this, serializer);
                };
            }
            return _this;
        }
        Int16NDArray.prototype[(_d = __ndarray__, eq_1.equals)] = function (that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        };
        Int16NDArray.prototype[serializer_1.serialize] = function (_serializer) {
            return (0, serialization_1.encode_NDArray)(this);
        };
        return Int16NDArray;
    }(Int16Array));
    exports.Int16NDArray = Int16NDArray;
    Int16NDArray.__name__ = "Int16NDArray";
    var Uint32NDArray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Uint32NDArray, _super);
        function Uint32NDArray(seq, shape) {
            var _this = new _super(seq);
            _this[_e] = true;
            _this.dtype = "uint32";
            _this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [_this.length]);
            _this.dimension = _this.shape.length;
            // TODO: remove this when IE/legacy is dropped
            if (_this[eq_1.equals] == null) {
                _this[eq_1.equals] = function (that, cmp) {
                    return Uint32NDArray.prototype[eq_1.equals].call(_this, that, cmp);
                };
            }
            if (_this[serializer_1.serialize] == null) {
                _this[serializer_1.serialize] = function (serializer) {
                    return Uint32NDArray.prototype[serializer_1.serialize].call(_this, serializer);
                };
            }
            return _this;
        }
        Uint32NDArray.prototype[(_e = __ndarray__, eq_1.equals)] = function (that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        };
        Uint32NDArray.prototype[serializer_1.serialize] = function (_serializer) {
            return (0, serialization_1.encode_NDArray)(this);
        };
        return Uint32NDArray;
    }(Uint32Array));
    exports.Uint32NDArray = Uint32NDArray;
    Uint32NDArray.__name__ = "Uint32NDArray";
    var Int32NDArray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Int32NDArray, _super);
        function Int32NDArray(seq, shape) {
            var _this = new _super(seq);
            _this[_f] = true;
            _this.dtype = "int32";
            _this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [_this.length]);
            _this.dimension = _this.shape.length;
            // TODO: remove this when IE/legacy is dropped
            if (_this[eq_1.equals] == null) {
                _this[eq_1.equals] = function (that, cmp) {
                    return Int32NDArray.prototype[eq_1.equals].call(_this, that, cmp);
                };
            }
            if (_this[serializer_1.serialize] == null) {
                _this[serializer_1.serialize] = function (serializer) {
                    return Int32NDArray.prototype[serializer_1.serialize].call(_this, serializer);
                };
            }
            return _this;
        }
        Int32NDArray.prototype[(_f = __ndarray__, eq_1.equals)] = function (that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        };
        Int32NDArray.prototype[serializer_1.serialize] = function (_serializer) {
            return (0, serialization_1.encode_NDArray)(this);
        };
        return Int32NDArray;
    }(Int32Array));
    exports.Int32NDArray = Int32NDArray;
    Int32NDArray.__name__ = "Int32NDArray";
    var Float32NDArray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Float32NDArray, _super);
        function Float32NDArray(seq, shape) {
            var _this = new _super(seq);
            _this[_g] = true;
            _this.dtype = "float32";
            _this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [_this.length]);
            _this.dimension = _this.shape.length;
            // TODO: remove this when IE/legacy is dropped
            if (_this[eq_1.equals] == null) {
                _this[eq_1.equals] = function (that, cmp) {
                    return Float32NDArray.prototype[eq_1.equals].call(_this, that, cmp);
                };
            }
            if (_this[serializer_1.serialize] == null) {
                _this[serializer_1.serialize] = function (serializer) {
                    return Float32NDArray.prototype[serializer_1.serialize].call(_this, serializer);
                };
            }
            return _this;
        }
        Float32NDArray.prototype[(_g = __ndarray__, eq_1.equals)] = function (that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        };
        Float32NDArray.prototype[serializer_1.serialize] = function (_serializer) {
            return (0, serialization_1.encode_NDArray)(this);
        };
        return Float32NDArray;
    }(Float32Array));
    exports.Float32NDArray = Float32NDArray;
    Float32NDArray.__name__ = "Float32NDArray";
    var Float64NDArray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Float64NDArray, _super);
        function Float64NDArray(seq, shape) {
            var _this = new _super(seq);
            _this[_h] = true;
            _this.dtype = "float64";
            _this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [_this.length]);
            _this.dimension = _this.shape.length;
            // TODO: remove this when IE/legacy is dropped
            if (_this[eq_1.equals] == null) {
                _this[eq_1.equals] = function (that, cmp) {
                    return Float64NDArray.prototype[eq_1.equals].call(_this, that, cmp);
                };
            }
            if (_this[serializer_1.serialize] == null) {
                _this[serializer_1.serialize] = function (serializer) {
                    return Float64NDArray.prototype[serializer_1.serialize].call(_this, serializer);
                };
            }
            return _this;
        }
        Float64NDArray.prototype[(_h = __ndarray__, eq_1.equals)] = function (that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        };
        Float64NDArray.prototype[serializer_1.serialize] = function (_serializer) {
            return (0, serialization_1.encode_NDArray)(this);
        };
        return Float64NDArray;
    }(Float64Array));
    exports.Float64NDArray = Float64NDArray;
    Float64NDArray.__name__ = "Float64NDArray";
    function is_NDArray(v) {
        return (0, types_1.isObject)(v) && v[__ndarray__] !== undefined;
    }
    exports.is_NDArray = is_NDArray;
    function ndarray(array, options) {
        if (options === void 0) {
            options = {};
        }
        var dtype = options.dtype;
        if (dtype == null) {
            if (array instanceof ArrayBuffer || (0, types_1.isArray)(array)) {
                dtype = "float64";
            }
            else {
                dtype = (function () {
                    switch (true) {
                        case array instanceof Uint8Array: return "uint8";
                        case array instanceof Int8Array: return "int8";
                        case array instanceof Uint16Array: return "uint16";
                        case array instanceof Int16Array: return "int16";
                        case array instanceof Uint32Array: return "uint32";
                        case array instanceof Int32Array: return "int32";
                        case array instanceof Float32Array: return "float32";
                        case array instanceof Float64Array: return "float64";
                        default:
                            (0, assert_1.unreachable)();
                    }
                })();
            }
        }
        var shape = options.shape;
        switch (dtype) {
            case "uint8": return new Uint8NDArray(array, shape);
            case "int8": return new Int8NDArray(array, shape);
            case "uint16": return new Uint16NDArray(array, shape);
            case "int16": return new Int16NDArray(array, shape);
            case "uint32": return new Uint32NDArray(array, shape);
            case "int32": return new Int32NDArray(array, shape);
            case "float32": return new Float32NDArray(array, shape);
            case "float64": return new Float64NDArray(array, shape);
        }
    }
    exports.ndarray = ndarray;
},
/* core/serializer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var assert_1 = require(127) /* ./util/assert */;
    var object_1 = require(128) /* ./util/object */;
    var types_1 = require(125) /* ./util/types */;
    //| Map<SerializableType, SerializableType>
    //| Set<SerializableType>
    //| ArrayBuffer
    // TypedArray?
    exports.serialize = Symbol("serialize");
    function is_Serializable(obj) {
        return (0, types_1.isObject)(obj) && obj[exports.serialize] !== undefined;
    }
    var SerializationError = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SerializationError, _super);
        function SerializationError() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return SerializationError;
    }(Error));
    exports.SerializationError = SerializationError;
    SerializationError.__name__ = "SerializationError";
    var Serializer = /** @class */ (function () {
        function Serializer(options) {
            var _a;
            this._references = new Map();
            this._definitions = new Map();
            this._refmap = new Map();
            this.include_defaults = (_a = options === null || options === void 0 ? void 0 : options.include_defaults) !== null && _a !== void 0 ? _a : true;
        }
        Serializer.prototype.get_ref = function (obj) {
            return this._references.get(obj);
        };
        Serializer.prototype.add_ref = function (obj, ref) {
            (0, assert_1.assert)(!this._references.has(obj));
            this._references.set(obj, ref);
        };
        Serializer.prototype.add_def = function (obj, def) {
            var ref = this.get_ref(obj);
            (0, assert_1.assert)(ref != null);
            this._definitions.set(obj, def);
            this._refmap.set(ref, def);
        };
        Object.defineProperty(Serializer.prototype, "objects", {
            get: function () {
                return new Set(this._references.keys());
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Serializer.prototype, "references", {
            get: function () {
                return new Set(this._references.values());
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Serializer.prototype, "definitions", {
            get: function () {
                return new Set(this._definitions.values());
            },
            enumerable: false,
            configurable: true
        });
        Serializer.prototype.resolve_ref = function (ref) {
            return this._refmap.get(ref);
        };
        Serializer.prototype.remove_ref = function (obj) {
            return this._references.delete(obj);
        };
        Serializer.prototype.remove_def = function (obj) {
            return this._definitions.delete(obj);
        };
        Serializer.prototype.to_serializable = function (obj) {
            var e_1, _a;
            var ref = this.get_ref(obj);
            if (ref != null)
                return ref;
            else if (is_Serializable(obj))
                return obj[exports.serialize](this);
            else if ((0, types_1.isArray)(obj) || (0, types_1.isTypedArray)(obj)) {
                var n = obj.length;
                var result = new Array(n);
                for (var i = 0; i < n; i++) {
                    var value = obj[i];
                    result[i] = this.to_serializable(value);
                }
                return result;
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                var result = {};
                try {
                    for (var _b = (0, tslib_1.__values)((0, object_1.entries)(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var _d = (0, tslib_1.__read)(_c.value, 2), key = _d[0], value = _d[1];
                        result[key] = this.to_serializable(value);
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
                return result;
            }
            else if (obj === null || (0, types_1.isBoolean)(obj) || (0, types_1.isNumber)(obj) || (0, types_1.isString)(obj)) {
                return obj;
            }
            else
                throw new SerializationError(Object.prototype.toString.call(obj) + " is not serializable");
        };
        return Serializer;
    }());
    exports.Serializer = Serializer;
    Serializer.__name__ = "Serializer";
},
/* core/util/serialization.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var types_1 = require(125) /* ./types */;
    var platform_1 = require(142) /* ./platform */;
    var buffer_1 = require(147) /* ./buffer */;
    function is_NDArray_ref(v) {
        return (0, types_1.isPlainObject)(v) && ("__buffer__" in v || "__ndarray__" in v);
    }
    exports.is_NDArray_ref = is_NDArray_ref;
    function decode_NDArray(ref, buffers) {
        var shape = ref.shape, dtype = ref.dtype, order = ref.order;
        var bytes;
        if ("__buffer__" in ref) {
            var buffer = buffers.get(ref.__buffer__);
            if (buffer != null)
                bytes = buffer;
            else
                throw new Error("buffer for " + ref.__buffer__ + " not found");
        }
        else {
            bytes = (0, buffer_1.base64_to_buffer)(ref.__ndarray__);
        }
        if (order !== platform_1.BYTE_ORDER) {
            (0, buffer_1.swap)(bytes, dtype);
        }
        return { buffer: bytes, dtype: dtype, shape: shape };
    }
    exports.decode_NDArray = decode_NDArray;
    function encode_NDArray(array, buffers) {
        var data = {
            order: platform_1.BYTE_ORDER,
            dtype: array.dtype,
            shape: array.shape,
        };
        if (buffers != null) {
            var __buffer__ = "" + buffers.size;
            buffers.set(__buffer__, array.buffer);
            return (0, tslib_1.__assign)({ __buffer__: __buffer__ }, data);
        }
        else {
            var __ndarray__ = {
                toJSON: function () {
                    return (0, buffer_1.buffer_to_base64)(array.buffer);
                },
            };
            return (0, tslib_1.__assign)({ __ndarray__: __ndarray__ }, data);
        }
    }
    exports.encode_NDArray = encode_NDArray;
},
/* core/util/buffer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function buffer_to_base64(buffer) {
        var bytes = new Uint8Array(buffer);
        var chars = Array.from(bytes).map(function (b) { return String.fromCharCode(b); });
        return btoa(chars.join(""));
    }
    exports.buffer_to_base64 = buffer_to_base64;
    function base64_to_buffer(base64) {
        var binary_string = atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0, end = len; i < end; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }
    exports.base64_to_buffer = base64_to_buffer;
    // NOTE: swap{16,32,64} assume byteOffset == 0
    function swap16(buffer) {
        var x = new Uint8Array(buffer);
        for (var i = 0, end = x.length; i < end; i += 2) {
            var t = x[i];
            x[i] = x[i + 1];
            x[i + 1] = t;
        }
    }
    function swap32(buffer) {
        var x = new Uint8Array(buffer);
        for (var i = 0, end = x.length; i < end; i += 4) {
            var t = x[i];
            x[i] = x[i + 3];
            x[i + 3] = t;
            t = x[i + 1];
            x[i + 1] = x[i + 2];
            x[i + 2] = t;
        }
    }
    function swap64(buffer) {
        var x = new Uint8Array(buffer);
        for (var i = 0, end = x.length; i < end; i += 8) {
            var t = x[i];
            x[i] = x[i + 7];
            x[i + 7] = t;
            t = x[i + 1];
            x[i + 1] = x[i + 6];
            x[i + 6] = t;
            t = x[i + 2];
            x[i + 2] = x[i + 5];
            x[i + 5] = t;
            t = x[i + 3];
            x[i + 3] = x[i + 4];
            x[i + 4] = t;
        }
    }
    function swap(buffer, dtype) {
        switch (dtype) {
            case "uint16":
            case "int16":
                swap16(buffer);
                break;
            case "uint32":
            case "int32":
            case "float32":
                swap32(buffer);
                break;
            case "float64":
                swap64(buffer);
                break;
        }
    }
    exports.swap = swap;
},
/* core/uniforms.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var eq_1 = require(141) /* ./util/eq */;
    var Uniform = /** @class */ (function () {
        function Uniform() {
        }
        Uniform.prototype.is_Scalar = function () { return this.is_scalar; };
        Uniform.prototype.is_Vector = function () { return !this.is_scalar; };
        return Uniform;
    }());
    exports.Uniform = Uniform;
    Uniform.__name__ = "Uniform";
    var UniformScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UniformScalar, _super);
        function UniformScalar(value, length) {
            var _this = _super.call(this) || this;
            _this.value = value;
            _this.length = length;
            _this.is_scalar = true;
            return _this;
        }
        UniformScalar.prototype.get = function (_i) {
            return this.value;
        };
        UniformScalar.prototype[Symbol.iterator] = function () {
            var _a, length, value, i;
            return (0, tslib_1.__generator)(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this, length = _a.length, value = _a.value;
                        i = 0;
                        _b.label = 1;
                    case 1:
                        if (!(i < length))
                            return [3 /*break*/, 4];
                        return [4 /*yield*/, value];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3:
                        i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        };
        UniformScalar.prototype.select = function (indices) {
            return new UniformScalar(this.value, indices.count);
        };
        UniformScalar.prototype[eq_1.equals] = function (that, cmp) {
            return cmp.eq(this.length, that.length) && cmp.eq(this.value, that.value);
        };
        return UniformScalar;
    }(Uniform));
    exports.UniformScalar = UniformScalar;
    UniformScalar.__name__ = "UniformScalar";
    var UniformVector = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UniformVector, _super);
        function UniformVector(array) {
            var _this = _super.call(this) || this;
            _this.array = array;
            _this.is_scalar = false;
            _this.length = _this.array.length;
            return _this;
        }
        UniformVector.prototype.get = function (i) {
            return this.array[i];
        };
        UniformVector.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [5 /*yield**/, (0, tslib_1.__values)(this.array)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        };
        UniformVector.prototype.select = function (indices) {
            var array = indices.select(this.array);
            return new this.constructor(array);
        };
        UniformVector.prototype[eq_1.equals] = function (that, cmp) {
            return cmp.eq(this.length, that.length) && cmp.eq(this.array, that.array);
        };
        return UniformVector;
    }(Uniform));
    exports.UniformVector = UniformVector;
    UniformVector.__name__ = "UniformVector";
    var ColorUniformVector = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColorUniformVector, _super);
        function ColorUniformVector(array) {
            var _this = _super.call(this, array) || this;
            _this.array = array;
            _this._view = new DataView(array.buffer);
            return _this;
        }
        ColorUniformVector.prototype.get = function (i) {
            return this._view.getUint32(4 * i);
        };
        ColorUniformVector.prototype[Symbol.iterator] = function () {
            var n, i;
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        n = this.length;
                        i = 0;
                        _a.label = 1;
                    case 1:
                        if (!(i < n))
                            return [3 /*break*/, 4];
                        return [4 /*yield*/, this.get(i)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        };
        return ColorUniformVector;
    }(UniformVector));
    exports.ColorUniformVector = ColorUniformVector;
    ColorUniformVector.__name__ = "ColorUniformVector";
},
/* core/util/string.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var settings_1 = require(143) /* ../settings */;
    function startsWith(str, searchString, position) {
        if (position === void 0) {
            position = 0;
        }
        return str.substr(position, searchString.length) == searchString;
    }
    exports.startsWith = startsWith;
    function uuid4() {
        // from ipython project
        // http://www.ietf.org/rfc/rfc4122.txt
        var s = new Array(32);
        var hexDigits = "0123456789ABCDEF";
        for (var i = 0; i < 32; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[16] = hexDigits.substr((s[16].charCodeAt(0) & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        return s.join("");
    }
    exports.uuid4 = uuid4;
    var counter = 1000;
    function uniqueId(prefix) {
        var id = settings_1.settings.dev ? "j" + counter++ : uuid4();
        if (prefix != null)
            return prefix + "-" + id;
        else
            return id;
    }
    exports.uniqueId = uniqueId;
    function escape(s) {
        return s.replace(/(?:[&<>"'`])/g, function (ch) {
            switch (ch) {
                case "&": return "&amp;";
                case "<": return "&lt;";
                case ">": return "&gt;";
                case '"': return "&quot;";
                case "'": return "&#x27;";
                case "`": return "&#x60;";
                default: return ch;
            }
        });
    }
    exports.escape = escape;
    function unescape(s) {
        return s.replace(/&(amp|lt|gt|quot|#x27|#x60);/g, function (_, entity) {
            switch (entity) {
                case "amp": return "&";
                case "lt": return "<";
                case "gt": return ">";
                case "quot": return '"';
                case "#x27": return "'";
                case "#x60": return "`";
                default: return entity;
            }
        });
    }
    exports.unescape = unescape;
    function use_strict(code) {
        return "'use strict';\n" + code;
    }
    exports.use_strict = use_strict;
    function to_fixed(val, precision) {
        return val.toFixed(precision).replace(/(\.[0-9]*?)0+$/, "$1").replace(/\.$/, "");
    }
    exports.to_fixed = to_fixed;
},
/* document/events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var serializer_1 = require(145) /* ../core/serializer */;
    var DocumentEvent = /** @class */ (function () {
        function DocumentEvent(document) {
            this.document = document;
        }
        return DocumentEvent;
    }());
    exports.DocumentEvent = DocumentEvent;
    DocumentEvent.__name__ = "DocumentEvent";
    var DocumentEventBatch = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DocumentEventBatch, _super);
        function DocumentEventBatch(document, events, setter_id) {
            var _this = _super.call(this, document) || this;
            _this.events = events;
            _this.setter_id = setter_id;
            return _this;
        }
        return DocumentEventBatch;
    }(DocumentEvent));
    exports.DocumentEventBatch = DocumentEventBatch;
    DocumentEventBatch.__name__ = "DocumentEventBatch";
    var DocumentChangedEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DocumentChangedEvent, _super);
        function DocumentChangedEvent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return DocumentChangedEvent;
    }(DocumentEvent));
    exports.DocumentChangedEvent = DocumentChangedEvent;
    DocumentChangedEvent.__name__ = "DocumentChangedEvent";
    var MessageSentEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MessageSentEvent, _super);
        function MessageSentEvent(document, msg_type, msg_data) {
            var _this = _super.call(this, document) || this;
            _this.msg_type = msg_type;
            _this.msg_data = msg_data;
            return _this;
        }
        MessageSentEvent.prototype[serializer_1.serialize] = function (serializer) {
            var value = this.msg_data;
            var value_serialized = serializer.to_serializable(value);
            return {
                kind: "MessageSent",
                msg_type: this.msg_type,
                msg_data: value_serialized,
            };
        };
        return MessageSentEvent;
    }(DocumentChangedEvent));
    exports.MessageSentEvent = MessageSentEvent;
    MessageSentEvent.__name__ = "MessageSentEvent";
    var ModelChangedEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ModelChangedEvent, _super);
        function ModelChangedEvent(document, model, attr, old, new_, setter_id, hint) {
            var _this = _super.call(this, document) || this;
            _this.model = model;
            _this.attr = attr;
            _this.old = old;
            _this.new_ = new_;
            _this.setter_id = setter_id;
            _this.hint = hint;
            return _this;
        }
        ModelChangedEvent.prototype[serializer_1.serialize] = function (serializer) {
            if (this.hint != null)
                return serializer.to_serializable(this.hint);
            var value = this.new_;
            var value_serialized = serializer.to_serializable(value);
            if (this.model != value) {
                // we know we don't want a whole new copy of the obj we're
                // patching unless it's also the value itself
                serializer.remove_def(this.model);
            }
            return {
                kind: "ModelChanged",
                model: this.model.ref(),
                attr: this.attr,
                new: value_serialized,
            };
        };
        return ModelChangedEvent;
    }(DocumentChangedEvent));
    exports.ModelChangedEvent = ModelChangedEvent;
    ModelChangedEvent.__name__ = "ModelChangedEvent";
    var ColumnsPatchedEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColumnsPatchedEvent, _super);
        function ColumnsPatchedEvent(document, column_source, patches) {
            var _this = _super.call(this, document) || this;
            _this.column_source = column_source;
            _this.patches = patches;
            return _this;
        }
        ColumnsPatchedEvent.prototype[serializer_1.serialize] = function (_serializer) {
            return {
                kind: "ColumnsPatched",
                column_source: this.column_source,
                patches: this.patches,
            };
        };
        return ColumnsPatchedEvent;
    }(DocumentChangedEvent));
    exports.ColumnsPatchedEvent = ColumnsPatchedEvent;
    ColumnsPatchedEvent.__name__ = "ColumnsPatchedEvent";
    var ColumnsStreamedEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColumnsStreamedEvent, _super);
        function ColumnsStreamedEvent(document, column_source, data, rollover) {
            var _this = _super.call(this, document) || this;
            _this.column_source = column_source;
            _this.data = data;
            _this.rollover = rollover;
            return _this;
        }
        ColumnsStreamedEvent.prototype[serializer_1.serialize] = function (_serializer) {
            return {
                kind: "ColumnsStreamed",
                column_source: this.column_source,
                data: this.data,
                rollover: this.rollover,
            };
        };
        return ColumnsStreamedEvent;
    }(DocumentChangedEvent));
    exports.ColumnsStreamedEvent = ColumnsStreamedEvent;
    ColumnsStreamedEvent.__name__ = "ColumnsStreamedEvent";
    var TitleChangedEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TitleChangedEvent, _super);
        function TitleChangedEvent(document, title, setter_id) {
            var _this = _super.call(this, document) || this;
            _this.title = title;
            _this.setter_id = setter_id;
            return _this;
        }
        TitleChangedEvent.prototype[serializer_1.serialize] = function (_serializer) {
            return {
                kind: "TitleChanged",
                title: this.title,
            };
        };
        return TitleChangedEvent;
    }(DocumentChangedEvent));
    exports.TitleChangedEvent = TitleChangedEvent;
    TitleChangedEvent.__name__ = "TitleChangedEvent";
    var RootAddedEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RootAddedEvent, _super);
        function RootAddedEvent(document, model, setter_id) {
            var _this = _super.call(this, document) || this;
            _this.model = model;
            _this.setter_id = setter_id;
            return _this;
        }
        RootAddedEvent.prototype[serializer_1.serialize] = function (serializer) {
            return {
                kind: "RootAdded",
                model: serializer.to_serializable(this.model),
            };
        };
        return RootAddedEvent;
    }(DocumentChangedEvent));
    exports.RootAddedEvent = RootAddedEvent;
    RootAddedEvent.__name__ = "RootAddedEvent";
    var RootRemovedEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RootRemovedEvent, _super);
        function RootRemovedEvent(document, model, setter_id) {
            var _this = _super.call(this, document) || this;
            _this.model = model;
            _this.setter_id = setter_id;
            return _this;
        }
        RootRemovedEvent.prototype[serializer_1.serialize] = function (_serializer) {
            return {
                kind: "RootRemoved",
                model: this.model.ref(),
            };
        };
        return RootRemovedEvent;
    }(DocumentChangedEvent));
    exports.RootRemovedEvent = RootRemovedEvent;
    RootRemovedEvent.__name__ = "RootRemovedEvent";
},
/* core/util/pretty.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var types_1 = require(125) /* ./types */;
    var object_1 = require(128) /* ./object */;
    exports.pretty = Symbol("pretty");
    function is_Printable(obj) {
        return (0, types_1.isObject)(obj) && obj[exports.pretty] !== undefined;
    }
    var Printer = /** @class */ (function () {
        function Printer(options) {
            this.visited = new Set();
            this.precision = options === null || options === void 0 ? void 0 : options.precision;
        }
        Printer.prototype.to_string = function (obj) {
            if ((0, types_1.isObject)(obj)) {
                if (this.visited.has(obj))
                    return "<circular>";
                else
                    this.visited.add(obj);
            }
            if (is_Printable(obj))
                return obj[exports.pretty](this);
            else if ((0, types_1.isBoolean)(obj))
                return this.boolean(obj);
            else if ((0, types_1.isNumber)(obj))
                return this.number(obj);
            else if ((0, types_1.isString)(obj))
                return this.string(obj);
            else if ((0, types_1.isArray)(obj))
                return this.array(obj);
            else if ((0, types_1.isIterable)(obj))
                return this.iterable(obj);
            else if ((0, types_1.isPlainObject)(obj))
                return this.object(obj);
            else if ((0, types_1.isSymbol)(obj))
                return this.symbol(obj);
            else
                return "" + obj;
        };
        Printer.prototype.token = function (val) {
            return val;
        };
        Printer.prototype.boolean = function (val) {
            return "" + val;
        };
        Printer.prototype.number = function (val) {
            if (this.precision != null)
                return val.toFixed(this.precision);
            else
                return "" + val;
        };
        Printer.prototype.string = function (val) {
            return "\"" + val.replace(/'/g, "\\'") + "\""; // lgtm [js/incomplete-sanitization]
        };
        Printer.prototype.symbol = function (val) {
            return val.toString();
        };
        Printer.prototype.array = function (obj) {
            var e_1, _a;
            var T = this.token;
            var items = [];
            try {
                for (var obj_1 = (0, tslib_1.__values)(obj), obj_1_1 = obj_1.next(); !obj_1_1.done; obj_1_1 = obj_1.next()) {
                    var entry = obj_1_1.value;
                    items.push(this.to_string(entry));
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (obj_1_1 && !obj_1_1.done && (_a = obj_1.return))
                        _a.call(obj_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return "" + T("[") + items.join(T(",") + " ") + T("]");
        };
        Printer.prototype.iterable = function (obj) {
            var _a;
            var T = this.token;
            var tag = (_a = Object(obj)[Symbol.toStringTag]) !== null && _a !== void 0 ? _a : "Object";
            var items = this.array(obj);
            return "" + tag + T("(") + items + T(")");
        };
        Printer.prototype.object = function (obj) {
            var e_2, _a;
            var T = this.token;
            var items = [];
            try {
                for (var _b = (0, tslib_1.__values)((0, object_1.entries)(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var _d = (0, tslib_1.__read)(_c.value, 2), key = _d[0], val = _d[1];
                    items.push("" + key + T(":") + " " + this.to_string(val));
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return "" + T("{") + items.join(T(",") + " ") + T("}");
        };
        return Printer;
    }());
    exports.Printer = Printer;
    Printer.__name__ = "Printer";
    function to_string(obj, options) {
        var printer = new Printer(options);
        return printer.to_string(obj);
    }
    exports.to_string = to_string;
},
/* core/util/cloneable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var object_1 = require(128) /* ./object */;
    var types_1 = require(125) /* ./types */;
    //| Map<CloneableType, CloneableType>
    //| Set<CloneableType>
    exports.clone = Symbol("clone");
    function is_Cloneable(obj) {
        return (0, types_1.isObject)(obj) && obj[exports.clone] !== undefined;
    }
    exports.is_Cloneable = is_Cloneable;
    var CloningError = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CloningError, _super);
        function CloningError() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return CloningError;
    }(Error));
    exports.CloningError = CloningError;
    CloningError.__name__ = "CloningError";
    var Cloner = /** @class */ (function () {
        function Cloner() {
        }
        Cloner.prototype.clone = function (obj) {
            var e_1, _a;
            if (is_Cloneable(obj))
                return obj[exports.clone](this);
            else if ((0, types_1.isArray)(obj)) {
                var n = obj.length;
                var result = new Array(n);
                for (var i = 0; i < n; i++) {
                    var value = obj[i];
                    result[i] = this.clone(value);
                }
                return result;
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                var result = {};
                try {
                    for (var _b = (0, tslib_1.__values)((0, object_1.entries)(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var _d = (0, tslib_1.__read)(_c.value, 2), key = _d[0], value = _d[1];
                        result[key] = this.clone(value);
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
                return result;
            }
            else if (obj === null || (0, types_1.isBoolean)(obj) || (0, types_1.isNumber)(obj) || (0, types_1.isString)(obj)) {
                return obj;
            }
            else
                throw new CloningError(Object.prototype.toString.call(obj) + " is not cloneable");
        };
        return Cloner;
    }());
    exports.Cloner = Cloner;
    Cloner.__name__ = "Cloner";
},
/* models/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    (0, tslib_1.__exportStar)(require(154) /* ./annotations */, exports);
    (0, tslib_1.__exportStar)(require(242) /* ./axes */, exports);
    (0, tslib_1.__exportStar)(require(359) /* ./callbacks */, exports);
    (0, tslib_1.__exportStar)(require(363) /* ./canvas */, exports);
    (0, tslib_1.__exportStar)(require(368) /* ./expressions */, exports);
    (0, tslib_1.__exportStar)(require(377) /* ./filters */, exports);
    (0, tslib_1.__exportStar)(require(307) /* ./formatters */, exports);
    (0, tslib_1.__exportStar)(require(382) /* ./glyphs */, exports);
    (0, tslib_1.__exportStar)(require(416) /* ./graphs */, exports);
    (0, tslib_1.__exportStar)(require(420) /* ./grids */, exports);
    (0, tslib_1.__exportStar)(require(422) /* ./layouts */, exports);
    (0, tslib_1.__exportStar)(require(311) /* ./mappers */, exports);
    (0, tslib_1.__exportStar)(require(435) /* ./text */, exports);
    (0, tslib_1.__exportStar)(require(436) /* ./transforms */, exports);
    (0, tslib_1.__exportStar)(require(444) /* ./plots */, exports);
    (0, tslib_1.__exportStar)(require(452) /* ./policies */, exports);
    (0, tslib_1.__exportStar)(require(321) /* ./ranges */, exports);
    (0, tslib_1.__exportStar)(require(453) /* ./renderers */, exports);
    (0, tslib_1.__exportStar)(require(319) /* ./scales */, exports);
    (0, tslib_1.__exportStar)(require(455) /* ./selections */, exports);
    (0, tslib_1.__exportStar)(require(456) /* ./sources */, exports);
    (0, tslib_1.__exportStar)(require(283) /* ./tickers */, exports);
    (0, tslib_1.__exportStar)(require(461) /* ./tiles */, exports);
    (0, tslib_1.__exportStar)(require(471) /* ./textures */, exports);
    (0, tslib_1.__exportStar)(require(475) /* ./tools */, exports);
},
/* models/annotations/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var annotation_1 = require(155) /* ./annotation */;
    __esExport("Annotation", annotation_1.Annotation);
    var arrow_1 = require(183) /* ./arrow */;
    __esExport("Arrow", arrow_1.Arrow);
    var arrow_head_1 = require(227) /* ./arrow_head */;
    __esExport("ArrowHead", arrow_head_1.ArrowHead);
    var arrow_head_2 = require(227) /* ./arrow_head */;
    __esExport("OpenHead", arrow_head_2.OpenHead);
    var arrow_head_3 = require(227) /* ./arrow_head */;
    __esExport("NormalHead", arrow_head_3.NormalHead);
    var arrow_head_4 = require(227) /* ./arrow_head */;
    __esExport("TeeHead", arrow_head_4.TeeHead);
    var arrow_head_5 = require(227) /* ./arrow_head */;
    __esExport("VeeHead", arrow_head_5.VeeHead);
    var band_1 = require(229) /* ./band */;
    __esExport("Band", band_1.Band);
    var box_annotation_1 = require(231) /* ./box_annotation */;
    __esExport("BoxAnnotation", box_annotation_1.BoxAnnotation);
    var color_bar_1 = require(232) /* ./color_bar */;
    __esExport("ColorBar", color_bar_1.ColorBar);
    var label_1 = require(327) /* ./label */;
    __esExport("Label", label_1.Label);
    var label_set_1 = require(328) /* ./label_set */;
    __esExport("LabelSet", label_set_1.LabelSet);
    var legend_1 = require(329) /* ./legend */;
    __esExport("Legend", legend_1.Legend);
    var legend_item_1 = require(330) /* ./legend_item */;
    __esExport("LegendItem", legend_item_1.LegendItem);
    var poly_annotation_1 = require(332) /* ./poly_annotation */;
    __esExport("PolyAnnotation", poly_annotation_1.PolyAnnotation);
    var slope_1 = require(333) /* ./slope */;
    __esExport("Slope", slope_1.Slope);
    var span_1 = require(334) /* ./span */;
    __esExport("Span", span_1.Span);
    var text_annotation_1 = require(234) /* ./text_annotation */;
    __esExport("TextAnnotation", text_annotation_1.TextAnnotation);
    var title_1 = require(233) /* ./title */;
    __esExport("Title", title_1.Title);
    var toolbar_panel_1 = require(335) /* ./toolbar_panel */;
    __esExport("ToolbarPanel", toolbar_panel_1.ToolbarPanel);
    var tooltip_1 = require(356) /* ./tooltip */;
    __esExport("Tooltip", tooltip_1.Tooltip);
    var whisker_1 = require(358) /* ./whisker */;
    __esExport("Whisker", whisker_1.Whisker);
},
/* models/annotations/annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var renderer_1 = require(156) /* ../renderers/renderer */;
    var AnnotationView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AnnotationView, _super);
        function AnnotationView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AnnotationView.prototype.get_size = function () {
            if (this.model.visible) {
                var _b = this._get_size(), width = _b.width, height = _b.height;
                return { width: Math.round(width), height: Math.round(height) };
            }
            else
                return { width: 0, height: 0 };
        };
        AnnotationView.prototype._get_size = function () {
            throw new Error("not implemented");
        };
        AnnotationView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var p = this.model.properties;
            this.on_change(p.visible, function () {
                if (_this.layout != null) {
                    _this.layout.visible = _this.model.visible;
                    _this.plot_view.request_layout();
                }
            });
        };
        Object.defineProperty(AnnotationView.prototype, "needs_clip", {
            get: function () {
                return this.layout == null; // TODO: change this, when center layout is fully implemented
            },
            enumerable: false,
            configurable: true
        });
        AnnotationView.prototype.serializable_state = function () {
            var state = _super.prototype.serializable_state.call(this);
            return this.layout == null ? state : (0, tslib_1.__assign)((0, tslib_1.__assign)({}, state), { bbox: this.layout.bbox.box });
        };
        return AnnotationView;
    }(renderer_1.RendererView));
    exports.AnnotationView = AnnotationView;
    AnnotationView.__name__ = "AnnotationView";
    var Annotation = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Annotation, _super);
        function Annotation(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Annotation;
    }(renderer_1.Renderer));
    exports.Annotation = Annotation;
    _a = Annotation;
    Annotation.__name__ = "Annotation";
    (function () {
        _a.override({
            level: "annotation",
        });
    })();
},
/* models/renderers/renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b;
    var view_1 = require(157) /* ../../core/view */;
    var visuals = (0, tslib_1.__importStar)(require(160) /* ../../core/visuals */);
    var enums_1 = require(135) /* ../../core/enums */;
    var model_1 = require(168) /* ../../model */;
    var coordinates_1 = require(169) /* ../canvas/coordinates */;
    var RendererGroup = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RendererGroup, _super);
        function RendererGroup(attrs) {
            return _super.call(this, attrs) || this;
        }
        return RendererGroup;
    }(model_1.Model));
    exports.RendererGroup = RendererGroup;
    _a = RendererGroup;
    RendererGroup.__name__ = "RendererGroup";
    (function () {
        _a.define(function (_c) {
            var Boolean = _c.Boolean;
            return ({
                visible: [Boolean, true],
            });
        });
    })();
    var RendererView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RendererView, _super);
        function RendererView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(RendererView.prototype, "coordinates", {
            get: function () {
                var _coordinates = this._coordinates;
                if (_coordinates != null)
                    return _coordinates;
                else
                    return this._coordinates = this._initialize_coordinates();
            },
            enumerable: false,
            configurable: true
        });
        RendererView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.visuals = new visuals.Visuals(this);
            this.needs_webgl_blit = false;
        };
        RendererView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var _c = this.model.properties, x_range_name = _c.x_range_name, y_range_name = _c.y_range_name;
            this.on_change([x_range_name, y_range_name], function () { return _this._initialize_coordinates(); });
            var group = this.model.group;
            if (group != null) {
                this.on_change(group.properties.visible, function () {
                    _this.model.visible = group.visible;
                });
            }
        };
        RendererView.prototype._initialize_coordinates = function () {
            var coordinates = this.model.coordinates;
            var frame = this.plot_view.frame;
            if (coordinates != null) {
                return coordinates.get_transform(frame);
            }
            else {
                var _c = this.model, x_range_name = _c.x_range_name, y_range_name = _c.y_range_name;
                var x_scale = frame.x_scales.get(x_range_name);
                var y_scale = frame.y_scales.get(y_range_name);
                return new coordinates_1.CoordinateTransform(x_scale, y_scale);
            }
        };
        Object.defineProperty(RendererView.prototype, "plot_view", {
            get: function () {
                return this.parent;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RendererView.prototype, "plot_model", {
            get: function () {
                return this.parent.model;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RendererView.prototype, "layer", {
            get: function () {
                var _c = this.canvas, overlays = _c.overlays, primary = _c.primary;
                return this.model.level == "overlay" ? overlays : primary;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RendererView.prototype, "canvas", {
            get: function () {
                return this.plot_view.canvas_view;
            },
            enumerable: false,
            configurable: true
        });
        RendererView.prototype.request_render = function () {
            this.request_paint();
        };
        RendererView.prototype.request_paint = function () {
            this.plot_view.request_paint(this);
        };
        RendererView.prototype.request_layout = function () {
            this.plot_view.request_layout();
        };
        RendererView.prototype.notify_finished = function () {
            this.plot_view.notify_finished();
        };
        RendererView.prototype.notify_finished_after_paint = function () {
            this.plot_view.notify_finished_after_paint();
        };
        Object.defineProperty(RendererView.prototype, "needs_clip", {
            get: function () {
                return false;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(RendererView.prototype, "has_webgl", {
            get: function () {
                return false;
            },
            enumerable: false,
            configurable: true
        });
        /*
        get visible(): boolean {
          const {visible, group} = this.model
          return !visible ? false : (group?.visible ?? true)
        }
        */
        RendererView.prototype.render = function () {
            if (this.model.visible) {
                this._render();
            }
            this._has_finished = true;
        };
        RendererView.prototype.renderer_view = function (_renderer) {
            return undefined;
        };
        return RendererView;
    }(view_1.View));
    exports.RendererView = RendererView;
    RendererView.__name__ = "RendererView";
    var Renderer = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Renderer, _super);
        function Renderer(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Renderer;
    }(model_1.Model));
    exports.Renderer = Renderer;
    _b = Renderer;
    Renderer.__name__ = "Renderer";
    (function () {
        _b.define(function (_c) {
            var Boolean = _c.Boolean, String = _c.String, Ref = _c.Ref, Nullable = _c.Nullable;
            return ({
                group: [Nullable(Ref(RendererGroup)), null],
                level: [enums_1.RenderLevel, "image"],
                visible: [Boolean, true],
                x_range_name: [String, "default"],
                y_range_name: [String, "default"],
                coordinates: [Nullable(Ref(coordinates_1.CoordinateMapping)), null],
            });
        });
    })();
},
/* core/view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var signaling_1 = require(130) /* ./signaling */;
    var dom_1 = require(158) /* ./dom */;
    var types_1 = require(125) /* ./util/types */;
    var root_css_1 = (0, tslib_1.__importDefault)(require(159) /* ../styles/root.css */);
    var View = /** @class */ (function () {
        function View(options) {
            this.removed = new signaling_1.Signal0(this, "removed");
            this._ready = Promise.resolve(undefined);
            /** @internal */
            this._slots = new WeakMap();
            this._idle_notified = false;
            var model = options.model, parent = options.parent;
            this.model = model;
            this.parent = parent;
            this.root = parent == null ? this : parent.root;
            this.removed.emit();
        }
        Object.defineProperty(View.prototype, "ready", {
            get: function () {
                return this._ready;
            },
            enumerable: false,
            configurable: true
        });
        View.prototype.connect = function (signal, slot) {
            var _this = this;
            var new_slot = this._slots.get(slot);
            if (new_slot == null) {
                new_slot = function (args, sender) {
                    var promise = Promise.resolve(slot.call(_this, args, sender));
                    _this._ready = _this._ready.then(function () { return promise; });
                };
                this._slots.set(slot, new_slot);
            }
            return signal.connect(new_slot, this);
        };
        View.prototype.disconnect = function (signal, slot) {
            return signal.disconnect(slot, this);
        };
        View.prototype.initialize = function () {
            var e_1, _a;
            this._has_finished = false;
            if (this.is_root) {
                this._stylesheet = dom_1.stylesheet;
            }
            try {
                for (var _b = (0, tslib_1.__values)(this.styles()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var style = _c.value;
                    this.stylesheet.append(style);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        View.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_a) {
                    return [2 /*return*/];
                });
            });
        };
        View.prototype.remove = function () {
            this.disconnect_signals();
            this.removed.emit();
        };
        View.prototype.toString = function () {
            return this.model.type + "View(" + this.model.id + ")";
        };
        View.prototype.serializable_state = function () {
            return { type: this.model.type };
        };
        Object.defineProperty(View.prototype, "is_root", {
            get: function () {
                return this.parent == null;
            },
            enumerable: false,
            configurable: true
        });
        View.prototype.has_finished = function () {
            return this._has_finished;
        };
        Object.defineProperty(View.prototype, "is_idle", {
            get: function () {
                return this.has_finished();
            },
            enumerable: false,
            configurable: true
        });
        View.prototype.connect_signals = function () { };
        View.prototype.disconnect_signals = function () {
            signaling_1.Signal.disconnect_receiver(this);
        };
        View.prototype.on_change = function (properties, fn) {
            var e_2, _a;
            try {
                for (var _b = (0, tslib_1.__values)((0, types_1.isArray)(properties) ? properties : [properties]), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var property = _c.value;
                    this.connect(property.change, fn);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        };
        View.prototype.cursor = function (_sx, _sy) {
            return null;
        };
        Object.defineProperty(View.prototype, "stylesheet", {
            get: function () {
                if (this.is_root)
                    return this._stylesheet;
                else
                    return this.root.stylesheet;
            },
            enumerable: false,
            configurable: true
        });
        View.prototype.styles = function () {
            return [root_css_1.default];
        };
        View.prototype.notify_finished = function () {
            if (!this.is_root)
                this.root.notify_finished();
            else {
                if (!this._idle_notified && this.has_finished()) {
                    if (this.model.document != null) {
                        this._idle_notified = true;
                        this.model.document.notify_idle(this.model);
                    }
                }
            }
        };
        return View;
    }());
    exports.View = View;
    View.__name__ = "View";
},
/* core/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var types_1 = require(125) /* ./util/types */;
    var object_1 = require(128) /* ./util/object */;
    var _createElement = function (tag) {
        return function (attrs) {
            var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
            if (attrs === void 0) {
                attrs = {};
            }
            var children = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                children[_i - 1] = arguments[_i];
            }
            var element = document.createElement(tag);
            element.classList.add("bk");
            if (!(0, types_1.isPlainObject)(attrs)) {
                children = (0, tslib_1.__spreadArray)([attrs], (0, tslib_1.__read)(children), false);
                attrs = {};
            }
            try {
                for (var _g = (0, tslib_1.__values)((0, object_1.entries)(attrs)), _h = _g.next(); !_h.done; _h = _g.next()) {
                    var _j = (0, tslib_1.__read)(_h.value, 2), attr = _j[0], value = _j[1];
                    if (value == null || (0, types_1.isBoolean)(value) && !value)
                        continue;
                    if (attr === "class") {
                        if ((0, types_1.isString)(value))
                            value = value.split(/\s+/);
                        if ((0, types_1.isArray)(value)) {
                            try {
                                for (var value_1 = (e_2 = void 0, (0, tslib_1.__values)(value)), value_1_1 = value_1.next(); !value_1_1.done; value_1_1 = value_1.next()) {
                                    var cls = value_1_1.value;
                                    if (cls != null)
                                        element.classList.add(cls);
                                }
                            }
                            catch (e_2_1) {
                                e_2 = { error: e_2_1 };
                            }
                            finally {
                                try {
                                    if (value_1_1 && !value_1_1.done && (_b = value_1.return))
                                        _b.call(value_1);
                                }
                                finally {
                                    if (e_2)
                                        throw e_2.error;
                                }
                            }
                            continue;
                        }
                    }
                    if (attr === "style" && (0, types_1.isPlainObject)(value)) {
                        try {
                            for (var _k = (e_3 = void 0, (0, tslib_1.__values)((0, object_1.entries)(value))), _l = _k.next(); !_l.done; _l = _k.next()) {
                                var _m = (0, tslib_1.__read)(_l.value, 2), prop = _m[0], data = _m[1];
                                element.style[prop] = data;
                            }
                        }
                        catch (e_3_1) {
                            e_3 = { error: e_3_1 };
                        }
                        finally {
                            try {
                                if (_l && !_l.done && (_c = _k.return))
                                    _c.call(_k);
                            }
                            finally {
                                if (e_3)
                                    throw e_3.error;
                            }
                        }
                        continue;
                    }
                    if (attr === "data" && (0, types_1.isPlainObject)(value)) {
                        try {
                            for (var _o = (e_4 = void 0, (0, tslib_1.__values)((0, object_1.entries)(value))), _p = _o.next(); !_p.done; _p = _o.next()) {
                                var _q = (0, tslib_1.__read)(_p.value, 2), key = _q[0], data = _q[1];
                                element.dataset[key] = data; // XXX: attrs needs a better type
                            }
                        }
                        catch (e_4_1) {
                            e_4 = { error: e_4_1 };
                        }
                        finally {
                            try {
                                if (_p && !_p.done && (_d = _o.return))
                                    _d.call(_o);
                            }
                            finally {
                                if (e_4)
                                    throw e_4.error;
                            }
                        }
                        continue;
                    }
                    element.setAttribute(attr, value);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_h && !_h.done && (_a = _g.return))
                        _a.call(_g);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            function append(child) {
                var e_7, _a;
                if ((0, types_1.isString)(child))
                    element.appendChild(document.createTextNode(child));
                else if (child instanceof Node)
                    element.appendChild(child);
                else if (child instanceof NodeList || child instanceof HTMLCollection) {
                    try {
                        for (var child_2 = (0, tslib_1.__values)(child), child_2_1 = child_2.next(); !child_2_1.done; child_2_1 = child_2.next()) {
                            var el = child_2_1.value;
                            element.appendChild(el);
                        }
                    }
                    catch (e_7_1) {
                        e_7 = { error: e_7_1 };
                    }
                    finally {
                        try {
                            if (child_2_1 && !child_2_1.done && (_a = child_2.return))
                                _a.call(child_2);
                        }
                        finally {
                            if (e_7)
                                throw e_7.error;
                        }
                    }
                }
                else if (child != null && child !== false)
                    throw new Error("expected a DOM element, string, false or null, got " + JSON.stringify(child));
            }
            try {
                for (var children_1 = (0, tslib_1.__values)(children), children_1_1 = children_1.next(); !children_1_1.done; children_1_1 = children_1.next()) {
                    var child = children_1_1.value;
                    if ((0, types_1.isArray)(child)) {
                        try {
                            for (var child_1 = (e_6 = void 0, (0, tslib_1.__values)(child)), child_1_1 = child_1.next(); !child_1_1.done; child_1_1 = child_1.next()) {
                                var _child = child_1_1.value;
                                append(_child);
                            }
                        }
                        catch (e_6_1) {
                            e_6 = { error: e_6_1 };
                        }
                        finally {
                            try {
                                if (child_1_1 && !child_1_1.done && (_f = child_1.return))
                                    _f.call(child_1);
                            }
                            finally {
                                if (e_6)
                                    throw e_6.error;
                            }
                        }
                    }
                    else
                        append(child);
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (children_1_1 && !children_1_1.done && (_e = children_1.return))
                        _e.call(children_1);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            return element;
        };
    };
    function createElement(tag, attrs) {
        var children = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            children[_i - 2] = arguments[_i];
        }
        return _createElement(tag).apply(void 0, (0, tslib_1.__spreadArray)([attrs], (0, tslib_1.__read)(children), false));
    }
    exports.createElement = createElement;
    exports.div = _createElement("div"), exports.span = _createElement("span"), exports.canvas = _createElement("canvas"), exports.link = _createElement("link"), exports.style = _createElement("style"), exports.a = _createElement("a"), exports.p = _createElement("p"), exports.i = _createElement("i"), exports.pre = _createElement("pre"), exports.button = _createElement("button"), exports.label = _createElement("label"), exports.input = _createElement("input"), exports.select = _createElement("select"), exports.option = _createElement("option"), exports.optgroup = _createElement("optgroup"), exports.textarea = _createElement("textarea");
    function createSVGElement(tag, attrs) {
        var e_8, _a, e_9, _b, e_10, _c;
        var children = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            children[_i - 2] = arguments[_i];
        }
        var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
        try {
            for (var _d = (0, tslib_1.__values)((0, object_1.entries)(attrs !== null && attrs !== void 0 ? attrs : {})), _e = _d.next(); !_e.done; _e = _d.next()) {
                var _f = (0, tslib_1.__read)(_e.value, 2), attr = _f[0], value = _f[1];
                if (value == null || (0, types_1.isBoolean)(value) && !value)
                    continue;
                element.setAttribute(attr, value);
            }
        }
        catch (e_8_1) {
            e_8 = { error: e_8_1 };
        }
        finally {
            try {
                if (_e && !_e.done && (_a = _d.return))
                    _a.call(_d);
            }
            finally {
                if (e_8)
                    throw e_8.error;
            }
        }
        function append(child) {
            var e_11, _a;
            if ((0, types_1.isString)(child))
                element.appendChild(document.createTextNode(child));
            else if (child instanceof Node)
                element.appendChild(child);
            else if (child instanceof NodeList || child instanceof HTMLCollection) {
                try {
                    for (var child_4 = (0, tslib_1.__values)(child), child_4_1 = child_4.next(); !child_4_1.done; child_4_1 = child_4.next()) {
                        var el = child_4_1.value;
                        element.appendChild(el);
                    }
                }
                catch (e_11_1) {
                    e_11 = { error: e_11_1 };
                }
                finally {
                    try {
                        if (child_4_1 && !child_4_1.done && (_a = child_4.return))
                            _a.call(child_4);
                    }
                    finally {
                        if (e_11)
                            throw e_11.error;
                    }
                }
            }
            else if (child != null && child !== false)
                throw new Error("expected a DOM element, string, false or null, got " + JSON.stringify(child));
        }
        try {
            for (var children_2 = (0, tslib_1.__values)(children), children_2_1 = children_2.next(); !children_2_1.done; children_2_1 = children_2.next()) {
                var child = children_2_1.value;
                if ((0, types_1.isArray)(child)) {
                    try {
                        for (var child_3 = (e_10 = void 0, (0, tslib_1.__values)(child)), child_3_1 = child_3.next(); !child_3_1.done; child_3_1 = child_3.next()) {
                            var _child = child_3_1.value;
                            append(_child);
                        }
                    }
                    catch (e_10_1) {
                        e_10 = { error: e_10_1 };
                    }
                    finally {
                        try {
                            if (child_3_1 && !child_3_1.done && (_c = child_3.return))
                                _c.call(child_3);
                        }
                        finally {
                            if (e_10)
                                throw e_10.error;
                        }
                    }
                }
                else
                    append(child);
            }
        }
        catch (e_9_1) {
            e_9 = { error: e_9_1 };
        }
        finally {
            try {
                if (children_2_1 && !children_2_1.done && (_b = children_2.return))
                    _b.call(children_2);
            }
            finally {
                if (e_9)
                    throw e_9.error;
            }
        }
        return element;
    }
    exports.createSVGElement = createSVGElement;
    function nbsp() {
        return document.createTextNode("\u00a0");
    }
    exports.nbsp = nbsp;
    function append(element) {
        var e_12, _a;
        var children = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            children[_i - 1] = arguments[_i];
        }
        try {
            for (var children_3 = (0, tslib_1.__values)(children), children_3_1 = children_3.next(); !children_3_1.done; children_3_1 = children_3.next()) {
                var child = children_3_1.value;
                element.appendChild(child);
            }
        }
        catch (e_12_1) {
            e_12 = { error: e_12_1 };
        }
        finally {
            try {
                if (children_3_1 && !children_3_1.done && (_a = children_3.return))
                    _a.call(children_3);
            }
            finally {
                if (e_12)
                    throw e_12.error;
            }
        }
    }
    exports.append = append;
    function remove(element) {
        var parent = element.parentNode;
        if (parent != null) {
            parent.removeChild(element);
        }
    }
    exports.remove = remove;
    exports.removeElement = remove;
    function replaceWith(element, replacement) {
        var parent = element.parentNode;
        if (parent != null) {
            parent.replaceChild(replacement, element);
        }
    }
    exports.replaceWith = replaceWith;
    function prepend(element) {
        var e_13, _a;
        var nodes = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            nodes[_i - 1] = arguments[_i];
        }
        var first = element.firstChild;
        try {
            for (var nodes_1 = (0, tslib_1.__values)(nodes), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) {
                var node = nodes_1_1.value;
                element.insertBefore(node, first);
            }
        }
        catch (e_13_1) {
            e_13 = { error: e_13_1 };
        }
        finally {
            try {
                if (nodes_1_1 && !nodes_1_1.done && (_a = nodes_1.return))
                    _a.call(nodes_1);
            }
            finally {
                if (e_13)
                    throw e_13.error;
            }
        }
    }
    exports.prepend = prepend;
    function empty(node, attrs) {
        var e_14, _a;
        if (attrs === void 0) {
            attrs = false;
        }
        var child;
        while (child = node.firstChild) {
            node.removeChild(child);
        }
        if (attrs && node instanceof Element) {
            try {
                for (var _b = (0, tslib_1.__values)(node.attributes), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var attr = _c.value;
                    node.removeAttributeNode(attr);
                }
            }
            catch (e_14_1) {
                e_14 = { error: e_14_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_14)
                        throw e_14.error;
                }
            }
        }
    }
    exports.empty = empty;
    function display(element) {
        element.style.display = "";
    }
    exports.display = display;
    function undisplay(element) {
        element.style.display = "none";
    }
    exports.undisplay = undisplay;
    function show(element) {
        element.style.visibility = "";
    }
    exports.show = show;
    function hide(element) {
        element.style.visibility = "hidden";
    }
    exports.hide = hide;
    function offset(element) {
        var rect = element.getBoundingClientRect();
        return {
            top: rect.top + window.pageYOffset - document.documentElement.clientTop,
            left: rect.left + window.pageXOffset - document.documentElement.clientLeft,
        };
    }
    exports.offset = offset;
    function matches(el, selector) {
        var _a, _b, _c;
        var p = Element.prototype;
        var f = (_c = (_b = (_a = p.matches) !== null && _a !== void 0 ? _a : p.webkitMatchesSelector) !== null && _b !== void 0 ? _b : p.mozMatchesSelector) !== null && _c !== void 0 ? _c : p.msMatchesSelector;
        return f.call(el, selector);
    }
    exports.matches = matches;
    function parent(el, selector) {
        var node = el;
        while (node = node.parentElement) {
            if (matches(node, selector))
                return node;
        }
        return null;
    }
    exports.parent = parent;
    function num(value) {
        return parseFloat(value) || 0;
    }
    function extents(el) {
        var style = getComputedStyle(el);
        return {
            border: {
                top: num(style.borderTopWidth),
                bottom: num(style.borderBottomWidth),
                left: num(style.borderLeftWidth),
                right: num(style.borderRightWidth),
            },
            margin: {
                top: num(style.marginTop),
                bottom: num(style.marginBottom),
                left: num(style.marginLeft),
                right: num(style.marginRight),
            },
            padding: {
                top: num(style.paddingTop),
                bottom: num(style.paddingBottom),
                left: num(style.paddingLeft),
                right: num(style.paddingRight),
            },
        };
    }
    exports.extents = extents;
    function size(el) {
        var rect = el.getBoundingClientRect();
        return {
            width: Math.ceil(rect.width),
            height: Math.ceil(rect.height),
        };
    }
    exports.size = size;
    function scroll_size(el) {
        return {
            width: Math.ceil(el.scrollWidth),
            height: Math.ceil(el.scrollHeight),
        };
    }
    exports.scroll_size = scroll_size;
    function outer_size(el) {
        var _a = extents(el).margin, left = _a.left, right = _a.right, top = _a.top, bottom = _a.bottom;
        var _b = size(el), width = _b.width, height = _b.height;
        return {
            width: Math.ceil(width + left + right),
            height: Math.ceil(height + top + bottom),
        };
    }
    exports.outer_size = outer_size;
    function content_size(el) {
        var e_15, _a;
        var _b = el.getBoundingClientRect(), left = _b.left, top = _b.top;
        var padding = extents(el).padding;
        var width = 0;
        var height = 0;
        try {
            for (var _c = (0, tslib_1.__values)(el.children), _d = _c.next(); !_d.done; _d = _c.next()) {
                var child = _d.value;
                var rect = child.getBoundingClientRect();
                width = Math.max(width, Math.ceil(rect.left - left - padding.left + rect.width));
                height = Math.max(height, Math.ceil(rect.top - top - padding.top + rect.height));
            }
        }
        catch (e_15_1) {
            e_15 = { error: e_15_1 };
        }
        finally {
            try {
                if (_d && !_d.done && (_a = _c.return))
                    _a.call(_c);
            }
            finally {
                if (e_15)
                    throw e_15.error;
            }
        }
        return { width: width, height: height };
    }
    exports.content_size = content_size;
    function position(el, box, margin) {
        var style = el.style;
        style.left = box.x + "px";
        style.top = box.y + "px";
        style.width = box.width + "px";
        style.height = box.height + "px";
        if (margin == null)
            style.margin = "";
        else {
            var top = margin.top, right = margin.right, bottom = margin.bottom, left = margin.left;
            style.margin = top + "px " + right + "px " + bottom + "px " + left + "px";
        }
    }
    exports.position = position;
    function children(el) {
        return Array.from(el.children);
    }
    exports.children = children;
    var ClassList = /** @class */ (function () {
        function ClassList(el) {
            this.el = el;
            this.classList = el.classList;
        }
        Object.defineProperty(ClassList.prototype, "values", {
            get: function () {
                var values = [];
                for (var i_1 = 0; i_1 < this.classList.length; i_1++) {
                    var item = this.classList.item(i_1);
                    if (item != null)
                        values.push(item);
                }
                return values;
            },
            enumerable: false,
            configurable: true
        });
        ClassList.prototype.has = function (cls) {
            return this.classList.contains(cls);
        };
        ClassList.prototype.add = function () {
            var e_16, _a;
            var classes = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                classes[_i] = arguments[_i];
            }
            try {
                for (var classes_1 = (0, tslib_1.__values)(classes), classes_1_1 = classes_1.next(); !classes_1_1.done; classes_1_1 = classes_1.next()) {
                    var cls = classes_1_1.value;
                    this.classList.add(cls);
                }
            }
            catch (e_16_1) {
                e_16 = { error: e_16_1 };
            }
            finally {
                try {
                    if (classes_1_1 && !classes_1_1.done && (_a = classes_1.return))
                        _a.call(classes_1);
                }
                finally {
                    if (e_16)
                        throw e_16.error;
                }
            }
            return this;
        };
        ClassList.prototype.remove = function () {
            var e_17, _a;
            var classes = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                classes[_i] = arguments[_i];
            }
            try {
                for (var classes_2 = (0, tslib_1.__values)(classes), classes_2_1 = classes_2.next(); !classes_2_1.done; classes_2_1 = classes_2.next()) {
                    var cls = classes_2_1.value;
                    this.classList.remove(cls);
                }
            }
            catch (e_17_1) {
                e_17 = { error: e_17_1 };
            }
            finally {
                try {
                    if (classes_2_1 && !classes_2_1.done && (_a = classes_2.return))
                        _a.call(classes_2);
                }
                finally {
                    if (e_17)
                        throw e_17.error;
                }
            }
            return this;
        };
        ClassList.prototype.clear = function () {
            var e_18, _a;
            try {
                for (var _b = (0, tslib_1.__values)(this.values), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var cls = _c.value;
                    if (cls != "bk")
                        this.classList.remove(cls);
                }
            }
            catch (e_18_1) {
                e_18 = { error: e_18_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_18)
                        throw e_18.error;
                }
            }
            return this;
        };
        ClassList.prototype.toggle = function (cls, activate) {
            var add = activate != null ? activate : !this.has(cls);
            if (add)
                this.add(cls);
            else
                this.remove(cls);
            return this;
        };
        return ClassList;
    }());
    exports.ClassList = ClassList;
    ClassList.__name__ = "ClassList";
    function classes(el) {
        return new ClassList(el);
    }
    exports.classes = classes;
    function toggle_attribute(el, attr, state) {
        if (state == null) {
            state = !el.hasAttribute(attr);
        }
        if (state)
            el.setAttribute(attr, "true");
        else
            el.removeAttribute(attr);
    }
    exports.toggle_attribute = toggle_attribute;
    (function (Keys) {
        Keys[Keys["Backspace"] = 8] = "Backspace";
        Keys[Keys["Tab"] = 9] = "Tab";
        Keys[Keys["Enter"] = 13] = "Enter";
        Keys[Keys["Esc"] = 27] = "Esc";
        Keys[Keys["PageUp"] = 33] = "PageUp";
        Keys[Keys["PageDown"] = 34] = "PageDown";
        Keys[Keys["Left"] = 37] = "Left";
        Keys[Keys["Up"] = 38] = "Up";
        Keys[Keys["Right"] = 39] = "Right";
        Keys[Keys["Down"] = 40] = "Down";
        Keys[Keys["Delete"] = 46] = "Delete";
    })(exports.Keys || (exports.Keys = {}));
    function undisplayed(el, fn) {
        var display = el.style.display;
        el.style.display = "none";
        try {
            return fn();
        }
        finally {
            el.style.display = display;
        }
    }
    exports.undisplayed = undisplayed;
    function unsized(el, fn) {
        return sized(el, {}, fn);
    }
    exports.unsized = unsized;
    function sized(el, size, fn) {
        var _a = el.style, width = _a.width, height = _a.height, position = _a.position, display = _a.display;
        el.style.position = "absolute";
        el.style.display = "";
        el.style.width = size.width != null && size.width != Infinity ? size.width + "px" : "auto";
        el.style.height = size.height != null && size.height != Infinity ? size.height + "px" : "auto";
        try {
            return fn();
        }
        finally {
            el.style.position = position;
            el.style.display = display;
            el.style.width = width;
            el.style.height = height;
        }
    }
    exports.sized = sized;
    var StyleSheet = /** @class */ (function () {
        function StyleSheet(root) {
            this.root = root;
            this.known = new Set();
            this.style = (0, exports.style)({ type: "text/css" });
            prepend(root, this.style);
        }
        StyleSheet.prototype.append = function (css) {
            if (!this.known.has(css)) {
                this.style.appendChild(document.createTextNode(css));
                this.known.add(css);
            }
        };
        return StyleSheet;
    }());
    exports.StyleSheet = StyleSheet;
    StyleSheet.__name__ = "StyleSheet";
    exports.stylesheet = new StyleSheet(document.head);
    function dom_ready() {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                if (document.readyState == "loading") {
                    return [2 /*return*/, new Promise(function (resolve, _reject) {
                            document.addEventListener("DOMContentLoaded", function () { return resolve(); }, { once: true });
                        })];
                }
                return [2 /*return*/];
            });
        });
    }
    exports.dom_ready = dom_ready;
},
/* styles/root.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.default = ".bk-root{position:relative;width:auto;height:auto;box-sizing:border-box;font-family:Helvetica, Arial, sans-serif;font-size:13px;}.bk-root .bk,.bk-root .bk:before,.bk-root .bk:after{box-sizing:inherit;margin:0;border:0;padding:0;background-image:none;font-family:inherit;font-size:100%;line-height:1.42857143;}.bk-root pre.bk{font-family:Courier, monospace;}";
},
/* core/visuals/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var line_1 = require(161) /* ./line */;
    __esExport("Line", line_1.Line);
    __esExport("LineScalar", line_1.LineScalar);
    __esExport("LineVector", line_1.LineVector);
    var fill_1 = require(164) /* ./fill */;
    __esExport("Fill", fill_1.Fill);
    __esExport("FillScalar", fill_1.FillScalar);
    __esExport("FillVector", fill_1.FillVector);
    var text_1 = require(165) /* ./text */;
    __esExport("Text", text_1.Text);
    __esExport("TextScalar", text_1.TextScalar);
    __esExport("TextVector", text_1.TextVector);
    var hatch_1 = require(166) /* ./hatch */;
    __esExport("Hatch", hatch_1.Hatch);
    __esExport("HatchScalar", hatch_1.HatchScalar);
    __esExport("HatchVector", hatch_1.HatchVector);
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../property_mixins */);
    var visual_1 = require(162) /* ./visual */;
    __esExport("VisualProperties", visual_1.VisualProperties);
    __esExport("VisualUniforms", visual_1.VisualUniforms);
    var Visuals = /** @class */ (function () {
        function Visuals(view) {
            var e_1, _a;
            this._visuals = [];
            var _loop_1 = function (prefix, mixin) {
                var visual = (function () {
                    switch (mixin) {
                        case mixins.Line: return new line_1.Line(view, prefix);
                        case mixins.LineScalar: return new line_1.LineScalar(view, prefix);
                        case mixins.LineVector: return new line_1.LineVector(view, prefix);
                        case mixins.Fill: return new fill_1.Fill(view, prefix);
                        case mixins.FillScalar: return new fill_1.FillScalar(view, prefix);
                        case mixins.FillVector: return new fill_1.FillVector(view, prefix);
                        case mixins.Text: return new text_1.Text(view, prefix);
                        case mixins.TextScalar: return new text_1.TextScalar(view, prefix);
                        case mixins.TextVector: return new text_1.TextVector(view, prefix);
                        case mixins.Hatch: return new hatch_1.Hatch(view, prefix);
                        case mixins.HatchScalar: return new hatch_1.HatchScalar(view, prefix);
                        case mixins.HatchVector: return new hatch_1.HatchVector(view, prefix);
                        default:
                            throw new Error("unknown visual");
                    }
                })();
                if (visual instanceof visual_1.VisualProperties)
                    visual.update();
                this_1._visuals.push(visual);
                Object.defineProperty(this_1, prefix + visual.type, {
                    get: function () { return visual; },
                    configurable: false,
                    enumerable: true,
                });
            };
            var this_1 = this;
            try {
                for (var _b = (0, tslib_1.__values)(view.model._mixins), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var _d = (0, tslib_1.__read)(_c.value, 2), prefix = _d[0], mixin = _d[1];
                    _loop_1(prefix, mixin);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        }
        Visuals.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [5 /*yield**/, (0, tslib_1.__values)(this._visuals)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        };
        return Visuals;
    }());
    exports.Visuals = Visuals;
    Visuals.__name__ = "Visuals";
},
/* core/visuals/line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var visual_1 = require(162) /* ./visual */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../property_mixins */);
    var color_1 = require(137) /* ../util/color */;
    var types_1 = require(125) /* ../util/types */;
    function resolve_line_dash(line_dash) {
        if ((0, types_1.isArray)(line_dash))
            return line_dash;
        else {
            switch (line_dash) {
                case "solid": return [];
                case "dashed": return [6];
                case "dotted": return [2, 4];
                case "dotdash": return [2, 4, 6, 4];
                case "dashdot": return [6, 4, 2, 4];
                default:
                    return line_dash.split(" ").map(Number).filter(types_1.isInteger);
            }
        }
    }
    exports.resolve_line_dash = resolve_line_dash;
    var Line = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Line, _super);
        function Line() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(Line.prototype, "doit", {
            get: function () {
                var color = this.line_color.get_value();
                var alpha = this.line_alpha.get_value();
                var width = this.line_width.get_value();
                return !(color == null || alpha == 0 || width == 0);
            },
            enumerable: false,
            configurable: true
        });
        Line.prototype.apply = function (ctx) {
            var doit = this.doit;
            if (doit) {
                this.set_value(ctx);
                ctx.stroke();
            }
            return doit;
        };
        Line.prototype.values = function () {
            return {
                color: this.line_color.get_value(),
                alpha: this.line_alpha.get_value(),
                width: this.line_width.get_value(),
                join: this.line_join.get_value(),
                cap: this.line_cap.get_value(),
                dash: this.line_dash.get_value(),
                offset: this.line_dash_offset.get_value(),
            };
        };
        Line.prototype.set_value = function (ctx) {
            var color = this.line_color.get_value();
            var alpha = this.line_alpha.get_value();
            ctx.strokeStyle = (0, color_1.color2css)(color, alpha);
            ctx.lineWidth = this.line_width.get_value();
            ctx.lineJoin = this.line_join.get_value();
            ctx.lineCap = this.line_cap.get_value();
            ctx.lineDash = resolve_line_dash(this.line_dash.get_value());
            ctx.lineDashOffset = this.line_dash_offset.get_value();
        };
        return Line;
    }(visual_1.VisualProperties));
    exports.Line = Line;
    Line.__name__ = "Line";
    var LineScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineScalar, _super);
        function LineScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(LineScalar.prototype, "doit", {
            get: function () {
                var color = this.line_color.value;
                var alpha = this.line_alpha.value;
                var width = this.line_width.value;
                return !(color == 0 || alpha == 0 || width == 0);
            },
            enumerable: false,
            configurable: true
        });
        LineScalar.prototype.apply = function (ctx) {
            var doit = this.doit;
            if (doit) {
                this.set_value(ctx);
                ctx.stroke();
            }
            return doit;
        };
        LineScalar.prototype.values = function () {
            return {
                color: this.line_color.value,
                alpha: this.line_alpha.value,
                width: this.line_width.value,
                join: this.line_join.value,
                cap: this.line_cap.value,
                dash: this.line_dash.value,
                offset: this.line_dash_offset.value,
            };
        };
        LineScalar.prototype.set_value = function (ctx) {
            var color = this.line_color.value;
            var alpha = this.line_alpha.value;
            ctx.strokeStyle = (0, color_1.color2css)(color, alpha);
            ctx.lineWidth = this.line_width.value;
            ctx.lineJoin = this.line_join.value;
            ctx.lineCap = this.line_cap.value;
            ctx.lineDash = resolve_line_dash(this.line_dash.value);
            ctx.lineDashOffset = this.line_dash_offset.value;
        };
        return LineScalar;
    }(visual_1.VisualUniforms));
    exports.LineScalar = LineScalar;
    LineScalar.__name__ = "LineScalar";
    var LineVector = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineVector, _super);
        function LineVector() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(LineVector.prototype, "doit", {
            get: function () {
                var line_color = this.line_color;
                if (line_color.is_Scalar() && line_color.value == 0)
                    return false;
                var line_alpha = this.line_alpha;
                if (line_alpha.is_Scalar() && line_alpha.value == 0)
                    return false;
                var line_width = this.line_width;
                if (line_width.is_Scalar() && line_width.value == 0)
                    return false;
                return true;
            },
            enumerable: false,
            configurable: true
        });
        LineVector.prototype.apply = function (ctx, i) {
            var doit = this.doit;
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.stroke();
            }
            return doit;
        };
        LineVector.prototype.values = function (i) {
            return {
                color: this.line_color.get(i),
                alpha: this.line_alpha.get(i),
                width: this.line_width.get(i),
                join: this.line_join.get(i),
                cap: this.line_cap.get(i),
                dash: this.line_dash.get(i),
                offset: this.line_dash_offset.get(i),
            };
        };
        LineVector.prototype.set_vectorize = function (ctx, i) {
            var color = this.line_color.get(i);
            var alpha = this.line_alpha.get(i);
            var width = this.line_width.get(i);
            var join = this.line_join.get(i);
            var cap = this.line_cap.get(i);
            var dash = this.line_dash.get(i);
            var offset = this.line_dash_offset.get(i);
            ctx.strokeStyle = (0, color_1.color2css)(color, alpha);
            ctx.lineWidth = width;
            ctx.lineJoin = join;
            ctx.lineCap = cap;
            ctx.lineDash = resolve_line_dash(dash);
            ctx.lineDashOffset = offset;
        };
        return LineVector;
    }(visual_1.VisualUniforms));
    exports.LineVector = LineVector;
    LineVector.__name__ = "LineVector";
    Line.prototype.type = "line";
    Line.prototype.attrs = Object.keys(mixins.Line);
    LineScalar.prototype.type = "line";
    LineScalar.prototype.attrs = Object.keys(mixins.LineScalar);
    LineVector.prototype.type = "line";
    LineVector.prototype.attrs = Object.keys(mixins.LineVector);
},
/* core/visuals/visual.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var VisualProperties = /** @class */ (function () {
        function VisualProperties(obj, prefix) {
            var e_1, _a;
            var _this = this;
            if (prefix === void 0) {
                prefix = "";
            }
            this.obj = obj;
            this.prefix = prefix;
            var self = this;
            this._props = [];
            try {
                for (var _b = (0, tslib_1.__values)(this.attrs), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var attr = _c.value;
                    var prop = obj.model.properties[prefix + attr];
                    prop.change.connect(function () { return _this.update(); });
                    self[attr] = prop;
                    this._props.push(prop);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        }
        VisualProperties.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [5 /*yield**/, (0, tslib_1.__values)(this._props)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        };
        VisualProperties.prototype.update = function () { };
        return VisualProperties;
    }());
    exports.VisualProperties = VisualProperties;
    VisualProperties.__name__ = "VisualProperties";
    var VisualUniforms = /** @class */ (function () {
        function VisualUniforms(obj, prefix) {
            var e_2, _a;
            if (prefix === void 0) {
                prefix = "";
            }
            this.obj = obj;
            this.prefix = prefix;
            var _loop_1 = function (attr) {
                Object.defineProperty(this_1, attr, {
                    get: function () {
                        return obj[prefix + attr];
                    },
                });
            };
            var this_1 = this;
            try {
                for (var _b = (0, tslib_1.__values)(this.attrs), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var attr = _c.value;
                    _loop_1(attr);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        }
        VisualUniforms.prototype[Symbol.iterator] = function () {
            var _a, _b, attr, e_3_1;
            var e_3, _c;
            return (0, tslib_1.__generator)(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 5, 6, 7]);
                        _a = (0, tslib_1.__values)(this.attrs), _b = _a.next();
                        _d.label = 1;
                    case 1:
                        if (!!_b.done)
                            return [3 /*break*/, 4];
                        attr = _b.value;
                        return [4 /*yield*/, this.obj.model.properties[this.prefix + attr]];
                    case 2:
                        _d.sent();
                        _d.label = 3;
                    case 3:
                        _b = _a.next();
                        return [3 /*break*/, 1];
                    case 4: return [3 /*break*/, 7];
                    case 5:
                        e_3_1 = _d.sent();
                        e_3 = { error: e_3_1 };
                        return [3 /*break*/, 7];
                    case 6:
                        try {
                            if (_b && !_b.done && (_c = _a.return))
                                _c.call(_a);
                        }
                        finally {
                            if (e_3)
                                throw e_3.error;
                        }
                        return [7 /*endfinally*/];
                    case 7: return [2 /*return*/];
                }
            });
        };
        VisualUniforms.prototype.update = function () { };
        return VisualUniforms;
    }());
    exports.VisualUniforms = VisualUniforms;
    VisualUniforms.__name__ = "VisualUniforms";
},
/* core/property_mixins.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var p = (0, tslib_1.__importStar)(require(133) /* ./properties */);
    var enums_1 = require(135) /* ./enums */;
    var k = (0, tslib_1.__importStar)(require(136) /* ./kinds */);
    var object_1 = require(128) /* ./util/object */;
    exports.Line = {
        line_color: [k.Nullable(k.Color), "black"],
        line_alpha: [k.Alpha, 1.0],
        line_width: [k.Number, 1],
        line_join: [enums_1.LineJoin, "bevel"],
        line_cap: [enums_1.LineCap, "butt"],
        line_dash: [k.Or(enums_1.LineDash, k.Array(k.Number)), []],
        line_dash_offset: [k.Number, 0],
    };
    exports.Fill = {
        fill_color: [k.Nullable(k.Color), "gray"],
        fill_alpha: [k.Alpha, 1.0],
    };
    exports.Hatch = {
        hatch_color: [k.Nullable(k.Color), "black"],
        hatch_alpha: [k.Alpha, 1.0],
        hatch_scale: [k.Number, 12.0],
        hatch_pattern: [k.Nullable(k.Or(enums_1.HatchPatternType, k.String)), null],
        hatch_weight: [k.Number, 1.0],
        hatch_extra: [k.Dict(k.AnyRef()), {}], // XXX: recursive imports
    };
    exports.Text = {
        text_color: [k.Nullable(k.Color), "#444444"],
        text_alpha: [k.Alpha, 1.0],
        text_font: [p.Font, "helvetica"],
        text_font_size: [k.FontSize, "16px"],
        text_font_style: [enums_1.FontStyle, "normal"],
        text_align: [enums_1.TextAlign, "left"],
        text_baseline: [enums_1.TextBaseline, "bottom"],
        text_line_height: [k.Number, 1.2],
    };
    exports.LineScalar = {
        line_color: [p.ColorScalar, "black"],
        line_alpha: [p.NumberScalar, 1.0],
        line_width: [p.NumberScalar, 1],
        line_join: [p.LineJoinScalar, "bevel"],
        line_cap: [p.LineCapScalar, "butt"],
        line_dash: [p.LineDashScalar, []],
        line_dash_offset: [p.NumberScalar, 0],
    };
    exports.FillScalar = {
        fill_color: [p.ColorScalar, "gray"],
        fill_alpha: [p.NumberScalar, 1.0],
    };
    exports.HatchScalar = {
        hatch_color: [p.ColorScalar, "black"],
        hatch_alpha: [p.NumberScalar, 1.0],
        hatch_scale: [p.NumberScalar, 12.0],
        hatch_pattern: [p.NullStringScalar, null],
        hatch_weight: [p.NumberScalar, 1.0],
        hatch_extra: [p.AnyScalar, {}],
    };
    exports.TextScalar = {
        text_color: [p.ColorScalar, "#444444"],
        text_alpha: [p.NumberScalar, 1.0],
        text_font: [p.FontScalar, "helvetica"],
        text_font_size: [p.FontSizeScalar, "16px"],
        text_font_style: [p.FontStyleScalar, "normal"],
        text_align: [p.TextAlignScalar, "left"],
        text_baseline: [p.TextBaselineScalar, "bottom"],
        text_line_height: [p.NumberScalar, 1.2],
    };
    exports.LineVector = {
        line_color: [p.ColorSpec, "black"],
        line_alpha: [p.NumberSpec, 1.0],
        line_width: [p.NumberSpec, 1],
        line_join: [p.LineJoinSpec, "bevel"],
        line_cap: [p.LineCapSpec, "butt"],
        line_dash: [p.LineDashSpec, []],
        line_dash_offset: [p.NumberSpec, 0],
    };
    exports.FillVector = {
        fill_color: [p.ColorSpec, "gray"],
        fill_alpha: [p.NumberSpec, 1.0],
    };
    exports.HatchVector = {
        hatch_color: [p.ColorSpec, "black"],
        hatch_alpha: [p.NumberSpec, 1.0],
        hatch_scale: [p.NumberSpec, 12.0],
        hatch_pattern: [p.NullStringSpec, null],
        hatch_weight: [p.NumberSpec, 1.0],
        hatch_extra: [p.AnyScalar, {}],
    };
    exports.TextVector = {
        text_color: [p.ColorSpec, "#444444"],
        text_alpha: [p.NumberSpec, 1.0],
        text_font: [p.FontSpec, "helvetica"],
        text_font_size: [p.FontSizeSpec, "16px"],
        text_font_style: [p.FontStyleSpec, "normal"],
        text_align: [p.TextAlignSpec, "left"],
        text_baseline: [p.TextBaselineSpec, "bottom"],
        text_line_height: [p.NumberSpec, 1.2],
    };
    function attrs_of(model, prefix, mixin, prefixed) {
        var e_1, _a;
        if (prefixed === void 0) {
            prefixed = false;
        }
        var attrs = {};
        try {
            for (var _b = (0, tslib_1.__values)((0, object_1.keys)(mixin)), _c = _b.next(); !_c.done; _c = _b.next()) {
                var attr = _c.value;
                var prefixed_attr = "" + prefix + attr;
                var value = model[prefixed_attr];
                attrs[prefixed ? prefixed_attr : attr] = value;
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return))
                    _a.call(_b);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return attrs;
    }
    exports.attrs_of = attrs_of;
},
/* core/visuals/fill.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var visual_1 = require(162) /* ./visual */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../property_mixins */);
    var color_1 = require(137) /* ../util/color */;
    var Fill = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Fill, _super);
        function Fill() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(Fill.prototype, "doit", {
            get: function () {
                var color = this.fill_color.get_value();
                var alpha = this.fill_alpha.get_value();
                return !(color == null || alpha == 0);
            },
            enumerable: false,
            configurable: true
        });
        Fill.prototype.apply = function (ctx, rule) {
            var doit = this.doit;
            if (doit) {
                this.set_value(ctx);
                ctx.fill(rule);
            }
            return doit;
        };
        Fill.prototype.values = function () {
            return {
                color: this.fill_color.get_value(),
                alpha: this.fill_alpha.get_value(),
            };
        };
        Fill.prototype.set_value = function (ctx) {
            var color = this.fill_color.get_value();
            var alpha = this.fill_alpha.get_value();
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        };
        return Fill;
    }(visual_1.VisualProperties));
    exports.Fill = Fill;
    Fill.__name__ = "Fill";
    var FillScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FillScalar, _super);
        function FillScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(FillScalar.prototype, "doit", {
            get: function () {
                var color = this.fill_color.value;
                var alpha = this.fill_alpha.value;
                return !(color == 0 || alpha == 0);
            },
            enumerable: false,
            configurable: true
        });
        FillScalar.prototype.apply = function (ctx, rule) {
            var doit = this.doit;
            if (doit) {
                this.set_value(ctx);
                ctx.fill(rule);
            }
            return doit;
        };
        FillScalar.prototype.values = function () {
            return {
                color: this.fill_color.value,
                alpha: this.fill_alpha.value,
            };
        };
        FillScalar.prototype.set_value = function (ctx) {
            var color = this.fill_color.value;
            var alpha = this.fill_alpha.value;
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        };
        return FillScalar;
    }(visual_1.VisualUniforms));
    exports.FillScalar = FillScalar;
    FillScalar.__name__ = "FillScalar";
    var FillVector = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FillVector, _super);
        function FillVector() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(FillVector.prototype, "doit", {
            get: function () {
                var fill_color = this.fill_color;
                if (fill_color.is_Scalar() && fill_color.value == 0)
                    return false;
                var fill_alpha = this.fill_alpha;
                if (fill_alpha.is_Scalar() && fill_alpha.value == 0)
                    return false;
                return true;
            },
            enumerable: false,
            configurable: true
        });
        FillVector.prototype.apply = function (ctx, i, rule) {
            var doit = this.doit;
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.fill(rule);
            }
            return doit;
        };
        FillVector.prototype.values = function (i) {
            return {
                color: this.fill_color.get(i),
                alpha: this.fill_alpha.get(i),
            };
        };
        FillVector.prototype.set_vectorize = function (ctx, i) {
            var color = this.fill_color.get(i);
            var alpha = this.fill_alpha.get(i);
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        };
        return FillVector;
    }(visual_1.VisualUniforms));
    exports.FillVector = FillVector;
    FillVector.__name__ = "FillVector";
    Fill.prototype.type = "fill";
    Fill.prototype.attrs = Object.keys(mixins.Fill);
    FillScalar.prototype.type = "fill";
    FillScalar.prototype.attrs = Object.keys(mixins.FillScalar);
    FillVector.prototype.type = "fill";
    FillVector.prototype.attrs = Object.keys(mixins.FillVector);
},
/* core/visuals/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var visual_1 = require(162) /* ./visual */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../property_mixins */);
    var color_1 = require(137) /* ../util/color */;
    var Text = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Text, _super);
        function Text() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(Text.prototype, "doit", {
            get: function () {
                var color = this.text_color.get_value();
                var alpha = this.text_alpha.get_value();
                return !(color == null || alpha == 0);
            },
            enumerable: false,
            configurable: true
        });
        Text.prototype.values = function () {
            return {
                color: this.text_color.get_value(),
                alpha: this.text_alpha.get_value(),
                font: this.text_font.get_value(),
                font_size: this.text_font_size.get_value(),
                font_style: this.text_font_style.get_value(),
                align: this.text_align.get_value(),
                baseline: this.text_baseline.get_value(),
                line_height: this.text_line_height.get_value(),
            };
        };
        Text.prototype.set_value = function (ctx) {
            var color = this.text_color.get_value();
            var alpha = this.text_alpha.get_value();
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.font = this.font_value();
            ctx.textAlign = this.text_align.get_value();
            ctx.textBaseline = this.text_baseline.get_value();
        };
        Text.prototype.font_value = function () {
            var style = this.text_font_style.get_value();
            var size = this.text_font_size.get_value();
            var face = this.text_font.get_value();
            return style + " " + size + " " + face;
        };
        return Text;
    }(visual_1.VisualProperties));
    exports.Text = Text;
    Text.__name__ = "Text";
    var TextScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextScalar, _super);
        function TextScalar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(TextScalar.prototype, "doit", {
            get: function () {
                var color = this.text_color.value;
                var alpha = this.text_alpha.value;
                return !(color == 0 || alpha == 0);
            },
            enumerable: false,
            configurable: true
        });
        TextScalar.prototype.values = function () {
            return {
                color: this.text_color.value,
                alpha: this.text_alpha.value,
                font: this.text_font.value,
                font_size: this.text_font_size.value,
                font_style: this.text_font_style.value,
                align: this.text_align.value,
                baseline: this.text_baseline.value,
                line_height: this.text_line_height.value,
            };
        };
        TextScalar.prototype.set_value = function (ctx) {
            var color = this.text_color.value;
            var alpha = this.text_alpha.value;
            var font = this.font_value();
            var align = this.text_align.value;
            var baseline = this.text_baseline.value;
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.font = font;
            ctx.textAlign = align;
            ctx.textBaseline = baseline;
        };
        TextScalar.prototype.font_value = function () {
            var style = this.text_font_style.value;
            var size = this.text_font_size.value;
            var face = this.text_font.value;
            return style + " " + size + " " + face;
        };
        return TextScalar;
    }(visual_1.VisualUniforms));
    exports.TextScalar = TextScalar;
    TextScalar.__name__ = "TextScalar";
    var TextVector = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextVector, _super);
        function TextVector() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TextVector.prototype.values = function (i) {
            return {
                color: this.text_color.get(i),
                alpha: this.text_alpha.get(i),
                font: this.text_font.get(i),
                font_size: this.text_font_size.get(i),
                font_style: this.text_font_style.get(i),
                align: this.text_align.get(i),
                baseline: this.text_baseline.get(i),
                line_height: this.text_line_height.get(i),
            };
        };
        Object.defineProperty(TextVector.prototype, "doit", {
            get: function () {
                var text_color = this.text_color;
                if (text_color.is_Scalar() && text_color.value == 0)
                    return false;
                var text_alpha = this.text_alpha;
                if (text_alpha.is_Scalar() && text_alpha.value == 0)
                    return false;
                return true;
            },
            enumerable: false,
            configurable: true
        });
        TextVector.prototype.set_vectorize = function (ctx, i) {
            var color = this.text_color.get(i);
            var alpha = this.text_alpha.get(i);
            var font = this.font_value(i);
            var align = this.text_align.get(i);
            var baseline = this.text_baseline.get(i);
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.font = font;
            ctx.textAlign = align;
            ctx.textBaseline = baseline;
        };
        TextVector.prototype.font_value = function (i) {
            var style = this.text_font_style.get(i);
            var size = this.text_font_size.get(i);
            var face = this.text_font.get(i);
            return style + " " + size + " " + face;
        };
        return TextVector;
    }(visual_1.VisualUniforms));
    exports.TextVector = TextVector;
    TextVector.__name__ = "TextVector";
    Text.prototype.type = "text";
    Text.prototype.attrs = Object.keys(mixins.Text);
    TextScalar.prototype.type = "text";
    TextScalar.prototype.attrs = Object.keys(mixins.TextScalar);
    TextVector.prototype.type = "text";
    TextVector.prototype.attrs = Object.keys(mixins.TextVector);
},
/* core/visuals/hatch.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var visual_1 = require(162) /* ./visual */;
    var patterns_1 = require(167) /* ./patterns */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../properties */);
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../property_mixins */);
    var Hatch = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Hatch, _super);
        function Hatch() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._update_iteration = 0;
            return _this;
        }
        Hatch.prototype.update = function () {
            var _this = this;
            this._update_iteration++;
            this._hatch_image = null;
            if (!this.doit)
                return;
            var color = this.hatch_color.get_value();
            var alpha = this.hatch_alpha.get_value();
            var scale = this.hatch_scale.get_value();
            var pattern = this.hatch_pattern.get_value();
            var weight = this.hatch_weight.get_value();
            var finalize = function (image) {
                _this._hatch_image = image;
            };
            var textures = this.hatch_extra.get_value();
            var texture = textures[pattern];
            if (texture != null) {
                var image = texture.get_pattern(color, alpha, scale, weight);
                if (image instanceof Promise) {
                    var _update_iteration_1 = this._update_iteration;
                    image.then(function (image) {
                        if (_this._update_iteration == _update_iteration_1) {
                            finalize(image);
                            _this.obj.request_render();
                        }
                    });
                }
                else {
                    finalize(image);
                }
            }
            else {
                var layer = this.obj.canvas.create_layer();
                var image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                finalize(image);
            }
        };
        Object.defineProperty(Hatch.prototype, "doit", {
            get: function () {
                var color = this.hatch_color.get_value();
                var alpha = this.hatch_alpha.get_value();
                var pattern = this.hatch_pattern.get_value();
                return !(color == null || alpha == 0 || pattern == " " || pattern == "blank" || pattern == null);
            },
            enumerable: false,
            configurable: true
        });
        Hatch.prototype.apply = function (ctx, rule) {
            var doit = this.doit;
            if (doit) {
                this.set_value(ctx);
                ctx.layer.undo_transform(function () { return ctx.fill(rule); });
            }
            return doit;
        };
        Hatch.prototype.set_value = function (ctx) {
            var pattern = this.pattern(ctx);
            ctx.fillStyle = pattern !== null && pattern !== void 0 ? pattern : "transparent";
        };
        Hatch.prototype.pattern = function (ctx) {
            var image = this._hatch_image;
            if (image == null)
                return null;
            else
                return ctx.createPattern(image, this.repetition());
        };
        Hatch.prototype.repetition = function () {
            var pattern = this.hatch_pattern.get_value();
            var texture = this.hatch_extra.get_value()[pattern];
            if (texture == null)
                return "repeat";
            else {
                switch (texture.repetition) {
                    case "repeat": return "repeat";
                    case "repeat_x": return "repeat-x";
                    case "repeat_y": return "repeat-y";
                    case "no_repeat": return "no-repeat";
                }
            }
        };
        return Hatch;
    }(visual_1.VisualProperties));
    exports.Hatch = Hatch;
    Hatch.__name__ = "Hatch";
    var HatchScalar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HatchScalar, _super);
        function HatchScalar() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._static_doit = false;
            _this._update_iteration = 0;
            return _this;
        }
        HatchScalar.prototype._compute_static_doit = function () {
            var color = this.hatch_color.value;
            var alpha = this.hatch_alpha.value;
            var pattern = this.hatch_pattern.value;
            return !(color == null || alpha == 0 || pattern == " " || pattern == "blank" || pattern == null);
        };
        HatchScalar.prototype.update = function () {
            var _this = this;
            this._update_iteration++;
            var n = this.hatch_color.length;
            this._hatch_image = new p.UniformScalar(null, n);
            this._static_doit = this._compute_static_doit();
            if (!this._static_doit)
                return;
            var color = this.hatch_color.value;
            var alpha = this.hatch_alpha.value;
            var scale = this.hatch_scale.value;
            var pattern = this.hatch_pattern.value;
            var weight = this.hatch_weight.value;
            var finalize = function (image) {
                _this._hatch_image = new p.UniformScalar(image, n);
            };
            var textures = this.hatch_extra.value;
            var texture = textures[pattern];
            if (texture != null) {
                var image = texture.get_pattern(color, alpha, scale, weight);
                if (image instanceof Promise) {
                    var _update_iteration_2 = this._update_iteration;
                    image.then(function (image) {
                        if (_this._update_iteration == _update_iteration_2) {
                            finalize(image);
                            _this.obj.request_render();
                        }
                    });
                }
                else {
                    finalize(image);
                }
            }
            else {
                var layer = this.obj.canvas.create_layer();
                var image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                finalize(image);
            }
        };
        Object.defineProperty(HatchScalar.prototype, "doit", {
            get: function () {
                return this._static_doit;
            },
            enumerable: false,
            configurable: true
        });
        HatchScalar.prototype.apply = function (ctx, rule) {
            var doit = this.doit;
            if (doit) {
                this.set_value(ctx);
                ctx.layer.undo_transform(function () { return ctx.fill(rule); });
            }
            return doit;
        };
        HatchScalar.prototype.set_value = function (ctx) {
            var _a;
            ctx.fillStyle = (_a = this.pattern(ctx)) !== null && _a !== void 0 ? _a : "transparent";
        };
        HatchScalar.prototype.pattern = function (ctx) {
            var image = this._hatch_image.value;
            if (image == null)
                return null;
            else
                return ctx.createPattern(image, this.repetition());
        };
        HatchScalar.prototype.repetition = function () {
            var pattern = this.hatch_pattern.value;
            var texture = this.hatch_extra.value[pattern];
            if (texture == null)
                return "repeat";
            else {
                switch (texture.repetition) {
                    case "repeat": return "repeat";
                    case "repeat_x": return "repeat-x";
                    case "repeat_y": return "repeat-y";
                    case "no_repeat": return "no-repeat";
                }
            }
        };
        return HatchScalar;
    }(visual_1.VisualUniforms));
    exports.HatchScalar = HatchScalar;
    HatchScalar.__name__ = "HatchScalar";
    var HatchVector = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HatchVector, _super);
        function HatchVector() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._static_doit = false;
            _this._update_iteration = 0;
            return _this;
        }
        HatchVector.prototype._compute_static_doit = function () {
            var hatch_color = this.hatch_color;
            if (hatch_color.is_Scalar() && hatch_color.value == 0)
                return false;
            var hatch_alpha = this.hatch_alpha;
            if (hatch_alpha.is_Scalar() && hatch_alpha.value == 0)
                return false;
            var hatch_pattern = this.hatch_pattern;
            if (hatch_pattern.is_Scalar()) {
                var pattern = hatch_pattern.value;
                if (pattern == " " || pattern == "blank" || pattern == null)
                    return false;
            }
            return true;
        };
        HatchVector.prototype.update = function () {
            var _this = this;
            this._update_iteration++;
            var n = this.hatch_color.length;
            this._hatch_image = new p.UniformScalar(null, n);
            this._static_doit = this._compute_static_doit();
            if (!this._static_doit)
                return;
            var resolve_image = function (pattern, color, alpha, scale, weight, finalize) {
                var textures = _this.hatch_extra.value;
                var texture = textures[pattern];
                if (texture != null) {
                    var image = texture.get_pattern(color, alpha, scale, weight);
                    if (image instanceof Promise) {
                        var _update_iteration_3 = _this._update_iteration;
                        image.then(function (image) {
                            if (_this._update_iteration == _update_iteration_3) {
                                finalize(image);
                                _this.obj.request_render();
                            }
                        });
                    }
                    else {
                        finalize(image);
                    }
                }
                else {
                    var layer = _this.obj.canvas.create_layer();
                    var image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                    finalize(image);
                }
            };
            if (this.hatch_color.is_Scalar() &&
                this.hatch_alpha.is_Scalar() &&
                this.hatch_scale.is_Scalar() &&
                this.hatch_pattern.is_Scalar() &&
                this.hatch_weight.is_Scalar()) {
                var color = this.hatch_color.value;
                var alpha = this.hatch_alpha.value;
                var scale = this.hatch_scale.value;
                var pattern = this.hatch_pattern.value;
                var weight = this.hatch_weight.value;
                resolve_image(pattern, color, alpha, scale, weight, function (image) {
                    _this._hatch_image = new p.UniformScalar(image, n);
                });
            }
            else {
                var images_1 = new Array(n);
                images_1.fill(null);
                this._hatch_image = new p.UniformVector(images_1);
                var _loop_1 = function (i) {
                    var color = this_1.hatch_color.get(i);
                    var alpha = this_1.hatch_alpha.get(i);
                    var scale = this_1.hatch_scale.get(i);
                    var pattern = this_1.hatch_pattern.get(i);
                    var weight = this_1.hatch_weight.get(i);
                    resolve_image(pattern, color, alpha, scale, weight, function (image) {
                        images_1[i] = image;
                    });
                };
                var this_1 = this;
                for (var i = 0; i < n; i++) {
                    _loop_1(i);
                }
            }
        };
        Object.defineProperty(HatchVector.prototype, "doit", {
            get: function () {
                return this._static_doit;
            },
            enumerable: false,
            configurable: true
        });
        HatchVector.prototype.apply = function (ctx, i, rule) {
            var doit = this.doit;
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.layer.undo_transform(function () { return ctx.fill(rule); });
            }
            return doit;
        };
        HatchVector.prototype.set_vectorize = function (ctx, i) {
            var _a;
            ctx.fillStyle = (_a = this.pattern(ctx, i)) !== null && _a !== void 0 ? _a : "transparent";
        };
        HatchVector.prototype.pattern = function (ctx, i) {
            var image = this._hatch_image.get(i);
            if (image == null)
                return null;
            else
                return ctx.createPattern(image, this.repetition(i));
        };
        HatchVector.prototype.repetition = function (i) {
            var pattern = this.hatch_pattern.get(i);
            var texture = this.hatch_extra.value[pattern];
            if (texture == null)
                return "repeat";
            else {
                switch (texture.repetition) {
                    case "repeat": return "repeat";
                    case "repeat_x": return "repeat-x";
                    case "repeat_y": return "repeat-y";
                    case "no_repeat": return "no-repeat";
                }
            }
        };
        return HatchVector;
    }(visual_1.VisualUniforms));
    exports.HatchVector = HatchVector;
    HatchVector.__name__ = "HatchVector";
    Hatch.prototype.type = "hatch";
    Hatch.prototype.attrs = Object.keys(mixins.Hatch);
    HatchScalar.prototype.type = "hatch";
    HatchScalar.prototype.attrs = Object.keys(mixins.HatchScalar);
    HatchVector.prototype.type = "hatch";
    HatchVector.prototype.attrs = Object.keys(mixins.HatchVector);
},
/* core/visuals/patterns.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var color_1 = require(137) /* ../util/color */;
    function _horz(ctx, h, h2) {
        ctx.moveTo(0, h2 + 0.5);
        ctx.lineTo(h, h2 + 0.5);
        ctx.stroke();
    }
    function _vert(ctx, h, h2) {
        ctx.moveTo(h2 + 0.5, 0);
        ctx.lineTo(h2 + 0.5, h);
        ctx.stroke();
    }
    function _x(ctx, h) {
        ctx.moveTo(0, h);
        ctx.lineTo(h, 0);
        ctx.stroke();
        ctx.moveTo(0, 0);
        ctx.lineTo(h, h);
        ctx.stroke();
    }
    exports.hatch_aliases = {
        " ": "blank",
        ".": "dot",
        o: "ring",
        "-": "horizontal_line",
        "|": "vertical_line",
        "+": "cross",
        "\"": "horizontal_dash",
        ":": "vertical_dash",
        "@": "spiral",
        "/": "right_diagonal_line",
        "\\": "left_diagonal_line",
        x: "diagonal_cross",
        ",": "right_diagonal_dash",
        "`": "left_diagonal_dash",
        v: "horizontal_wave",
        ">": "vertical_wave",
        "*": "criss_cross",
    };
    function get_pattern(layer, pattern, color, alpha, scale, weight) {
        layer.resize(scale, scale);
        layer.prepare();
        create_hatch_canvas(layer.ctx, pattern, color, alpha, scale, weight);
        return layer.canvas;
    }
    exports.get_pattern = get_pattern;
    function create_hatch_canvas(ctx, hatch_pattern, hatch_color, hatch_alpha, hatch_scale, hatch_weight) {
        var _a;
        var h = hatch_scale;
        var h2 = h / 2;
        var h4 = h2 / 2;
        var color = (0, color_1.color2css)(hatch_color, hatch_alpha);
        ctx.strokeStyle = color;
        ctx.fillStyle = color;
        ctx.lineCap = "square";
        ctx.lineWidth = hatch_weight;
        switch ((_a = exports.hatch_aliases[hatch_pattern]) !== null && _a !== void 0 ? _a : hatch_pattern) {
            // we should not need these if code conditions on hatch.doit, but
            // include them here just for completeness
            case "blank":
                break;
            case "dot":
                ctx.arc(h2, h2, h2 / 2, 0, 2 * Math.PI, true);
                ctx.fill();
                break;
            case "ring":
                ctx.arc(h2, h2, h2 / 2, 0, 2 * Math.PI, true);
                ctx.stroke();
                break;
            case "horizontal_line":
                _horz(ctx, h, h2);
                break;
            case "vertical_line":
                _vert(ctx, h, h2);
                break;
            case "cross":
                _horz(ctx, h, h2);
                _vert(ctx, h, h2);
                break;
            case "horizontal_dash":
                _horz(ctx, h2, h2);
                break;
            case "vertical_dash":
                _vert(ctx, h2, h2);
                break;
            case "spiral": {
                var h30 = h / 30;
                ctx.moveTo(h2, h2);
                for (var i = 0; i < 360; i++) {
                    var angle = 0.1 * i;
                    var x = h2 + (h30 * angle) * Math.cos(angle);
                    var y = h2 + (h30 * angle) * Math.sin(angle);
                    ctx.lineTo(x, y);
                }
                ctx.stroke();
                break;
            }
            case "right_diagonal_line":
                ctx.moveTo(-h4 + 0.5, h);
                ctx.lineTo(h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(h4 + 0.5, h);
                ctx.lineTo(3 * h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(3 * h4 + 0.5, h);
                ctx.lineTo(5 * h4 + 0.5, 0);
                ctx.stroke();
                ctx.stroke();
                break;
            case "left_diagonal_line":
                ctx.moveTo(h4 + 0.5, h);
                ctx.lineTo(-h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(3 * h4 + 0.5, h);
                ctx.lineTo(h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(5 * h4 + 0.5, h);
                ctx.lineTo(3 * h4 + 0.5, 0);
                ctx.stroke();
                ctx.stroke();
                break;
            case "diagonal_cross":
                _x(ctx, h);
                break;
            case "right_diagonal_dash":
                ctx.moveTo(h4 + 0.5, 3 * h4 + 0.5);
                ctx.lineTo(3 * h4 + 0.5, h4 + 0.5);
                ctx.stroke();
                break;
            case "left_diagonal_dash":
                ctx.moveTo(h4 + 0.5, h4 + 0.5);
                ctx.lineTo(3 * h4 + 0.5, 3 * h4 + 0.5);
                ctx.stroke();
                break;
            case "horizontal_wave":
                ctx.moveTo(0, h4);
                ctx.lineTo(h2, 3 * h4);
                ctx.lineTo(h, h4);
                ctx.stroke();
                break;
            case "vertical_wave":
                ctx.moveTo(h4, 0);
                ctx.lineTo(3 * h4, h2);
                ctx.lineTo(h4, h);
                ctx.stroke();
                break;
            case "criss_cross":
                _x(ctx, h);
                _horz(ctx, h, h2);
                _vert(ctx, h, h2);
                break;
        }
    }
},
/* model.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var has_props_1 = require(129) /* ./core/has_props */;
    var types_1 = require(125) /* ./core/util/types */;
    var object_1 = require(128) /* ./core/util/object */;
    var eq_1 = require(141) /* ./core/util/eq */;
    var logging_1 = require(134) /* ./core/logging */;
    var Model = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Model, _super);
        function Model(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(Model.prototype, "is_syncable", {
            get: function () {
                return this.syncable;
            },
            enumerable: false,
            configurable: true
        });
        Model.prototype[eq_1.equals] = function (that, cmp) {
            return cmp.eq(this.id, that.id) && _super.prototype[eq_1.equals].call(this, that, cmp);
        };
        Model.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._js_callbacks = new Map();
        };
        Model.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this._update_property_callbacks();
            this.connect(this.properties.js_property_callbacks.change, function () { return _this._update_property_callbacks(); });
            this.connect(this.properties.js_event_callbacks.change, function () { return _this._update_event_callbacks(); });
            this.connect(this.properties.subscribed_events.change, function () { return _this._update_event_callbacks(); });
        };
        /*protected*/ Model.prototype._process_event = function (event) {
            var e_1, _b;
            var _c;
            try {
                for (var _d = (0, tslib_1.__values)((_c = this.js_event_callbacks[event.event_name]) !== null && _c !== void 0 ? _c : []), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var callback = _e.value;
                    callback.execute(event);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            if (this.document != null && this.subscribed_events.some(function (m) { return m == event.event_name; }))
                this.document.event_manager.send_event(event);
        };
        Model.prototype.trigger_event = function (event) {
            if (this.document != null) {
                event.origin = this;
                this.document.event_manager.trigger(event);
            }
        };
        Model.prototype._update_event_callbacks = function () {
            if (this.document == null) {
                logging_1.logger.warn("WARNING: Document not defined for updating event callbacks");
                return;
            }
            this.document.event_manager.subscribed_models.add(this);
        };
        Model.prototype._update_property_callbacks = function () {
            var e_2, _b, e_3, _c, e_4, _d, e_5, _e;
            var _this = this;
            var signal_for = function (event) {
                var _b = (0, tslib_1.__read)(event.split(":"), 2), evt = _b[0], _c = _b[1], attr = _c === void 0 ? null : _c;
                return attr != null ? _this.properties[attr][evt] : _this[evt];
            };
            try {
                for (var _f = (0, tslib_1.__values)(this._js_callbacks), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var _h = (0, tslib_1.__read)(_g.value, 2), event = _h[0], callbacks = _h[1];
                    var signal = signal_for(event);
                    try {
                        for (var callbacks_1 = (e_3 = void 0, (0, tslib_1.__values)(callbacks)), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {
                            var cb = callbacks_1_1.value;
                            this.disconnect(signal, cb);
                        }
                    }
                    catch (e_3_1) {
                        e_3 = { error: e_3_1 };
                    }
                    finally {
                        try {
                            if (callbacks_1_1 && !callbacks_1_1.done && (_c = callbacks_1.return))
                                _c.call(callbacks_1);
                        }
                        finally {
                            if (e_3)
                                throw e_3.error;
                        }
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_b = _f.return))
                        _b.call(_f);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            this._js_callbacks.clear();
            try {
                for (var _j = (0, tslib_1.__values)((0, object_1.entries)(this.js_property_callbacks)), _k = _j.next(); !_k.done; _k = _j.next()) {
                    var _l = (0, tslib_1.__read)(_k.value, 2), event = _l[0], callbacks = _l[1];
                    var wrappers = callbacks.map(function (cb) { return function () { return cb.execute(_this); }; });
                    this._js_callbacks.set(event, wrappers);
                    var signal = signal_for(event);
                    try {
                        for (var wrappers_1 = (e_5 = void 0, (0, tslib_1.__values)(wrappers)), wrappers_1_1 = wrappers_1.next(); !wrappers_1_1.done; wrappers_1_1 = wrappers_1.next()) {
                            var cb = wrappers_1_1.value;
                            this.connect(signal, cb);
                        }
                    }
                    catch (e_5_1) {
                        e_5 = { error: e_5_1 };
                    }
                    finally {
                        try {
                            if (wrappers_1_1 && !wrappers_1_1.done && (_e = wrappers_1.return))
                                _e.call(wrappers_1);
                        }
                        finally {
                            if (e_5)
                                throw e_5.error;
                        }
                    }
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_k && !_k.done && (_d = _j.return))
                        _d.call(_j);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
        };
        Model.prototype._doc_attached = function () {
            if (!(0, object_1.isEmpty)(this.js_event_callbacks) || this.subscribed_events.length != 0)
                this._update_event_callbacks();
        };
        Model.prototype._doc_detached = function () {
            this.document.event_manager.subscribed_models.delete(this);
        };
        Model.prototype.select = function (selector) {
            if ((0, types_1.isString)(selector))
                return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.references()), false).filter(function (ref) { return ref instanceof Model && ref.name === selector; });
            else if (selector.prototype instanceof has_props_1.HasProps)
                return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.references()), false).filter(function (ref) { return ref instanceof selector; });
            else
                throw new Error("invalid selector");
        };
        Model.prototype.select_one = function (selector) {
            var result = this.select(selector);
            switch (result.length) {
                case 0:
                    return null;
                case 1:
                    return result[0];
                default:
                    throw new Error("found more than one object matching given selector");
            }
        };
        return Model;
    }(has_props_1.HasProps));
    exports.Model = Model;
    _a = Model;
    Model.__name__ = "Model";
    (function () {
        _a.define(function (_b) {
            var Any = _b.Any, Unknown = _b.Unknown, Boolean = _b.Boolean, String = _b.String, Array = _b.Array, Dict = _b.Dict, Nullable = _b.Nullable;
            return ({
                tags: [Array(Unknown), []],
                name: [Nullable(String), null],
                js_property_callbacks: [Dict(Array(Any /*TODO*/)), {}],
                js_event_callbacks: [Dict(Array(Any /*TODO*/)), {}],
                subscribed_events: [Array(String), []],
                syncable: [Boolean, true],
            });
        });
    })();
},
/* models/canvas/coordinates.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var model_1 = require(168) /* ../../model */;
    var scale_1 = require(170) /* ../scales/scale */;
    var linear_scale_1 = require(174) /* ../scales/linear_scale */;
    var log_scale_1 = require(176) /* ../scales/log_scale */;
    var categorical_scale_1 = require(177) /* ../scales/categorical_scale */;
    var range_1 = require(172) /* ../ranges/range */;
    var data_range1d_1 = require(178) /* ../ranges/data_range1d */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var CoordinateTransform = /** @class */ (function () {
        function CoordinateTransform(x_scale, y_scale) {
            this.x_scale = x_scale;
            this.y_scale = y_scale;
            this.x_source = this.x_scale.source_range;
            this.y_source = this.y_scale.source_range;
            this.ranges = [this.x_source, this.y_source];
            this.scales = [this.x_scale, this.y_scale];
        }
        CoordinateTransform.prototype.map_to_screen = function (xs, ys) {
            var sxs = this.x_scale.v_compute(xs);
            var sys = this.y_scale.v_compute(ys);
            return [sxs, sys];
        };
        CoordinateTransform.prototype.map_from_screen = function (sxs, sys) {
            var xs = this.x_scale.v_invert(sxs);
            var ys = this.y_scale.v_invert(sys);
            return [xs, ys];
        };
        return CoordinateTransform;
    }());
    exports.CoordinateTransform = CoordinateTransform;
    CoordinateTransform.__name__ = "CoordinateTransform";
    var CoordinateMapping = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CoordinateMapping, _super);
        function CoordinateMapping(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CoordinateMapping.prototype, "x_ranges", {
            get: function () {
                return new Map([["default", this.x_source]]);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CoordinateMapping.prototype, "y_ranges", {
            get: function () {
                return new Map([["default", this.y_source]]);
            },
            enumerable: false,
            configurable: true
        });
        CoordinateMapping.prototype._get_scale = function (range, scale, target) {
            var factor_range = range instanceof factor_range_1.FactorRange;
            var categorical_scale = scale instanceof categorical_scale_1.CategoricalScale;
            if (factor_range != categorical_scale) {
                throw new Error("Range " + range.type + " is incompatible is Scale " + scale.type);
            }
            if (scale instanceof log_scale_1.LogScale && range instanceof data_range1d_1.DataRange1d)
                range.scale_hint = "log";
            var derived_scale = scale.clone();
            derived_scale.setv({ source_range: range, target_range: target });
            return derived_scale;
        };
        CoordinateMapping.prototype.get_transform = function (frame) {
            var _c = this, x_source = _c.x_source, x_scale = _c.x_scale, x_target = _c.x_target;
            var x_source_scale = this._get_scale(x_source, x_scale, x_target);
            var _d = this, y_source = _d.y_source, y_scale = _d.y_scale, y_target = _d.y_target;
            var y_source_scale = this._get_scale(y_source, y_scale, y_target);
            var xscale = new CompositeScale({
                source_scale: x_source_scale, source_range: x_source_scale.source_range,
                target_scale: frame.x_scale, target_range: frame.x_target,
            });
            var yscale = new CompositeScale({
                source_scale: y_source_scale, source_range: y_source_scale.source_range,
                target_scale: frame.y_scale, target_range: frame.y_target,
            });
            return new CoordinateTransform(xscale, yscale);
        };
        return CoordinateMapping;
    }(model_1.Model));
    exports.CoordinateMapping = CoordinateMapping;
    _a = CoordinateMapping;
    CoordinateMapping.__name__ = "CoordinateMapping";
    (function () {
        _a.define(function (_c) {
            var Ref = _c.Ref;
            return ({
                x_source: [Ref(range_1.Range), function () { return new data_range1d_1.DataRange1d(); }],
                y_source: [Ref(range_1.Range), function () { return new data_range1d_1.DataRange1d(); }],
                x_scale: [Ref(scale_1.Scale), function () { return new linear_scale_1.LinearScale(); }],
                y_scale: [Ref(scale_1.Scale), function () { return new linear_scale_1.LinearScale(); }],
                x_target: [Ref(range_1.Range)],
                y_target: [Ref(range_1.Range)],
            });
        });
    })();
    var CompositeScale = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CompositeScale, _super);
        function CompositeScale(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CompositeScale.prototype, "s_compute", {
            get: function () {
                var source_compute = this.source_scale.s_compute;
                var target_compute = this.target_scale.s_compute;
                return function (x) { return target_compute(source_compute(x)); };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CompositeScale.prototype, "s_invert", {
            get: function () {
                var source_invert = this.source_scale.s_invert;
                var target_invert = this.target_scale.s_invert;
                return function (sx) { return source_invert(target_invert(sx)); };
            },
            enumerable: false,
            configurable: true
        });
        CompositeScale.prototype.compute = function (x) {
            return this.s_compute(x);
        };
        CompositeScale.prototype.v_compute = function (xs) {
            var s_compute = this.s_compute;
            return (0, arrayable_1.map)(xs, s_compute); // XXX
        };
        CompositeScale.prototype.invert = function (sx) {
            return this.s_invert(sx);
        };
        CompositeScale.prototype.v_invert = function (sxs) {
            var s_invert = this.s_invert;
            return (0, arrayable_1.map)(sxs, s_invert); // XXX
        };
        return CompositeScale;
    }(scale_1.Scale));
    exports.CompositeScale = CompositeScale;
    _b = CompositeScale;
    CompositeScale.__name__ = "CompositeScale";
    (function () {
        _b.internal(function (_c) {
            var Ref = _c.Ref;
            return ({
                source_scale: [Ref(scale_1.Scale)],
                target_scale: [Ref(scale_1.Scale)],
            });
        });
    })();
},
/* models/scales/scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var transform_1 = require(171) /* ../transforms/transform */;
    var range_1 = require(172) /* ../ranges/range */;
    var range1d_1 = require(173) /* ../ranges/range1d */;
    var types_1 = require(139) /* ../../core/types */;
    var Scale = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Scale, _super);
        function Scale(attrs) {
            return _super.call(this, attrs) || this;
        }
        Scale.prototype.compute = function (x) {
            return this.s_compute(x);
        };
        Scale.prototype.v_compute = function (xs) {
            var result = new types_1.ScreenArray(xs.length);
            var s_compute = this.s_compute;
            for (var i = 0; i < xs.length; i++) {
                result[i] = s_compute(xs[i]);
            }
            return result;
        };
        Scale.prototype.invert = function (sx) {
            return this.s_invert(sx);
        };
        Scale.prototype.v_invert = function (sxs) {
            var result = new Float64Array(sxs.length);
            var s_invert = this.s_invert;
            for (var i = 0; i < sxs.length; i++) {
                result[i] = s_invert(sxs[i]);
            }
            return result;
        };
        Scale.prototype.r_compute = function (x0, x1) {
            var s_compute = this.s_compute;
            if (this.target_range.is_reversed)
                return [s_compute(x1), s_compute(x0)];
            else
                return [s_compute(x0), s_compute(x1)];
        };
        Scale.prototype.r_invert = function (sx0, sx1) {
            var s_invert = this.s_invert;
            if (this.target_range.is_reversed)
                return [s_invert(sx1), s_invert(sx0)];
            else
                return [s_invert(sx0), s_invert(sx1)];
        };
        return Scale;
    }(transform_1.Transform));
    exports.Scale = Scale;
    _a = Scale;
    Scale.__name__ = "Scale";
    (function () {
        _a.internal(function (_b) {
            var Ref = _b.Ref;
            return ({
                source_range: [Ref(range_1.Range)],
                target_range: [Ref(range1d_1.Range1d)],
            });
        });
    })();
},
/* models/transforms/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../../model */;
    var Transform = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Transform, _super);
        function Transform(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Transform;
    }(model_1.Model));
    exports.Transform = Transform;
    Transform.__name__ = "Transform";
},
/* models/ranges/range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var Range = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Range, _super);
        function Range(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.have_updated_interactively = false;
            return _this;
        }
        Object.defineProperty(Range.prototype, "is_reversed", {
            get: function () {
                return this.start > this.end;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Range.prototype, "is_valid", {
            get: function () {
                return isFinite(this.min) && isFinite(this.max);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Range.prototype, "span", {
            get: function () {
                return Math.abs(this.end - this.start);
            },
            enumerable: false,
            configurable: true
        });
        return Range;
    }(model_1.Model));
    exports.Range = Range;
    _a = Range;
    Range.__name__ = "Range";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Tuple = _b.Tuple, Or = _b.Or, Auto = _b.Auto, Nullable = _b.Nullable;
            return ({
                bounds: [Nullable(Or(Tuple(Nullable(Number), Nullable(Number)), Auto)), null],
                min_interval: [Nullable(Number), null],
                max_interval: [Nullable(Number), null],
            });
        });
        _a.internal(function (_b) {
            var Array = _b.Array, AnyRef = _b.AnyRef;
            return ({
                plots: [Array(AnyRef()), []],
            });
        });
    })();
},
/* models/ranges/range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var range_1 = require(172) /* ./range */;
    var Range1d = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Range1d, _super);
        function Range1d(attrs) {
            return _super.call(this, attrs) || this;
        }
        Range1d.prototype._set_auto_bounds = function () {
            if (this.bounds == "auto") {
                var min = Math.min(this._reset_start, this._reset_end);
                var max = Math.max(this._reset_start, this._reset_end);
                this.setv({ bounds: [min, max] }, { silent: true });
            }
        };
        Range1d.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._set_auto_bounds();
        };
        Object.defineProperty(Range1d.prototype, "min", {
            get: function () {
                return Math.min(this.start, this.end);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Range1d.prototype, "max", {
            get: function () {
                return Math.max(this.start, this.end);
            },
            enumerable: false,
            configurable: true
        });
        Range1d.prototype.reset = function () {
            this._set_auto_bounds();
            var _b = this, _reset_start = _b._reset_start, _reset_end = _b._reset_end;
            if (this.start != _reset_start || this.end != _reset_end)
                this.setv({ start: _reset_start, end: _reset_end });
            else
                this.change.emit();
        };
        Range1d.prototype.map = function (fn) {
            return new Range1d({ start: fn(this.start), end: fn(this.end) });
        };
        Range1d.prototype.widen = function (v) {
            var _b = this, start = _b.start, end = _b.end;
            if (this.is_reversed) {
                start += v;
                end -= v;
            }
            else {
                start -= v;
                end += v;
            }
            return new Range1d({ start: start, end: end });
        };
        return Range1d;
    }(range_1.Range));
    exports.Range1d = Range1d;
    _a = Range1d;
    Range1d.__name__ = "Range1d";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Nullable = _b.Nullable;
            return ({
                start: [Number, 0],
                end: [Number, 1],
                reset_start: [Nullable(Number), null, {
                        on_update: function (reset_start, self) {
                            self._reset_start = reset_start !== null && reset_start !== void 0 ? reset_start : self.start;
                        },
                    }],
                reset_end: [Nullable(Number), null, {
                        on_update: function (reset_end, self) {
                            self._reset_end = reset_end !== null && reset_end !== void 0 ? reset_end : self.end;
                        },
                    }],
            });
        });
    })();
},
/* models/scales/linear_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var continuous_scale_1 = require(175) /* ./continuous_scale */;
    var LinearScale = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LinearScale, _super);
        function LinearScale(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(LinearScale.prototype, "s_compute", {
            get: function () {
                var _a = (0, tslib_1.__read)(this._linear_compute_state(), 2), factor = _a[0], offset = _a[1];
                return function (x) { return factor * x + offset; };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LinearScale.prototype, "s_invert", {
            get: function () {
                var _a = (0, tslib_1.__read)(this._linear_compute_state(), 2), factor = _a[0], offset = _a[1];
                return function (sx) { return (sx - offset) / factor; };
            },
            enumerable: false,
            configurable: true
        });
        /*protected*/ LinearScale.prototype._linear_compute_state = function () {
            //
            //  (t1 - t0)       (t1 - t0)
            //  --------- * x - --------- * s0 + t0
            //  (s1 - s0)       (s1 - s0)
            //
            // [  factor  ]     [    offset    ]
            //
            var source_start = this.source_range.start;
            var source_end = this.source_range.end;
            var target_start = this.target_range.start;
            var target_end = this.target_range.end;
            var factor = (target_end - target_start) / (source_end - source_start);
            var offset = -(factor * source_start) + target_start;
            return [factor, offset];
        };
        return LinearScale;
    }(continuous_scale_1.ContinuousScale));
    exports.LinearScale = LinearScale;
    LinearScale.__name__ = "LinearScale";
},
/* models/scales/continuous_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var scale_1 = require(170) /* ./scale */;
    var ContinuousScale = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ContinuousScale, _super);
        function ContinuousScale(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ContinuousScale;
    }(scale_1.Scale));
    exports.ContinuousScale = ContinuousScale;
    ContinuousScale.__name__ = "ContinuousScale";
},
/* models/scales/log_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var continuous_scale_1 = require(175) /* ./continuous_scale */;
    var LogScale = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LogScale, _super);
        function LogScale(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(LogScale.prototype, "s_compute", {
            get: function () {
                var _a = (0, tslib_1.__read)(this._compute_state(), 4), factor = _a[0], offset = _a[1], inter_factor = _a[2], inter_offset = _a[3];
                return function (x) {
                    if (inter_factor == 0)
                        return 0;
                    else {
                        var _x = (Math.log(x) - inter_offset) / inter_factor;
                        return isFinite(_x) ? _x * factor + offset : NaN;
                    }
                };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LogScale.prototype, "s_invert", {
            get: function () {
                var _a = (0, tslib_1.__read)(this._compute_state(), 4), factor = _a[0], offset = _a[1], inter_factor = _a[2], inter_offset = _a[3];
                return function (xprime) {
                    var value = (xprime - offset) / factor;
                    return Math.exp(inter_factor * value + inter_offset);
                };
            },
            enumerable: false,
            configurable: true
        });
        LogScale.prototype._get_safe_factor = function (orig_start, orig_end) {
            var _a;
            var start = orig_start < 0 ? 0 : orig_start;
            var end = orig_end < 0 ? 0 : orig_end;
            if (start == end) {
                if (start == 0)
                    _a = (0, tslib_1.__read)([1, 10], 2), start = _a[0], end = _a[1];
                else {
                    var log_val = Math.log(start) / Math.log(10);
                    start = Math.pow(10, Math.floor(log_val));
                    if (Math.ceil(log_val) != Math.floor(log_val))
                        end = Math.pow(10, Math.ceil(log_val));
                    else
                        end = Math.pow(10, (Math.ceil(log_val) + 1));
                }
            }
            return [start, end];
        };
        /*protected*/ LogScale.prototype._compute_state = function () {
            var source_start = this.source_range.start;
            var source_end = this.source_range.end;
            var target_start = this.target_range.start;
            var target_end = this.target_range.end;
            var screen_range = target_end - target_start;
            var _a = (0, tslib_1.__read)(this._get_safe_factor(source_start, source_end), 2), start = _a[0], end = _a[1];
            var inter_factor;
            var inter_offset;
            if (start == 0) {
                inter_factor = Math.log(end);
                inter_offset = 0;
            }
            else {
                inter_factor = Math.log(end) - Math.log(start);
                inter_offset = Math.log(start);
            }
            var factor = screen_range;
            var offset = target_start;
            return [factor, offset, inter_factor, inter_offset];
        };
        return LogScale;
    }(continuous_scale_1.ContinuousScale));
    exports.LogScale = LogScale;
    LogScale.__name__ = "LogScale";
},
/* models/scales/categorical_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var scale_1 = require(170) /* ./scale */;
    var linear_scale_1 = require(174) /* ./linear_scale */;
    var _linear_compute_state = linear_scale_1.LinearScale.prototype._linear_compute_state;
    var CategoricalScale = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CategoricalScale, _super);
        function CategoricalScale(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CategoricalScale.prototype, "s_compute", {
            get: function () {
                var _a = (0, tslib_1.__read)(_linear_compute_state.call(this), 2), factor = _a[0], offset = _a[1];
                var range = this.source_range;
                return function (x) { return factor * range.synthetic(x) + offset; };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CategoricalScale.prototype, "s_invert", {
            get: function () {
                var _a = (0, tslib_1.__read)(_linear_compute_state.call(this), 2), factor = _a[0], offset = _a[1];
                return function (sx) { return (sx - offset) / factor; };
            },
            enumerable: false,
            configurable: true
        });
        return CategoricalScale;
    }(scale_1.Scale));
    exports.CategoricalScale = CategoricalScale;
    CategoricalScale.__name__ = "CategoricalScale";
},
/* models/ranges/data_range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var data_range_1 = require(179) /* ./data_range */;
    var enums_1 = require(135) /* ../../core/enums */;
    var array_1 = require(126) /* ../../core/util/array */;
    var logging_1 = require(134) /* ../../core/logging */;
    var bbox = (0, tslib_1.__importStar)(require(180) /* ../../core/util/bbox */);
    var util_1 = require(181) /* ../util */;
    var DataRange1d = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DataRange1d, _super);
        function DataRange1d(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.have_updated_interactively = false;
            return _this;
        }
        DataRange1d.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._initial_start = this.start;
            this._initial_end = this.end;
            this._initial_range_padding = this.range_padding;
            this._initial_range_padding_units = this.range_padding_units;
            this._initial_follow = this.follow;
            this._initial_follow_interval = this.follow_interval;
            this._initial_default_span = this.default_span;
            this._plot_bounds = new Map();
        };
        Object.defineProperty(DataRange1d.prototype, "min", {
            get: function () {
                return Math.min(this.start, this.end);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DataRange1d.prototype, "max", {
            get: function () {
                return Math.max(this.start, this.end);
            },
            enumerable: false,
            configurable: true
        });
        DataRange1d.prototype.computed_renderers = function () {
            // TODO (bev) check that renderers actually configured with this range
            var _b = this, renderers = _b.renderers, names = _b.names;
            var all_renderers = (0, array_1.concat)(this.plots.map(function (plot) { return plot.data_renderers; }));
            return (0, util_1.compute_renderers)(renderers.length == 0 ? "auto" : renderers, all_renderers, names);
        };
        /*protected*/ DataRange1d.prototype._compute_plot_bounds = function (renderers, bounds) {
            var e_1, _b;
            var result = bbox.empty();
            try {
                for (var renderers_1 = (0, tslib_1.__values)(renderers), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                    var r = renderers_1_1.value;
                    var rect = bounds.get(r);
                    if (rect != null && (r.visible || !this.only_visible)) {
                        result = bbox.union(result, rect);
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (renderers_1_1 && !renderers_1_1.done && (_b = renderers_1.return))
                        _b.call(renderers_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return result;
        };
        DataRange1d.prototype.adjust_bounds_for_aspect = function (bounds, ratio) {
            var result = bbox.empty();
            var width = bounds.x1 - bounds.x0;
            if (width <= 0) {
                width = 1.0;
            }
            var height = bounds.y1 - bounds.y0;
            if (height <= 0) {
                height = 1.0;
            }
            var xcenter = 0.5 * (bounds.x1 + bounds.x0);
            var ycenter = 0.5 * (bounds.y1 + bounds.y0);
            if (width < ratio * height) {
                width = ratio * height;
            }
            else {
                height = width / ratio;
            }
            result.x1 = xcenter + 0.5 * width;
            result.x0 = xcenter - 0.5 * width;
            result.y1 = ycenter + 0.5 * height;
            result.y0 = ycenter - 0.5 * height;
            return result;
        };
        /*protected*/ DataRange1d.prototype._compute_min_max = function (plot_bounds, dimension) {
            var e_2, _b, _c, _d;
            var overall = bbox.empty();
            try {
                for (var plot_bounds_1 = (0, tslib_1.__values)(plot_bounds), plot_bounds_1_1 = plot_bounds_1.next(); !plot_bounds_1_1.done; plot_bounds_1_1 = plot_bounds_1.next()) {
                    var rect = plot_bounds_1_1.value;
                    overall = bbox.union(overall, rect);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (plot_bounds_1_1 && !plot_bounds_1_1.done && (_b = plot_bounds_1.return))
                        _b.call(plot_bounds_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            var min, max;
            if (dimension == 0)
                _c = (0, tslib_1.__read)([overall.x0, overall.x1], 2), min = _c[0], max = _c[1];
            else
                _d = (0, tslib_1.__read)([overall.y0, overall.y1], 2), min = _d[0], max = _d[1];
            return [min, max];
        };
        /*protected*/ DataRange1d.prototype._compute_range = function (min, max) {
            var _b;
            var range_padding = this.range_padding; // XXX: ? 0
            var start, end;
            if (this._initial_start != null)
                min = this._initial_start;
            if (this._initial_end != null)
                max = this._initial_end;
            if (this.scale_hint == "log") {
                if (isNaN(min) || !isFinite(min) || min <= 0) {
                    if (isNaN(max) || !isFinite(max) || max <= 0)
                        min = 0.1;
                    else
                        min = max / 100;
                    logging_1.logger.warn("could not determine minimum data value for log axis, DataRange1d using value " + min);
                }
                if (isNaN(max) || !isFinite(max) || max <= 0) {
                    if (isNaN(min) || !isFinite(min) || min <= 0)
                        max = 10;
                    else
                        max = min * 100;
                    logging_1.logger.warn("could not determine maximum data value for log axis, DataRange1d using value " + max);
                }
                var center = void 0, span = void 0;
                if (max == min) {
                    span = this.default_span + 0.001;
                    center = Math.log(min) / Math.log(10);
                }
                else {
                    var log_min = void 0, log_max = void 0;
                    if (this.range_padding_units == "percent") {
                        log_min = Math.log(min) / Math.log(10);
                        log_max = Math.log(max) / Math.log(10);
                        span = (log_max - log_min) * (1 + range_padding);
                    }
                    else {
                        log_min = Math.log(min - range_padding) / Math.log(10);
                        log_max = Math.log(max + range_padding) / Math.log(10);
                        span = log_max - log_min;
                    }
                    center = (log_min + log_max) / 2.0;
                }
                start = Math.pow(10, (center - span / 2.0));
                end = Math.pow(10, (center + span / 2.0));
            }
            else {
                var span = void 0;
                if (max == min)
                    span = this.default_span;
                else {
                    if (this.range_padding_units == "percent")
                        span = (max - min) * (1 + range_padding);
                    else
                        span = (max - min) + 2 * range_padding;
                }
                var center = (max + min) / 2.0;
                start = center - span / 2.0;
                end = center + span / 2.0;
            }
            var follow_sign = +1;
            if (this.flipped) {
                _b = (0, tslib_1.__read)([end, start], 2), start = _b[0], end = _b[1];
                follow_sign = -1;
            }
            var follow_interval = this.follow_interval;
            if (follow_interval != null && Math.abs(start - end) > follow_interval) {
                if (this.follow == "start")
                    end = start + follow_sign * follow_interval;
                else if (this.follow == "end")
                    start = end - follow_sign * follow_interval;
            }
            return [start, end];
        };
        DataRange1d.prototype.update = function (bounds, dimension, plot, ratio) {
            if (this.have_updated_interactively)
                return;
            var renderers = this.computed_renderers();
            // update the raw data bounds for all renderers we care about
            var total_bounds = this._compute_plot_bounds(renderers, bounds);
            if (ratio != null)
                total_bounds = this.adjust_bounds_for_aspect(total_bounds, ratio);
            this._plot_bounds.set(plot, total_bounds);
            // compute the min/mix for our specified dimension
            var _b = (0, tslib_1.__read)(this._compute_min_max(this._plot_bounds.values(), dimension), 2), min = _b[0], max = _b[1];
            // derive start, end from bounds and data range config
            var _c = (0, tslib_1.__read)(this._compute_range(min, max), 2), start = _c[0], end = _c[1];
            if (this._initial_start != null) {
                if (this.scale_hint == "log") {
                    if (this._initial_start > 0)
                        start = this._initial_start;
                }
                else
                    start = this._initial_start;
            }
            if (this._initial_end != null) {
                if (this.scale_hint == "log") {
                    if (this._initial_end > 0)
                        end = this._initial_end;
                }
                else
                    end = this._initial_end;
            }
            var needs_emit = false;
            if (this.bounds == "auto") {
                this.setv({ bounds: [start, end] }, { silent: true });
                needs_emit = true;
            }
            // only trigger updates when there are changes
            var _d = (0, tslib_1.__read)([this.start, this.end], 2), _start = _d[0], _end = _d[1];
            if (start != _start || end != _end) {
                var new_range = {};
                if (start != _start)
                    new_range.start = start;
                if (end != _end)
                    new_range.end = end;
                this.setv(new_range);
                needs_emit = false;
            }
            if (needs_emit)
                this.change.emit();
        };
        DataRange1d.prototype.reset = function () {
            this.have_updated_interactively = false;
            // change events silenced as PlotView.update_dataranges triggers property callbacks
            this.setv({
                range_padding: this._initial_range_padding,
                range_padding_units: this._initial_range_padding_units,
                follow: this._initial_follow,
                follow_interval: this._initial_follow_interval,
                default_span: this._initial_default_span,
            }, { silent: true });
            this.change.emit();
        };
        return DataRange1d;
    }(data_range_1.DataRange));
    exports.DataRange1d = DataRange1d;
    _a = DataRange1d;
    DataRange1d.__name__ = "DataRange1d";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Number = _b.Number, Nullable = _b.Nullable;
            return ({
                start: [Number],
                end: [Number],
                range_padding: [Number, 0.1],
                range_padding_units: [enums_1.PaddingUnits, "percent"],
                flipped: [Boolean, false],
                follow: [Nullable(enums_1.StartEnd), null],
                follow_interval: [Nullable(Number), null],
                default_span: [Number, 2.0],
                only_visible: [Boolean, false],
            });
        });
        _a.internal(function (_b) {
            var Enum = _b.Enum;
            return ({
                scale_hint: [Enum("log", "auto"), "auto"],
            });
        });
    })();
},
/* models/ranges/data_range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var range_1 = require(172) /* ./range */;
    var DataRange = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DataRange, _super);
        function DataRange(attrs) {
            return _super.call(this, attrs) || this;
        }
        return DataRange;
    }(range_1.Range));
    exports.DataRange = DataRange;
    _a = DataRange;
    DataRange.__name__ = "DataRange";
    (function () {
        _a.define(function (_b) {
            var String = _b.String, Array = _b.Array, AnyRef = _b.AnyRef;
            return ({
                names: [Array(String), []],
                renderers: [Array(AnyRef( /*DataRenderer*/)), []], // TODO: [] -> "auto"
            });
        });
    })();
},
/* core/util/bbox.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(139) /* ../types */;
    var eq_1 = require(141) /* ./eq */;
    var min = Math.min, max = Math.max;
    function empty() {
        return {
            x0: Infinity,
            y0: Infinity,
            x1: -Infinity,
            y1: -Infinity,
        };
    }
    exports.empty = empty;
    function positive_x() {
        return {
            x0: Number.MIN_VALUE,
            y0: -Infinity,
            x1: Infinity,
            y1: Infinity,
        };
    }
    exports.positive_x = positive_x;
    function positive_y() {
        return {
            x0: -Infinity,
            y0: Number.MIN_VALUE,
            x1: Infinity,
            y1: Infinity,
        };
    }
    exports.positive_y = positive_y;
    function union(a, b) {
        return {
            x0: min(a.x0, b.x0),
            x1: max(a.x1, b.x1),
            y0: min(a.y0, b.y0),
            y1: max(a.y1, b.y1),
        };
    }
    exports.union = union;
    var BBox = /** @class */ (function () {
        function BBox(box) {
            if (box == null) {
                this.x0 = 0;
                this.y0 = 0;
                this.x1 = 0;
                this.y1 = 0;
            }
            else if ("x0" in box) {
                var x0 = box.x0, y0 = box.y0, x1 = box.x1, y1 = box.y1;
                if (!(x0 <= x1 && y0 <= y1))
                    throw new Error("invalid bbox {x0: " + x0 + ", y0: " + y0 + ", x1: " + x1 + ", y1: " + y1 + "}");
                this.x0 = x0;
                this.y0 = y0;
                this.x1 = x1;
                this.y1 = y1;
            }
            else if ("x" in box) {
                var x = box.x, y = box.y, width = box.width, height = box.height;
                if (!(width >= 0 && height >= 0))
                    throw new Error("invalid bbox {x: " + x + ", y: " + y + ", width: " + width + ", height: " + height + "}");
                this.x0 = x;
                this.y0 = y;
                this.x1 = x + width;
                this.y1 = y + height;
            }
            else {
                var left = void 0, right = void 0;
                var top = void 0, bottom = void 0;
                if ("width" in box) {
                    if ("left" in box) {
                        left = box.left;
                        right = left + box.width;
                    }
                    else if ("right" in box) {
                        right = box.right;
                        left = right - box.width;
                    }
                    else {
                        var w2 = box.width / 2;
                        left = box.hcenter - w2;
                        right = box.hcenter + w2;
                    }
                }
                else {
                    left = box.left;
                    right = box.right;
                }
                if ("height" in box) {
                    if ("top" in box) {
                        top = box.top;
                        bottom = top + box.height;
                    }
                    else if ("bottom" in box) {
                        bottom = box.bottom;
                        top = bottom - box.height;
                    }
                    else {
                        var h2 = box.height / 2;
                        top = box.vcenter - h2;
                        bottom = box.vcenter + h2;
                    }
                }
                else {
                    top = box.top;
                    bottom = box.bottom;
                }
                if (!(left <= right && top <= bottom))
                    throw new Error("invalid bbox {left: " + left + ", top: " + top + ", right: " + right + ", bottom: " + bottom + "}");
                this.x0 = left;
                this.y0 = top;
                this.x1 = right;
                this.y1 = bottom;
            }
        }
        BBox.from_rect = function (_a) {
            var left = _a.left, right = _a.right, top = _a.top, bottom = _a.bottom;
            return new BBox({
                x0: Math.min(left, right),
                y0: Math.min(top, bottom),
                x1: Math.max(left, right),
                y1: Math.max(top, bottom),
            });
        };
        BBox.prototype.equals = function (that) {
            return this.x0 == that.x0 && this.y0 == that.y0 &&
                this.x1 == that.x1 && this.y1 == that.y1;
        };
        BBox.prototype[eq_1.equals] = function (that, cmp) {
            return cmp.eq(this.x0, that.x0) && cmp.eq(this.y0, that.y0) &&
                cmp.eq(this.x1, that.x1) && cmp.eq(this.y1, that.y1);
        };
        BBox.prototype.toString = function () {
            return "BBox({left: " + this.left + ", top: " + this.top + ", width: " + this.width + ", height: " + this.height + "})";
        };
        Object.defineProperty(BBox.prototype, "left", {
            get: function () { return this.x0; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "top", {
            get: function () { return this.y0; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "right", {
            get: function () { return this.x1; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "bottom", {
            get: function () { return this.y1; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "p0", {
            get: function () { return [this.x0, this.y0]; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "p1", {
            get: function () { return [this.x1, this.y1]; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "x", {
            get: function () { return this.x0; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "y", {
            get: function () { return this.y0; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "width", {
            get: function () { return this.x1 - this.x0; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "height", {
            get: function () { return this.y1 - this.y0; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "size", {
            get: function () { return { width: this.width, height: this.height }; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "rect", {
            get: function () {
                var _a = this, x0 = _a.x0, y0 = _a.y0, x1 = _a.x1, y1 = _a.y1;
                return {
                    p0: { x: x0, y: y0 },
                    p1: { x: x1, y: y0 },
                    p2: { x: x1, y: y1 },
                    p3: { x: x0, y: y1 },
                };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "box", {
            get: function () {
                var _a = this, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
                return { x: x, y: y, width: width, height: height };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "h_range", {
            get: function () { return { start: this.x0, end: this.x1 }; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "v_range", {
            get: function () { return { start: this.y0, end: this.y1 }; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "ranges", {
            get: function () { return [this.h_range, this.v_range]; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "aspect", {
            get: function () { return this.width / this.height; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "hcenter", {
            get: function () { return (this.left + this.right) / 2; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "vcenter", {
            get: function () { return (this.top + this.bottom) / 2; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "area", {
            get: function () { return this.width * this.height; },
            enumerable: false,
            configurable: true
        });
        BBox.prototype.relative = function () {
            var _a = this, width = _a.width, height = _a.height;
            return new BBox({ x: 0, y: 0, width: width, height: height });
        };
        BBox.prototype.translate = function (tx, ty) {
            var _a = this, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
            return new BBox({ x: tx + x, y: ty + y, width: width, height: height });
        };
        BBox.prototype.relativize = function (x, y) {
            return [x - this.x, y - this.y];
        };
        BBox.prototype.contains = function (x, y) {
            return this.x0 <= x && x <= this.x1 && this.y0 <= y && y <= this.y1;
        };
        BBox.prototype.clip = function (x, y) {
            if (x < this.x0)
                x = this.x0;
            else if (x > this.x1)
                x = this.x1;
            if (y < this.y0)
                y = this.y0;
            else if (y > this.y1)
                y = this.y1;
            return [x, y];
        };
        BBox.prototype.grow_by = function (size) {
            return new BBox({
                left: this.left - size,
                right: this.right + size,
                top: this.top - size,
                bottom: this.bottom + size,
            });
        };
        BBox.prototype.shrink_by = function (size) {
            return new BBox({
                left: this.left + size,
                right: this.right - size,
                top: this.top + size,
                bottom: this.bottom - size,
            });
        };
        BBox.prototype.union = function (that) {
            return new BBox({
                x0: min(this.x0, that.x0),
                y0: min(this.y0, that.y0),
                x1: max(this.x1, that.x1),
                y1: max(this.y1, that.y1),
            });
        };
        BBox.prototype.intersection = function (that) {
            if (!this.intersects(that))
                return null;
            else {
                return new BBox({
                    x0: max(this.x0, that.x0),
                    y0: max(this.y0, that.y0),
                    x1: min(this.x1, that.x1),
                    y1: min(this.y1, that.y1),
                });
            }
        };
        BBox.prototype.intersects = function (that) {
            return !(that.x1 < this.x0 || that.x0 > this.x1 ||
                that.y1 < this.y0 || that.y0 > this.y1);
        };
        Object.defineProperty(BBox.prototype, "xview", {
            get: function () {
                var _this = this;
                return {
                    compute: function (x) {
                        return _this.left + x;
                    },
                    v_compute: function (xx) {
                        var _xx = new types_1.ScreenArray(xx.length);
                        var left = _this.left;
                        for (var i = 0; i < xx.length; i++) {
                            _xx[i] = left + xx[i];
                        }
                        return _xx;
                    },
                };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BBox.prototype, "yview", {
            get: function () {
                var _this = this;
                return {
                    compute: function (y) {
                        return _this.bottom - y;
                    },
                    v_compute: function (yy) {
                        var _yy = new types_1.ScreenArray(yy.length);
                        var bottom = _this.bottom;
                        for (var i = 0; i < yy.length; i++) {
                            _yy[i] = bottom - yy[i];
                        }
                        return _yy;
                    },
                };
            },
            enumerable: false,
            configurable: true
        });
        return BBox;
    }());
    exports.BBox = BBox;
    BBox.__name__ = "BBox";
},
/* models/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var array_1 = require(126) /* ../core/util/array */;
    function compute_renderers(renderers, all_renderers, names) {
        if (renderers == null)
            return [];
        var result = renderers == "auto" ? all_renderers : renderers;
        if (names.length > 0)
            result = result.filter(function (r) { return (0, array_1.includes)(names, r.name); });
        return result;
    }
    exports.compute_renderers = compute_renderers;
},
/* models/ranges/factor_range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var range_1 = require(172) /* ./range */;
    var enums_1 = require(135) /* ../../core/enums */;
    var kinds_1 = require(136) /* ../../core/kinds */;
    var types_1 = require(139) /* ../../core/types */;
    var array_1 = require(126) /* ../../core/util/array */;
    var types_2 = require(125) /* ../../core/util/types */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    exports.Factor = (0, kinds_1.Or)(kinds_1.String, (0, kinds_1.Tuple)(kinds_1.String, kinds_1.String), (0, kinds_1.Tuple)(kinds_1.String, kinds_1.String, kinds_1.String));
    exports.FactorSeq = (0, kinds_1.Or)((0, kinds_1.Array)(kinds_1.String), (0, kinds_1.Array)((0, kinds_1.Tuple)(kinds_1.String, kinds_1.String)), (0, kinds_1.Array)((0, kinds_1.Tuple)(kinds_1.String, kinds_1.String, kinds_1.String)));
    function map_one_level(factors, padding, offset) {
        if (offset === void 0) {
            offset = 0;
        }
        var mapping = new Map();
        for (var i = 0; i < factors.length; i++) {
            var factor = factors[i];
            if (!mapping.has(factor))
                mapping.set(factor, { value: 0.5 + i * (1 + padding) + offset });
            else
                throw new Error("duplicate factor or subfactor: " + factor);
        }
        return [mapping, (factors.length - 1) * padding];
    }
    exports.map_one_level = map_one_level;
    function map_two_levels(factors, outer_pad, factor_pad, offset) {
        var e_1, _b, e_2, _c;
        var _d;
        if (offset === void 0) {
            offset = 0;
        }
        var mapping = new Map();
        var tops = new Map();
        try {
            for (var factors_1 = (0, tslib_1.__values)(factors), factors_1_1 = factors_1.next(); !factors_1_1.done; factors_1_1 = factors_1.next()) {
                var _e = (0, tslib_1.__read)(factors_1_1.value, 2), f0 = _e[0], f1 = _e[1];
                var top = (_d = tops.get(f0)) !== null && _d !== void 0 ? _d : [];
                tops.set(f0, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(top), false), [f1], false));
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (factors_1_1 && !factors_1_1.done && (_b = factors_1.return))
                    _b.call(factors_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        var suboffset = offset;
        var total_subpad = 0;
        var _loop_1 = function (f0, top) {
            var n = top.length;
            var _g = (0, tslib_1.__read)(map_one_level(top, factor_pad, suboffset), 2), submap = _g[0], subpad = _g[1];
            total_subpad += subpad;
            var subtot = (0, array_1.sum)(top.map(function (f1) { return submap.get(f1).value; }));
            mapping.set(f0, { value: subtot / n, mapping: submap });
            suboffset += n + outer_pad + subpad;
        };
        try {
            for (var tops_1 = (0, tslib_1.__values)(tops), tops_1_1 = tops_1.next(); !tops_1_1.done; tops_1_1 = tops_1.next()) {
                var _f = (0, tslib_1.__read)(tops_1_1.value, 2), f0 = _f[0], top = _f[1];
                _loop_1(f0, top);
            }
        }
        catch (e_2_1) {
            e_2 = { error: e_2_1 };
        }
        finally {
            try {
                if (tops_1_1 && !tops_1_1.done && (_c = tops_1.return))
                    _c.call(tops_1);
            }
            finally {
                if (e_2)
                    throw e_2.error;
            }
        }
        return [mapping, (tops.size - 1) * outer_pad + total_subpad];
    }
    exports.map_two_levels = map_two_levels;
    function map_three_levels(factors, outer_pad, inner_pad, factor_pad, offset) {
        var e_3, _b, e_4, _c;
        var _d;
        if (offset === void 0) {
            offset = 0;
        }
        var mapping = new Map();
        var tops = new Map();
        try {
            for (var factors_2 = (0, tslib_1.__values)(factors), factors_2_1 = factors_2.next(); !factors_2_1.done; factors_2_1 = factors_2.next()) {
                var _e = (0, tslib_1.__read)(factors_2_1.value, 3), f0 = _e[0], f1 = _e[1], f2 = _e[2];
                var top = (_d = tops.get(f0)) !== null && _d !== void 0 ? _d : [];
                tops.set(f0, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(top), false), [[f1, f2]], false));
            }
        }
        catch (e_3_1) {
            e_3 = { error: e_3_1 };
        }
        finally {
            try {
                if (factors_2_1 && !factors_2_1.done && (_b = factors_2.return))
                    _b.call(factors_2);
            }
            finally {
                if (e_3)
                    throw e_3.error;
            }
        }
        var suboffset = offset;
        var total_subpad = 0;
        var _loop_2 = function (f0, top) {
            var n = top.length;
            var _g = (0, tslib_1.__read)(map_two_levels(top, inner_pad, factor_pad, suboffset), 2), submap = _g[0], subpad = _g[1];
            total_subpad += subpad;
            var subtot = (0, array_1.sum)(top.map(function (_b) {
                var _c = (0, tslib_1.__read)(_b, 1), f1 = _c[0];
                return submap.get(f1).value;
            }));
            mapping.set(f0, { value: subtot / n, mapping: submap });
            suboffset += n + outer_pad + subpad;
        };
        try {
            for (var tops_2 = (0, tslib_1.__values)(tops), tops_2_1 = tops_2.next(); !tops_2_1.done; tops_2_1 = tops_2.next()) {
                var _f = (0, tslib_1.__read)(tops_2_1.value, 2), f0 = _f[0], top = _f[1];
                _loop_2(f0, top);
            }
        }
        catch (e_4_1) {
            e_4 = { error: e_4_1 };
        }
        finally {
            try {
                if (tops_2_1 && !tops_2_1.done && (_c = tops_2.return))
                    _c.call(tops_2);
            }
            finally {
                if (e_4)
                    throw e_4.error;
            }
        }
        return [mapping, (tops.size - 1) * outer_pad + total_subpad];
    }
    exports.map_three_levels = map_three_levels;
    var FactorRange = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FactorRange, _super);
        function FactorRange(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(FactorRange.prototype, "min", {
            get: function () {
                return this.start;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(FactorRange.prototype, "max", {
            get: function () {
                return this.end;
            },
            enumerable: false,
            configurable: true
        });
        FactorRange.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._init(true);
        };
        FactorRange.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.properties.factors.change, function () { return _this.reset(); });
            this.connect(this.properties.factor_padding.change, function () { return _this.reset(); });
            this.connect(this.properties.group_padding.change, function () { return _this.reset(); });
            this.connect(this.properties.subgroup_padding.change, function () { return _this.reset(); });
            this.connect(this.properties.range_padding.change, function () { return _this.reset(); });
            this.connect(this.properties.range_padding_units.change, function () { return _this.reset(); });
        };
        FactorRange.prototype.reset = function () {
            this._init(false);
            this.change.emit();
        };
        FactorRange.prototype._lookup = function (x) {
            switch (x.length) {
                case 1: {
                    var _b = (0, tslib_1.__read)(x, 1), f0 = _b[0];
                    var mapping = this._mapping;
                    var y0 = mapping.get(f0);
                    return y0 != null ? y0.value : NaN;
                }
                case 2: {
                    var _c = (0, tslib_1.__read)(x, 2), f0 = _c[0], f1 = _c[1];
                    var mapping = this._mapping;
                    var y0 = mapping.get(f0);
                    if (y0 != null) {
                        var y1 = y0.mapping.get(f1);
                        if (y1 != null)
                            return y1.value;
                    }
                    return NaN;
                }
                case 3: {
                    var _d = (0, tslib_1.__read)(x, 3), f0 = _d[0], f1 = _d[1], f2 = _d[2];
                    var mapping = this._mapping;
                    var y0 = mapping.get(f0);
                    if (y0 != null) {
                        var y1 = y0.mapping.get(f1);
                        if (y1 != null) {
                            var y2 = y1.mapping.get(f2);
                            if (y2 != null)
                                return y2.value;
                        }
                    }
                    return NaN;
                }
                default:
                    (0, assert_1.unreachable)();
            }
        };
        // convert a string factor into a synthetic coordinate
        FactorRange.prototype.synthetic = function (x) {
            if ((0, types_2.isNumber)(x))
                return x;
            if ((0, types_2.isString)(x))
                return this._lookup([x]);
            var offset = 0;
            var off = x[x.length - 1];
            if ((0, types_2.isNumber)(off)) {
                offset = off;
                x = x.slice(0, -1);
            }
            return this._lookup(x) + offset;
        };
        // convert an array of string factors into synthetic coordinates
        FactorRange.prototype.v_synthetic = function (xs) {
            var n = xs.length;
            var array = new types_1.ScreenArray(n);
            for (var i = 0; i < n; i++) {
                array[i] = this.synthetic(xs[i]);
            }
            return array;
        };
        FactorRange.prototype._init = function (silent) {
            var _this = this;
            var _b = (function () {
                var e_5, _b, e_6, _c;
                if ((0, array_1.every)(_this.factors, types_2.isString)) {
                    var factors = _this.factors;
                    var _d = (0, tslib_1.__read)(map_one_level(factors, _this.factor_padding), 2), mapping_2 = _d[0], inside_padding_1 = _d[1];
                    var tops_3 = null;
                    var mids_1 = null;
                    return { levels: 1, mapping: mapping_2, tops: tops_3, mids: mids_1, inside_padding: inside_padding_1 };
                }
                else if ((0, array_1.every)(_this.factors, function (x) { return (0, types_2.isArray)(x) && x.length == 2 && (0, types_2.isString)(x[0]) && (0, types_2.isString)(x[1]); })) {
                    var factors = _this.factors;
                    var _e = (0, tslib_1.__read)(map_two_levels(factors, _this.group_padding, _this.factor_padding), 2), mapping_3 = _e[0], inside_padding_2 = _e[1];
                    var tops_4 = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(mapping_3.keys()), false);
                    var mids_2 = null;
                    return { levels: 2, mapping: mapping_3, tops: tops_4, mids: mids_2, inside_padding: inside_padding_2 };
                }
                else if ((0, array_1.every)(_this.factors, function (x) { return (0, types_2.isArray)(x) && x.length == 3 && (0, types_2.isString)(x[0]) && (0, types_2.isString)(x[1]) && (0, types_2.isString)(x[2]); })) {
                    var factors = _this.factors;
                    var _f = (0, tslib_1.__read)(map_three_levels(factors, _this.group_padding, _this.subgroup_padding, _this.factor_padding), 2), mapping_4 = _f[0], inside_padding_3 = _f[1];
                    var tops_5 = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(mapping_4.keys()), false);
                    var mids_3 = [];
                    try {
                        for (var mapping_1 = (0, tslib_1.__values)(mapping_4), mapping_1_1 = mapping_1.next(); !mapping_1_1.done; mapping_1_1 = mapping_1.next()) {
                            var _g = (0, tslib_1.__read)(mapping_1_1.value, 2), f0 = _g[0], L2 = _g[1];
                            try {
                                for (var _h = (e_6 = void 0, (0, tslib_1.__values)(L2.mapping.keys())), _j = _h.next(); !_j.done; _j = _h.next()) {
                                    var f1 = _j.value;
                                    mids_3.push([f0, f1]);
                                }
                            }
                            catch (e_6_1) {
                                e_6 = { error: e_6_1 };
                            }
                            finally {
                                try {
                                    if (_j && !_j.done && (_c = _h.return))
                                        _c.call(_h);
                                }
                                finally {
                                    if (e_6)
                                        throw e_6.error;
                                }
                            }
                        }
                    }
                    catch (e_5_1) {
                        e_5 = { error: e_5_1 };
                    }
                    finally {
                        try {
                            if (mapping_1_1 && !mapping_1_1.done && (_b = mapping_1.return))
                                _b.call(mapping_1);
                        }
                        finally {
                            if (e_5)
                                throw e_5.error;
                        }
                    }
                    return { levels: 3, mapping: mapping_4, tops: tops_5, mids: mids_3, inside_padding: inside_padding_3 };
                }
                else
                    (0, assert_1.unreachable)();
            })(), levels = _b.levels, mapping = _b.mapping, tops = _b.tops, mids = _b.mids, inside_padding = _b.inside_padding;
            this._mapping = mapping;
            this.tops = tops;
            this.mids = mids;
            var start = 0;
            var end = this.factors.length + inside_padding;
            if (this.range_padding_units == "percent") {
                var half_span = (end - start) * this.range_padding / 2;
                start -= half_span;
                end += half_span;
            }
            else {
                start -= this.range_padding;
                end += this.range_padding;
            }
            this.setv({ start: start, end: end, levels: levels }, { silent: silent });
            if (this.bounds == "auto")
                this.setv({ bounds: [start, end] }, { silent: true });
        };
        return FactorRange;
    }(range_1.Range));
    exports.FactorRange = FactorRange;
    _a = FactorRange;
    FactorRange.__name__ = "FactorRange";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number;
            return ({
                factors: [exports.FactorSeq, []],
                factor_padding: [Number, 0],
                subgroup_padding: [Number, 0.8],
                group_padding: [Number, 1.4],
                range_padding: [Number, 0],
                range_padding_units: [enums_1.PaddingUnits, "percent"],
                start: [Number],
                end: [Number],
            });
        });
        _a.internal(function (_b) {
            var Number = _b.Number, String = _b.String, Array = _b.Array, Tuple = _b.Tuple, Nullable = _b.Nullable;
            return ({
                levels: [Number],
                mids: [Nullable(Array(Tuple(String, String))), null],
                tops: [Nullable(Array(String)), null], // top level factors (whether 2 or 3 total levels)
            });
        });
    })();
},
/* models/annotations/arrow.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var data_annotation_1 = require(184) /* ./data_annotation */;
    var arrow_head_1 = require(227) /* ./arrow_head */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var enums_1 = require(135) /* ../../core/enums */;
    var types_1 = require(139) /* ../../core/types */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var math_1 = require(117) /* ../../core/util/math */;
    var ArrowView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ArrowView, _super);
        function ArrowView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ArrowView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var _b, start, end, _c, _d;
                return (0, tslib_1.__generator)(this, function (_e) {
                    switch (_e.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _e.sent();
                            _b = this.model, start = _b.start, end = _b.end;
                            if (!(start != null))
                                return [3 /*break*/, 3];
                            _c = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(start, { parent: this })];
                        case 2:
                            _c.start = _e.sent();
                            _e.label = 3;
                        case 3:
                            if (!(end != null))
                                return [3 /*break*/, 5];
                            _d = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(end, { parent: this })];
                        case 4:
                            _d.end = _e.sent();
                            _e.label = 5;
                        case 5: return [2 /*return*/];
                    }
                });
            });
        };
        ArrowView.prototype.set_data = function (source) {
            var _b, _c;
            _super.prototype.set_data.call(this, source);
            (_b = this.start) === null || _b === void 0 ? void 0 : _b.set_data(source);
            (_c = this.end) === null || _c === void 0 ? void 0 : _c.set_data(source);
        };
        ArrowView.prototype.remove = function () {
            var _b, _c;
            (_b = this.start) === null || _b === void 0 ? void 0 : _b.remove();
            (_c = this.end) === null || _c === void 0 ? void 0 : _c.remove();
            _super.prototype.remove.call(this);
        };
        ArrowView.prototype.map_data = function () {
            var frame = this.plot_view.frame;
            if (this.model.start_units == "data") {
                this._sx_start = this.coordinates.x_scale.v_compute(this._x_start);
                this._sy_start = this.coordinates.y_scale.v_compute(this._y_start);
            }
            else {
                this._sx_start = frame.bbox.xview.v_compute(this._x_start);
                this._sy_start = frame.bbox.yview.v_compute(this._y_start);
            }
            if (this.model.end_units == "data") {
                this._sx_end = this.coordinates.x_scale.v_compute(this._x_end);
                this._sy_end = this.coordinates.y_scale.v_compute(this._y_end);
            }
            else {
                this._sx_end = frame.bbox.xview.v_compute(this._x_end);
                this._sy_end = frame.bbox.yview.v_compute(this._y_end);
            }
            var _b = this, _sx_start = _b._sx_start, _sy_start = _b._sy_start, _sx_end = _b._sx_end, _sy_end = _b._sy_end;
            var n = _sx_start.length;
            var angles = this._angles = new types_1.ScreenArray(n);
            for (var i = 0; i < n; i++) {
                // arrow head runs orthogonal to arrow body (???)
                angles[i] = Math.PI / 2 + (0, math_1.atan2)([_sx_start[i], _sy_start[i]], [_sx_end[i], _sy_end[i]]);
            }
        };
        ArrowView.prototype.paint = function (ctx) {
            var _b = this, start = _b.start, end = _b.end;
            var _c = this, _sx_start = _c._sx_start, _sy_start = _c._sy_start, _sx_end = _c._sx_end, _sy_end = _c._sy_end, _angles = _c._angles;
            var _d = this.plot_view.frame.bbox, x = _d.x, y = _d.y, width = _d.width, height = _d.height;
            for (var i = 0, n = _sx_start.length; i < n; i++) {
                if (end != null) {
                    ctx.save();
                    ctx.translate(_sx_end[i], _sy_end[i]);
                    ctx.rotate(_angles[i]);
                    end.render(ctx, i);
                    ctx.restore();
                }
                if (start != null) {
                    ctx.save();
                    ctx.translate(_sx_start[i], _sy_start[i]);
                    ctx.rotate(_angles[i] + Math.PI);
                    start.render(ctx, i);
                    ctx.restore();
                }
                if (this.visuals.line.doit) {
                    ctx.save();
                    if (start != null || end != null) {
                        ctx.beginPath();
                        ctx.rect(x, y, width, height);
                        if (end != null) {
                            ctx.save();
                            ctx.translate(_sx_end[i], _sy_end[i]);
                            ctx.rotate(_angles[i]);
                            end.clip(ctx, i);
                            ctx.restore();
                        }
                        if (start != null) {
                            ctx.save();
                            ctx.translate(_sx_start[i], _sy_start[i]);
                            ctx.rotate(_angles[i] + Math.PI);
                            start.clip(ctx, i);
                            ctx.restore();
                        }
                        ctx.closePath();
                        ctx.clip();
                    }
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.beginPath();
                    ctx.moveTo(_sx_start[i], _sy_start[i]);
                    ctx.lineTo(_sx_end[i], _sy_end[i]);
                    ctx.stroke();
                    ctx.restore();
                }
            }
        };
        return ArrowView;
    }(data_annotation_1.DataAnnotationView));
    exports.ArrowView = ArrowView;
    ArrowView.__name__ = "ArrowView";
    var Arrow = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Arrow, _super);
        function Arrow(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Arrow;
    }(data_annotation_1.DataAnnotation));
    exports.Arrow = Arrow;
    _a = Arrow;
    Arrow.__name__ = "Arrow";
    (function () {
        _a.prototype.default_view = ArrowView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(function (_b) {
            var Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                x_start: [p.XCoordinateSpec, { field: "x_start" }],
                y_start: [p.YCoordinateSpec, { field: "y_start" }],
                start_units: [enums_1.SpatialUnits, "data"],
                start: [Nullable(Ref(arrow_head_1.ArrowHead)), null],
                x_end: [p.XCoordinateSpec, { field: "x_end" }],
                y_end: [p.YCoordinateSpec, { field: "y_end" }],
                end_units: [enums_1.SpatialUnits, "data"],
                end: [Nullable(Ref(arrow_head_1.ArrowHead)), function () { return new arrow_head_1.OpenHead(); }],
            });
        });
    })();
},
/* models/annotations/data_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var columnar_data_source_1 = require(185) /* ../sources/columnar_data_source */;
    var column_data_source_1 = require(190) /* ../sources/column_data_source */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var DataAnnotationView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DataAnnotationView, _super);
        function DataAnnotationView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._initial_set_data = false;
            return _this;
        }
        DataAnnotationView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var update = function () {
                _this.set_data(_this.model.source);
                _this._rerender();
            };
            this.connect(this.model.change, update);
            this.connect(this.model.source.streaming, update);
            this.connect(this.model.source.patching, update);
            this.connect(this.model.source.change, update);
        };
        DataAnnotationView.prototype._rerender = function () {
            this.request_render();
        };
        DataAnnotationView.prototype.set_data = function (source) {
            var e_1, _b, e_2, _c;
            var self = this;
            try {
                for (var _d = (0, tslib_1.__values)(this.model), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var prop = _e.value;
                    if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                        continue;
                    if (prop instanceof p.BaseCoordinateSpec) {
                        var array = prop.array(source);
                        self["_" + prop.attr] = array;
                    }
                    else {
                        var uniform = prop.uniform(source);
                        self["" + prop.attr] = uniform;
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            if (this.plot_model.use_map) {
                if (self._x != null)
                    projections_1.inplace.project_xy(self._x, self._y);
                if (self._xs != null)
                    projections_1.inplace.project_xsys(self._xs, self._ys);
            }
            try {
                for (var _f = (0, tslib_1.__values)(this.visuals), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var visual = _g.value;
                    visual.update();
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_c = _f.return))
                        _c.call(_f);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        };
        DataAnnotationView.prototype._render = function () {
            if (!this._initial_set_data) {
                this.set_data(this.model.source);
                this._initial_set_data = true;
            }
            this.map_data();
            this.paint(this.layer.ctx);
        };
        return DataAnnotationView;
    }(annotation_1.AnnotationView));
    exports.DataAnnotationView = DataAnnotationView;
    DataAnnotationView.__name__ = "DataAnnotationView";
    var DataAnnotation = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DataAnnotation, _super);
        function DataAnnotation(attrs) {
            return _super.call(this, attrs) || this;
        }
        return DataAnnotation;
    }(annotation_1.Annotation));
    exports.DataAnnotation = DataAnnotation;
    _a = DataAnnotation;
    DataAnnotation.__name__ = "DataAnnotation";
    (function () {
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                source: [Ref(columnar_data_source_1.ColumnarDataSource), function () { return new column_data_source_1.ColumnDataSource(); }],
            });
        });
    })();
},
/* models/sources/columnar_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var data_source_1 = require(186) /* ./data_source */;
    var signaling_1 = require(130) /* ../../core/signaling */;
    var logging_1 = require(134) /* ../../core/logging */;
    var selection_manager_1 = require(188) /* ../../core/selection_manager */;
    var types_1 = require(125) /* ../../core/util/types */;
    var array_1 = require(126) /* ../../core/util/array */;
    var object_1 = require(128) /* ../../core/util/object */;
    var selection_1 = require(187) /* ../selections/selection */;
    var interaction_policy_1 = require(189) /* ../selections/interaction_policy */;
    var ndarray_1 = require(144) /* ../../core/util/ndarray */;
    var ColumnarDataSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColumnarDataSource, _super);
        function ColumnarDataSource(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.selection_manager = new selection_manager_1.SelectionManager(_this);
            return _this;
        }
        ColumnarDataSource.prototype.get_array = function (key) {
            var column = this.data[key];
            if (column == null)
                this.data[key] = column = [];
            else if (!(0, types_1.isArray)(column))
                this.data[key] = column = Array.from(column);
            return column;
        };
        ColumnarDataSource.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._select = new signaling_1.Signal0(this, "select");
            this.inspect = new signaling_1.Signal(this, "inspect");
            this.streaming = new signaling_1.Signal0(this, "streaming");
            this.patching = new signaling_1.Signal(this, "patching");
        };
        ColumnarDataSource.prototype.get_column = function (colname) {
            var column = this.data[colname];
            return column != null ? column : null;
        };
        ColumnarDataSource.prototype.columns = function () {
            // return the column names in this data source
            return (0, object_1.keys)(this.data);
        };
        ColumnarDataSource.prototype.get_length = function (soft) {
            if (soft === void 0) {
                soft = true;
            }
            var lengths = (0, array_1.uniq)((0, object_1.values)(this.data).map(function (v) { return (0, ndarray_1.is_NDArray)(v) ? v.shape[0] : v.length; }));
            switch (lengths.length) {
                case 0: {
                    return null; // XXX: don't guess, treat on case-by-case basis
                }
                case 1: {
                    return lengths[0];
                }
                default: {
                    var msg = "data source has columns of inconsistent lengths";
                    if (soft) {
                        logging_1.logger.warn(msg);
                        return lengths.sort()[0];
                    }
                    else
                        throw new Error(msg);
                }
            }
        };
        Object.defineProperty(ColumnarDataSource.prototype, "length", {
            get: function () {
                var _b;
                return (_b = this.get_length()) !== null && _b !== void 0 ? _b : 0;
            },
            enumerable: false,
            configurable: true
        });
        ColumnarDataSource.prototype.clear = function () {
            var e_1, _b;
            var empty = {};
            try {
                for (var _c = (0, tslib_1.__values)(this.columns()), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var col = _d.value;
                    empty[col] = new this.data[col].constructor(0);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            this.data = empty;
        };
        return ColumnarDataSource;
    }(data_source_1.DataSource));
    exports.ColumnarDataSource = ColumnarDataSource;
    _a = ColumnarDataSource;
    ColumnarDataSource.__name__ = "ColumnarDataSource";
    (function () {
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                selection_policy: [Ref(interaction_policy_1.SelectionPolicy), function () { return new interaction_policy_1.UnionRenderers(); }],
            });
        });
        _a.internal(function (_b) {
            var AnyRef = _b.AnyRef;
            return ({
                inspected: [AnyRef(), function () { return new selection_1.Selection(); }],
            });
        });
    })();
},
/* models/sources/data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var selection_1 = require(187) /* ../selections/selection */;
    var DataSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DataSource, _super);
        function DataSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        return DataSource;
    }(model_1.Model));
    exports.DataSource = DataSource;
    _a = DataSource;
    DataSource.__name__ = "DataSource";
    (function () {
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                selected: [Ref(selection_1.Selection), function () { return new selection_1.Selection(); }],
            });
        });
    })();
},
/* models/selections/selection.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var array_1 = require(126) /* ../../core/util/array */;
    var object_1 = require(128) /* ../../core/util/object */;
    var Selection = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Selection, _super);
        function Selection(attrs) {
            return _super.call(this, attrs) || this;
        }
        Selection.prototype.get_view = function () {
            return this.view;
        };
        Object.defineProperty(Selection.prototype, "selected_glyph", {
            get: function () {
                return this.selected_glyphs.length > 0 ? this.selected_glyphs[0] : null;
            },
            enumerable: false,
            configurable: true
        });
        Selection.prototype.add_to_selected_glyphs = function (glyph) {
            this.selected_glyphs.push(glyph);
        };
        Selection.prototype.update = function (selection, _final, mode) {
            if (_final === void 0) {
                _final = true;
            }
            if (mode === void 0) {
                mode = "replace";
            }
            switch (mode) {
                case "replace": {
                    this.indices = selection.indices;
                    this.line_indices = selection.line_indices;
                    this.multiline_indices = selection.multiline_indices;
                    this.image_indices = selection.image_indices;
                    this.view = selection.view;
                    this.selected_glyphs = selection.selected_glyphs;
                    break;
                }
                case "append": {
                    this.update_through_union(selection);
                    break;
                }
                case "intersect": {
                    this.update_through_intersection(selection);
                    break;
                }
                case "subtract": {
                    this.update_through_subtraction(selection);
                    break;
                }
            }
        };
        Selection.prototype.clear = function () {
            this.indices = [];
            this.line_indices = [];
            this.multiline_indices = {};
            this.image_indices = [];
            this.view = null;
            this.selected_glyphs = [];
        };
        Selection.prototype.map = function (mapper) {
            return new Selection((0, tslib_1.__assign)((0, tslib_1.__assign)({}, this.attributes), { indices: this.indices.map(mapper),
                // NOTE: line_indices don't support subset indexing
                multiline_indices: (0, object_1.to_object)((0, object_1.entries)(this.multiline_indices).map(function (_b) {
                    var _c = (0, tslib_1.__read)(_b, 2), index = _c[0], line_indices = _c[1];
                    return [mapper(Number(index)), line_indices];
                })), image_indices: this.image_indices.map(function (ndx) { return ((0, tslib_1.__assign)((0, tslib_1.__assign)({}, ndx), { index: mapper(ndx.index) })); }) }));
        };
        Selection.prototype.is_empty = function () {
            return this.indices.length == 0 && this.line_indices.length == 0 && this.image_indices.length == 0;
        };
        Selection.prototype.update_through_union = function (other) {
            this.indices = (0, array_1.union)(this.indices, other.indices);
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        };
        Selection.prototype.update_through_intersection = function (other) {
            this.indices = (0, array_1.intersection)(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        };
        Selection.prototype.update_through_subtraction = function (other) {
            this.indices = (0, array_1.difference)(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        };
        return Selection;
    }(model_1.Model));
    exports.Selection = Selection;
    _a = Selection;
    Selection.__name__ = "Selection";
    (function () {
        _a.define(function (_b) {
            var Int = _b.Int, Array = _b.Array, Dict = _b.Dict;
            return ({
                indices: [Array(Int), []],
                line_indices: [Array(Int), []],
                multiline_indices: [Dict(Array(Int)), {}],
            });
        });
        _a.internal(function (_b) {
            var Int = _b.Int, Array = _b.Array, AnyRef = _b.AnyRef, Struct = _b.Struct, Nullable = _b.Nullable;
            return ({
                selected_glyphs: [Array(AnyRef()), []],
                view: [Nullable(AnyRef()), null],
                // Used internally to support hover tool for now. Python API TBD
                image_indices: [Array(Struct({ index: Int, dim1: Int, dim2: Int, flat_index: Int })), []],
            });
        });
    })();
},
/* core/selection_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var selection_1 = require(187) /* ../models/selections/selection */;
    // XXX: this is needed to cut circular dependency between this, models/renderers/* and models/sources/*
    function is_GlyphRendererView(renderer_view) {
        return renderer_view.model.type == "GlyphRenderer";
    }
    function is_GraphRendererView(renderer_view) {
        return renderer_view.model.type == "GraphRenderer";
    }
    var SelectionManager = /** @class */ (function () {
        function SelectionManager(source) {
            this.source = source;
            this.inspectors = new Map();
        }
        SelectionManager.prototype.select = function (renderer_views, geometry, final, mode) {
            var e_1, _a, e_2, _b;
            if (mode === void 0) {
                mode = "replace";
            }
            // divide renderers into glyph_renderers or graph_renderers
            var glyph_renderer_views = [];
            var graph_renderer_views = [];
            try {
                for (var renderer_views_1 = (0, tslib_1.__values)(renderer_views), renderer_views_1_1 = renderer_views_1.next(); !renderer_views_1_1.done; renderer_views_1_1 = renderer_views_1.next()) {
                    var r = renderer_views_1_1.value;
                    if (is_GlyphRendererView(r))
                        glyph_renderer_views.push(r);
                    else if (is_GraphRendererView(r))
                        graph_renderer_views.push(r);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (renderer_views_1_1 && !renderer_views_1_1.done && (_a = renderer_views_1.return))
                        _a.call(renderer_views_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            var did_hit = false;
            try {
                // graph renderer case
                for (var graph_renderer_views_1 = (0, tslib_1.__values)(graph_renderer_views), graph_renderer_views_1_1 = graph_renderer_views_1.next(); !graph_renderer_views_1_1.done; graph_renderer_views_1_1 = graph_renderer_views_1.next()) {
                    var r = graph_renderer_views_1_1.value;
                    var hit_test_result = r.model.selection_policy.hit_test(geometry, r);
                    did_hit = did_hit || r.model.selection_policy.do_selection(hit_test_result, r.model, final, mode);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (graph_renderer_views_1_1 && !graph_renderer_views_1_1.done && (_b = graph_renderer_views_1.return))
                        _b.call(graph_renderer_views_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            // glyph renderers
            if (glyph_renderer_views.length > 0) {
                var hit_test_result = this.source.selection_policy.hit_test(geometry, glyph_renderer_views);
                did_hit = did_hit || this.source.selection_policy.do_selection(hit_test_result, this.source, final, mode);
            }
            return did_hit;
        };
        SelectionManager.prototype.inspect = function (renderer_view, geometry) {
            var did_hit = false;
            if (is_GlyphRendererView(renderer_view)) {
                var hit_test_result = renderer_view.hit_test(geometry);
                if (hit_test_result != null) {
                    did_hit = !hit_test_result.is_empty();
                    var inspection = this.get_or_create_inspector(renderer_view.model);
                    inspection.update(hit_test_result, true, "replace");
                    this.source.setv({ inspected: inspection }, { silent: true });
                    this.source.inspect.emit([renderer_view.model, { geometry: geometry }]);
                }
            }
            else if (is_GraphRendererView(renderer_view)) {
                var hit_test_result = renderer_view.model.inspection_policy.hit_test(geometry, renderer_view);
                did_hit = did_hit || renderer_view.model.inspection_policy.do_inspection(hit_test_result, geometry, renderer_view, false, "replace");
            }
            return did_hit;
        };
        SelectionManager.prototype.clear = function (rview) {
            this.source.selected.clear();
            if (rview != null)
                this.get_or_create_inspector(rview.model).clear();
        };
        SelectionManager.prototype.get_or_create_inspector = function (renderer) {
            var selection = this.inspectors.get(renderer);
            if (selection == null) {
                selection = new selection_1.Selection();
                this.inspectors.set(renderer, selection);
            }
            return selection;
        };
        return SelectionManager;
    }());
    exports.SelectionManager = SelectionManager;
    SelectionManager.__name__ = "SelectionManager";
},
/* models/selections/interaction_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../../model */;
    var SelectionPolicy = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SelectionPolicy, _super);
        function SelectionPolicy() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SelectionPolicy.prototype.do_selection = function (hit_test_result, source, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            else {
                source.selected.update(hit_test_result, final, mode);
                source._select.emit();
                return !source.selected.is_empty();
            }
        };
        return SelectionPolicy;
    }(model_1.Model));
    exports.SelectionPolicy = SelectionPolicy;
    SelectionPolicy.__name__ = "SelectionPolicy";
    var IntersectRenderers = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(IntersectRenderers, _super);
        function IntersectRenderers() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        IntersectRenderers.prototype.hit_test = function (geometry, renderer_views) {
            var e_1, _a, e_2, _b;
            var hit_test_result_renderers = [];
            try {
                for (var renderer_views_1 = (0, tslib_1.__values)(renderer_views), renderer_views_1_1 = renderer_views_1.next(); !renderer_views_1_1.done; renderer_views_1_1 = renderer_views_1.next()) {
                    var r = renderer_views_1_1.value;
                    var result = r.hit_test(geometry);
                    if (result != null)
                        hit_test_result_renderers.push(result);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (renderer_views_1_1 && !renderer_views_1_1.done && (_a = renderer_views_1.return))
                        _a.call(renderer_views_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            if (hit_test_result_renderers.length > 0) {
                var hit_test_result = hit_test_result_renderers[0];
                try {
                    for (var hit_test_result_renderers_1 = (0, tslib_1.__values)(hit_test_result_renderers), hit_test_result_renderers_1_1 = hit_test_result_renderers_1.next(); !hit_test_result_renderers_1_1.done; hit_test_result_renderers_1_1 = hit_test_result_renderers_1.next()) {
                        var hit_test_result_other = hit_test_result_renderers_1_1.value;
                        hit_test_result.update_through_intersection(hit_test_result_other);
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (hit_test_result_renderers_1_1 && !hit_test_result_renderers_1_1.done && (_b = hit_test_result_renderers_1.return))
                            _b.call(hit_test_result_renderers_1);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
                return hit_test_result;
            }
            else {
                return null;
            }
        };
        return IntersectRenderers;
    }(SelectionPolicy));
    exports.IntersectRenderers = IntersectRenderers;
    IntersectRenderers.__name__ = "IntersectRenderers";
    var UnionRenderers = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UnionRenderers, _super);
        function UnionRenderers() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        UnionRenderers.prototype.hit_test = function (geometry, renderer_views) {
            var e_3, _a, e_4, _b;
            var hit_test_result_renderers = [];
            try {
                for (var renderer_views_2 = (0, tslib_1.__values)(renderer_views), renderer_views_2_1 = renderer_views_2.next(); !renderer_views_2_1.done; renderer_views_2_1 = renderer_views_2.next()) {
                    var r = renderer_views_2_1.value;
                    var result = r.hit_test(geometry);
                    if (result != null)
                        hit_test_result_renderers.push(result);
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (renderer_views_2_1 && !renderer_views_2_1.done && (_a = renderer_views_2.return))
                        _a.call(renderer_views_2);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            if (hit_test_result_renderers.length > 0) {
                var hit_test_result = hit_test_result_renderers[0];
                try {
                    for (var hit_test_result_renderers_2 = (0, tslib_1.__values)(hit_test_result_renderers), hit_test_result_renderers_2_1 = hit_test_result_renderers_2.next(); !hit_test_result_renderers_2_1.done; hit_test_result_renderers_2_1 = hit_test_result_renderers_2.next()) {
                        var hit_test_result_other = hit_test_result_renderers_2_1.value;
                        hit_test_result.update_through_union(hit_test_result_other);
                    }
                }
                catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                }
                finally {
                    try {
                        if (hit_test_result_renderers_2_1 && !hit_test_result_renderers_2_1.done && (_b = hit_test_result_renderers_2.return))
                            _b.call(hit_test_result_renderers_2);
                    }
                    finally {
                        if (e_4)
                            throw e_4.error;
                    }
                }
                return hit_test_result;
            }
            else {
                return null;
            }
        };
        return UnionRenderers;
    }(SelectionPolicy));
    exports.UnionRenderers = UnionRenderers;
    UnionRenderers.__name__ = "UnionRenderers";
},
/* models/sources/column_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var columnar_data_source_1 = require(185) /* ./columnar_data_source */;
    var types_1 = require(125) /* ../../core/util/types */;
    var object_1 = require(128) /* ../../core/util/object */;
    var typed_array = (0, tslib_1.__importStar)(require(191) /* ../../core/util/typed_array */);
    var set_1 = require(192) /* ../../core/util/set */;
    var events_1 = require(150) /* ../../document/events */;
    //exported for testing
    function stream_to_column(col, new_col, rollover) {
        if ((0, types_1.isArray)(col)) {
            var result = col.concat(new_col);
            if (rollover != null && result.length > rollover)
                return result.slice(-rollover);
            else
                return result;
        }
        else if ((0, types_1.isTypedArray)(col)) {
            var total_len = col.length + new_col.length;
            // handle rollover case for typed arrays
            if (rollover != null && total_len > rollover) {
                var start = total_len - rollover;
                var end = col.length;
                // resize col if it is shorter than the rollover length
                var result = void 0;
                if (col.length < rollover) {
                    result = new col.constructor(rollover);
                    result.set(col, 0);
                }
                else
                    result = col;
                // shift values in original col to accommodate new_col
                for (var i = start, endi = end; i < endi; i++) {
                    result[i - start] = result[i];
                }
                // update end values in col with new_col
                for (var i = 0, endi = new_col.length; i < endi; i++) {
                    result[i + (end - start)] = new_col[i];
                }
                return result;
            }
            else {
                var tmp = new col.constructor(new_col);
                return typed_array.concat(col, tmp);
            }
        }
        else
            throw new Error("unsupported array types");
    }
    exports.stream_to_column = stream_to_column;
    // exported for testing
    function slice(ind, length) {
        var start, step, stop;
        if ((0, types_1.isNumber)(ind)) {
            start = ind;
            stop = ind + 1;
            step = 1;
        }
        else {
            start = ind.start != null ? ind.start : 0;
            stop = ind.stop != null ? ind.stop : length;
            step = ind.step != null ? ind.step : 1;
        }
        return [start, stop, step];
    }
    exports.slice = slice;
    // exported for testing
    function patch_to_column(col, patch) {
        var e_1, _b;
        var patched = new Set();
        var patched_range = false;
        try {
            for (var patch_1 = (0, tslib_1.__values)(patch), patch_1_1 = patch_1.next(); !patch_1_1.done; patch_1_1 = patch_1.next()) {
                var _c = (0, tslib_1.__read)(patch_1_1.value, 2), ind = _c[0], val = _c[1];
                // make the single index case look like the length-3 multi-index case
                var shape = void 0;
                var item = void 0;
                var index = void 0;
                var value = void 0;
                if ((0, types_1.isArray)(ind)) {
                    var _d = (0, tslib_1.__read)(ind, 1), i = _d[0];
                    patched.add(i);
                    shape = col[i].shape;
                    item = col[i];
                    value = val;
                    // this is basically like NumPy's "newaxis", inserting an empty dimension
                    // makes length 2 and 3 multi-index cases uniform, so that the same code
                    // can handle both
                    if (ind.length === 2) {
                        shape = [1, shape[0]];
                        index = [ind[0], 0, ind[1]];
                    }
                    else
                        index = ind;
                }
                else {
                    if ((0, types_1.isNumber)(ind)) {
                        value = [val];
                        patched.add(ind);
                    }
                    else {
                        value = val;
                        patched_range = true;
                    }
                    index = [0, 0, ind];
                    shape = [1, col.length];
                    item = col;
                }
                // now this one nested loop handles all cases
                var flat_index = 0;
                var _e = (0, tslib_1.__read)(slice(index[1], shape[0]), 3), istart = _e[0], istop = _e[1], istep = _e[2];
                var _f = (0, tslib_1.__read)(slice(index[2], shape[1]), 3), jstart = _f[0], jstop = _f[1], jstep = _f[2];
                for (var i = istart; i < istop; i += istep) {
                    for (var j = jstart; j < jstop; j += jstep) {
                        if (patched_range) {
                            patched.add(j);
                        }
                        item[i * shape[1] + j] = value[flat_index];
                        flat_index++;
                    }
                }
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (patch_1_1 && !patch_1_1.done && (_b = patch_1.return))
                    _b.call(patch_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return patched;
    }
    exports.patch_to_column = patch_to_column;
    var ColumnDataSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColumnDataSource, _super);
        function ColumnDataSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        ColumnDataSource.prototype.stream = function (new_data, rollover, setter_id) {
            var e_2, _b;
            var data = this.data;
            try {
                for (var _c = (0, tslib_1.__values)((0, object_1.entries)(new_data)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), name = _e[0], new_column = _e[1];
                    data[name] = stream_to_column(data[name], new_column, rollover);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            this.setv({ data: data }, { silent: true });
            this.streaming.emit();
            if (this.document != null) {
                var hint = new events_1.ColumnsStreamedEvent(this.document, this.ref(), new_data, rollover);
                this.document._notify_change(this, "data", null, null, { setter_id: setter_id, hint: hint });
            }
        };
        ColumnDataSource.prototype.patch = function (patches, setter_id) {
            var e_3, _b;
            var data = this.data;
            var patched = new Set();
            try {
                for (var _c = (0, tslib_1.__values)((0, object_1.entries)(patches)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), column = _e[0], patch = _e[1];
                    patched = (0, set_1.union)(patched, patch_to_column(data[column], patch)); // XXX
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            this.setv({ data: data }, { silent: true });
            this.patching.emit((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(patched), false));
            if (this.document != null) {
                var hint = new events_1.ColumnsPatchedEvent(this.document, this.ref(), patches);
                this.document._notify_change(this, "data", null, null, { setter_id: setter_id, hint: hint });
            }
        };
        return ColumnDataSource;
    }(columnar_data_source_1.ColumnarDataSource));
    exports.ColumnDataSource = ColumnDataSource;
    _a = ColumnDataSource;
    ColumnDataSource.__name__ = "ColumnDataSource";
    (function () {
        _a.define(function (_b) {
            var Dict = _b.Dict, Any = _b.Any /*Arrayable*/;
            return ({
                data: [Dict(Any /*Arrayable*/), {}], // TODO: resolve ndarray refs earlier
            });
        });
    })();
},
/* core/util/typed_array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    function concat(array0) {
        var e_1, _a, e_2, _b;
        var arrays = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            arrays[_i - 1] = arguments[_i];
        }
        var n = array0.length;
        try {
            for (var arrays_1 = (0, tslib_1.__values)(arrays), arrays_1_1 = arrays_1.next(); !arrays_1_1.done; arrays_1_1 = arrays_1.next()) {
                var array = arrays_1_1.value;
                n += array.length;
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (arrays_1_1 && !arrays_1_1.done && (_a = arrays_1.return))
                    _a.call(arrays_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        var result = new array0.constructor(n);
        result.set(array0, 0);
        var i = array0.length;
        try {
            for (var arrays_2 = (0, tslib_1.__values)(arrays), arrays_2_1 = arrays_2.next(); !arrays_2_1.done; arrays_2_1 = arrays_2.next()) {
                var array = arrays_2_1.value;
                result.set(array, i);
                i += array.length;
            }
        }
        catch (e_2_1) {
            e_2 = { error: e_2_1 };
        }
        finally {
            try {
                if (arrays_2_1 && !arrays_2_1.done && (_b = arrays_2.return))
                    _b.call(arrays_2);
            }
            finally {
                if (e_2)
                    throw e_2.error;
            }
        }
        return result;
    }
    exports.concat = concat;
},
/* core/util/set.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    function union() {
        var e_1, _a, e_2, _b;
        var sets = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            sets[_i] = arguments[_i];
        }
        var result = new Set();
        try {
            for (var sets_1 = (0, tslib_1.__values)(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
                var set = sets_1_1.value;
                try {
                    for (var set_1 = (e_2 = void 0, (0, tslib_1.__values)(set)), set_1_1 = set_1.next(); !set_1_1.done; set_1_1 = set_1.next()) {
                        var item = set_1_1.value;
                        result.add(item);
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (set_1_1 && !set_1_1.done && (_b = set_1.return))
                            _b.call(set_1);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return))
                    _a.call(sets_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return result;
    }
    exports.union = union;
    function intersection(set) {
        var e_3, _a, e_4, _b;
        var sets = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            sets[_i - 1] = arguments[_i];
        }
        var result = new Set();
        try {
            top: for (var set_2 = (0, tslib_1.__values)(set), set_2_1 = set_2.next(); !set_2_1.done; set_2_1 = set_2.next()) {
                var item = set_2_1.value;
                try {
                    for (var sets_2 = (e_4 = void 0, (0, tslib_1.__values)(sets)), sets_2_1 = sets_2.next(); !sets_2_1.done; sets_2_1 = sets_2.next()) {
                        var other = sets_2_1.value;
                        if (!other.has(item))
                            continue top;
                    }
                }
                catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                }
                finally {
                    try {
                        if (sets_2_1 && !sets_2_1.done && (_b = sets_2.return))
                            _b.call(sets_2);
                    }
                    finally {
                        if (e_4)
                            throw e_4.error;
                    }
                }
                result.add(item);
            }
        }
        catch (e_3_1) {
            e_3 = { error: e_3_1 };
        }
        finally {
            try {
                if (set_2_1 && !set_2_1.done && (_a = set_2.return))
                    _a.call(set_2);
            }
            finally {
                if (e_3)
                    throw e_3.error;
            }
        }
        return result;
    }
    exports.intersection = intersection;
    function difference(set) {
        var e_5, _a;
        var sets = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            sets[_i - 1] = arguments[_i];
        }
        var result = new Set(set);
        try {
            for (var _b = (0, tslib_1.__values)(union.apply(void 0, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(sets), false))), _c = _b.next(); !_c.done; _c = _b.next()) {
                var item = _c.value;
                result.delete(item);
            }
        }
        catch (e_5_1) {
            e_5 = { error: e_5_1 };
        }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return))
                    _a.call(_b);
            }
            finally {
                if (e_5)
                    throw e_5.error;
            }
        }
        return result;
    }
    exports.difference = difference;
},
/* core/util/projections.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var core_1 = (0, tslib_1.__importDefault)(require(194) /* proj4/lib/core */);
    var Proj_1 = (0, tslib_1.__importDefault)(require(195) /* proj4/lib/Proj */);
    var types_1 = require(139) /* ../types */;
    var mercator = new Proj_1.default("GOOGLE");
    var wgs84 = new Proj_1.default("WGS84");
    var _wgs84_mercator = (0, core_1.default)(wgs84, mercator);
    exports.wgs84_mercator = {
        compute: function (x, y) {
            if (isFinite(x) && isFinite(y))
                return _wgs84_mercator.forward([x, y]);
            else
                return [NaN, NaN];
        },
        invert: function (merc_x, merc_y) {
            if (isFinite(merc_x) && isFinite(merc_y))
                return _wgs84_mercator.inverse([merc_x, merc_y]);
            else
                return [NaN, NaN];
        },
    };
    var mercator_bounds = {
        lon: [-20026376.39, 20026376.39],
        lat: [-20048966.10, 20048966.10],
    };
    var latlon_bounds = {
        lon: [-180, 180],
        lat: [-85.06, 85.06],
    };
    var min = Math.min, max = Math.max;
    function clip_mercator(low, high, dimension) {
        var _a = (0, tslib_1.__read)(mercator_bounds[dimension], 2), vmin = _a[0], vmax = _a[1];
        return [max(low, vmin), min(high, vmax)];
    }
    exports.clip_mercator = clip_mercator;
    function in_bounds(value, dimension) {
        var _a = (0, tslib_1.__read)(latlon_bounds[dimension], 2), min = _a[0], max = _a[1];
        return min < value && value < max;
    }
    exports.in_bounds = in_bounds;
    (function (inplace) {
        function project_xy(x, y, merc_x, merc_y) {
            var n = min(x.length, y.length);
            merc_x = merc_x !== null && merc_x !== void 0 ? merc_x : x;
            merc_y = merc_y !== null && merc_y !== void 0 ? merc_y : y;
            for (var i = 0; i < n; i++) {
                var xi = x[i];
                var yi = y[i];
                var _a = (0, tslib_1.__read)(exports.wgs84_mercator.compute(xi, yi), 2), merc_xi = _a[0], merc_yi = _a[1];
                merc_x[i] = merc_xi;
                merc_y[i] = merc_yi;
            }
        }
        inplace.project_xy = project_xy;
        function project_xsys(xs, ys, merc_xs, merc_ys) {
            var n = min(xs.length, ys.length);
            merc_xs = merc_xs !== null && merc_xs !== void 0 ? merc_xs : xs;
            merc_ys = merc_ys !== null && merc_ys !== void 0 ? merc_ys : ys;
            for (var i = 0; i < n; i++) {
                project_xy(xs[i], ys[i], merc_xs[i], merc_ys[i]);
            }
        }
        inplace.project_xsys = project_xsys;
    })(exports.inplace || (exports.inplace = {}));
    function project_xy(x, y) {
        var n = min(x.length, y.length);
        var ArrayType = (0, types_1.infer_type)(x, y);
        var merc_x = new ArrayType(n);
        var merc_y = new ArrayType(n);
        exports.inplace.project_xy(x, y, merc_x, merc_y);
        return [merc_x, merc_y];
    }
    exports.project_xy = project_xy;
    function project_xsys(xs, ys) {
        var n = min(xs.length, ys.length);
        var merc_xs = new Array(n);
        var merc_ys = new Array(n);
        for (var i = 0; i < n; i++) {
            var _a = (0, tslib_1.__read)(project_xy(xs[i], ys[i]), 2), merc_x = _a[0], merc_y = _a[1];
            merc_xs[i] = merc_x;
            merc_ys[i] = merc_y;
        }
        return [merc_xs, merc_ys];
    }
    exports.project_xsys = project_xsys;
},
/* proj4/lib/core.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var Proj_1 = (0, tslib_1.__importDefault)(require(195) /* ./Proj */);
    var transform_1 = (0, tslib_1.__importDefault)(require(221) /* ./transform */);
    var wgs84 = (0, Proj_1.default)('WGS84');
    function transformer(from, to, coords, enforceAxis) {
        var transformedArray, out, keys;
        if (Array.isArray(coords)) {
            transformedArray = (0, transform_1.default)(from, to, coords, enforceAxis) || { x: NaN, y: NaN };
            if (coords.length > 2) {
                if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) {
                    if (typeof transformedArray.z === 'number') {
                        return [transformedArray.x, transformedArray.y, transformedArray.z].concat(coords.splice(3));
                    }
                    else {
                        return [transformedArray.x, transformedArray.y, coords[2]].concat(coords.splice(3));
                    }
                }
                else {
                    return [transformedArray.x, transformedArray.y].concat(coords.splice(2));
                }
            }
            else {
                return [transformedArray.x, transformedArray.y];
            }
        }
        else {
            out = (0, transform_1.default)(from, to, coords, enforceAxis);
            keys = Object.keys(coords);
            if (keys.length === 2) {
                return out;
            }
            keys.forEach(function (key) {
                if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) {
                    if (key === 'x' || key === 'y' || key === 'z') {
                        return;
                    }
                }
                else {
                    if (key === 'x' || key === 'y') {
                        return;
                    }
                }
                out[key] = coords[key];
            });
            return out;
        }
    }
    function checkProj(item) {
        if (item instanceof Proj_1.default) {
            return item;
        }
        if (item.oProj) {
            return item.oProj;
        }
        return (0, Proj_1.default)(item);
    }
    function proj4(fromProj, toProj, coord) {
        fromProj = checkProj(fromProj);
        var single = false;
        var obj;
        if (typeof toProj === 'undefined') {
            toProj = fromProj;
            fromProj = wgs84;
            single = true;
        }
        else if (typeof toProj.x !== 'undefined' || Array.isArray(toProj)) {
            coord = toProj;
            toProj = fromProj;
            fromProj = wgs84;
            single = true;
        }
        toProj = checkProj(toProj);
        if (coord) {
            return transformer(fromProj, toProj, coord);
        }
        else {
            obj = {
                forward: function (coords, enforceAxis) {
                    return transformer(fromProj, toProj, coords, enforceAxis);
                },
                inverse: function (coords, enforceAxis) {
                    return transformer(toProj, fromProj, coords, enforceAxis);
                }
            };
            if (single) {
                obj.oProj = toProj;
            }
            return obj;
        }
    }
    exports.default = proj4;
},
/* proj4/lib/Proj.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var parseCode_1 = (0, tslib_1.__importDefault)(require(196) /* ./parseCode */);
    var extend_1 = (0, tslib_1.__importDefault)(require(207) /* ./extend */);
    var projections_1 = (0, tslib_1.__importDefault)(require(208) /* ./projections */);
    var deriveConstants_1 = require(216) /* ./deriveConstants */;
    var Datum_1 = (0, tslib_1.__importDefault)(require(218) /* ./constants/Datum */);
    var datum_1 = (0, tslib_1.__importDefault)(require(219) /* ./datum */);
    var match_1 = (0, tslib_1.__importDefault)(require(203) /* ./match */);
    var nadgrid_1 = require(220) /* ./nadgrid */;
    function Projection(srsCode, callback) {
        if (!(this instanceof Projection)) {
            return new Projection(srsCode);
        }
        callback = callback || function (error) {
            if (error) {
                throw error;
            }
        };
        var json = (0, parseCode_1.default)(srsCode);
        if (typeof json !== 'object') {
            callback(srsCode);
            return;
        }
        var ourProj = Projection.projections.get(json.projName);
        if (!ourProj) {
            callback(srsCode);
            return;
        }
        if (json.datumCode && json.datumCode !== 'none') {
            var datumDef = (0, match_1.default)(Datum_1.default, json.datumCode);
            if (datumDef) {
                json.datum_params = json.datum_params || (datumDef.towgs84 ? datumDef.towgs84.split(',') : null);
                json.ellps = datumDef.ellipse;
                json.datumName = datumDef.datumName ? datumDef.datumName : json.datumCode;
            }
        }
        json.k0 = json.k0 || 1.0;
        json.axis = json.axis || 'enu';
        json.ellps = json.ellps || 'wgs84';
        json.lat1 = json.lat1 || json.lat0; // Lambert_Conformal_Conic_1SP, for example, needs this
        var sphere_ = (0, deriveConstants_1.sphere)(json.a, json.b, json.rf, json.ellps, json.sphere);
        var ecc = (0, deriveConstants_1.eccentricity)(sphere_.a, sphere_.b, sphere_.rf, json.R_A);
        var nadgrids = (0, nadgrid_1.getNadgrids)(json.nadgrids);
        var datumObj = json.datum || (0, datum_1.default)(json.datumCode, json.datum_params, sphere_.a, sphere_.b, ecc.es, ecc.ep2, nadgrids);
        (0, extend_1.default)(this, json); // transfer everything over from the projection because we don't know what we'll need
        (0, extend_1.default)(this, ourProj); // transfer all the methods from the projection
        // copy the 4 things over we calulated in deriveConstants.sphere
        this.a = sphere_.a;
        this.b = sphere_.b;
        this.rf = sphere_.rf;
        this.sphere = sphere_.sphere;
        // copy the 3 things we calculated in deriveConstants.eccentricity
        this.es = ecc.es;
        this.e = ecc.e;
        this.ep2 = ecc.ep2;
        // add in the datum object
        this.datum = datumObj;
        // init the projection
        this.init();
        // legecy callback from back in the day when it went to spatialreference.org
        callback(null, this);
    }
    Projection.projections = projections_1.default;
    Projection.projections.start();
    exports.default = Projection;
},
/* proj4/lib/parseCode.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var defs_1 = (0, tslib_1.__importDefault)(require(197) /* ./defs */);
    var wkt_parser_1 = (0, tslib_1.__importDefault)(require(204) /* wkt-parser */);
    var projString_1 = (0, tslib_1.__importDefault)(require(199) /* ./projString */);
    var match_1 = (0, tslib_1.__importDefault)(require(203) /* ./match */);
    function testObj(code) {
        return typeof code === 'string';
    }
    function testDef(code) {
        return code in defs_1.default;
    }
    var codeWords = ['PROJECTEDCRS', 'PROJCRS', 'GEOGCS', 'GEOCCS', 'PROJCS', 'LOCAL_CS', 'GEODCRS', 'GEODETICCRS', 'GEODETICDATUM', 'ENGCRS', 'ENGINEERINGCRS'];
    function testWKT(code) {
        return codeWords.some(function (word) {
            return code.indexOf(word) > -1;
        });
    }
    var codes = ['3857', '900913', '3785', '102113'];
    function checkMercator(item) {
        var auth = (0, match_1.default)(item, 'authority');
        if (!auth) {
            return;
        }
        var code = (0, match_1.default)(auth, 'epsg');
        return code && codes.indexOf(code) > -1;
    }
    function checkProjStr(item) {
        var ext = (0, match_1.default)(item, 'extension');
        if (!ext) {
            return;
        }
        return (0, match_1.default)(ext, 'proj4');
    }
    function testProj(code) {
        return code[0] === '+';
    }
    function parse(code) {
        if (testObj(code)) {
            //check to see if this is a WKT string
            if (testDef(code)) {
                return defs_1.default[code];
            }
            if (testWKT(code)) {
                var out = (0, wkt_parser_1.default)(code);
                // test of spetial case, due to this being a very common and often malformed
                if (checkMercator(out)) {
                    return defs_1.default['EPSG:3857'];
                }
                var maybeProjStr = checkProjStr(out);
                if (maybeProjStr) {
                    return (0, projString_1.default)(maybeProjStr);
                }
                return out;
            }
            if (testProj(code)) {
                return (0, projString_1.default)(code);
            }
        }
        else {
            return code;
        }
    }
    exports.default = parse;
},
/* proj4/lib/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var global_1 = (0, tslib_1.__importDefault)(require(198) /* ./global */);
    var projString_1 = (0, tslib_1.__importDefault)(require(199) /* ./projString */);
    var wkt_parser_1 = (0, tslib_1.__importDefault)(require(204) /* wkt-parser */);
    function defs(name) {
        /*global console*/
        var that = this;
        if (arguments.length === 2) {
            var def = arguments[1];
            if (typeof def === 'string') {
                if (def.charAt(0) === '+') {
                    defs[name] = (0, projString_1.default)(arguments[1]);
                }
                else {
                    defs[name] = (0, wkt_parser_1.default)(arguments[1]);
                }
            }
            else {
                defs[name] = def;
            }
        }
        else if (arguments.length === 1) {
            if (Array.isArray(name)) {
                return name.map(function (v) {
                    if (Array.isArray(v)) {
                        defs.apply(that, v);
                    }
                    else {
                        defs(v);
                    }
                });
            }
            else if (typeof name === 'string') {
                if (name in defs) {
                    return defs[name];
                }
            }
            else if ('EPSG' in name) {
                defs['EPSG:' + name.EPSG] = name;
            }
            else if ('ESRI' in name) {
                defs['ESRI:' + name.ESRI] = name;
            }
            else if ('IAU2000' in name) {
                defs['IAU2000:' + name.IAU2000] = name;
            }
            else {
                console.log(name);
            }
            return;
        }
    }
    (0, global_1.default)(defs);
    exports.default = defs;
},
/* proj4/lib/global.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function default_1(defs) {
        defs('EPSG:4326', "+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees");
        defs('EPSG:4269', "+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees");
        defs('EPSG:3857', "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs");
        defs.WGS84 = defs['EPSG:4326'];
        defs['EPSG:3785'] = defs['EPSG:3857']; // maintain backward compat, official code is 3857
        defs.GOOGLE = defs['EPSG:3857'];
        defs['EPSG:900913'] = defs['EPSG:3857'];
        defs['EPSG:102113'] = defs['EPSG:3857'];
    }
    exports.default = default_1;
},
/* proj4/lib/projString.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var values_1 = require(200) /* ./constants/values */;
    var PrimeMeridian_1 = (0, tslib_1.__importDefault)(require(201) /* ./constants/PrimeMeridian */);
    var units_1 = (0, tslib_1.__importDefault)(require(202) /* ./constants/units */);
    var match_1 = (0, tslib_1.__importDefault)(require(203) /* ./match */);
    function default_1(defData) {
        var self = {};
        var paramObj = defData.split('+').map(function (v) {
            return v.trim();
        }).filter(function (a) {
            return a;
        }).reduce(function (p, a) {
            var split = a.split('=');
            split.push(true);
            p[split[0].toLowerCase()] = split[1];
            return p;
        }, {});
        var paramName, paramVal, paramOutname;
        var params = {
            proj: 'projName',
            datum: 'datumCode',
            rf: function (v) {
                self.rf = parseFloat(v);
            },
            lat_0: function (v) {
                self.lat0 = v * values_1.D2R;
            },
            lat_1: function (v) {
                self.lat1 = v * values_1.D2R;
            },
            lat_2: function (v) {
                self.lat2 = v * values_1.D2R;
            },
            lat_ts: function (v) {
                self.lat_ts = v * values_1.D2R;
            },
            lon_0: function (v) {
                self.long0 = v * values_1.D2R;
            },
            lon_1: function (v) {
                self.long1 = v * values_1.D2R;
            },
            lon_2: function (v) {
                self.long2 = v * values_1.D2R;
            },
            alpha: function (v) {
                self.alpha = parseFloat(v) * values_1.D2R;
            },
            gamma: function (v) {
                self.rectified_grid_angle = parseFloat(v);
            },
            lonc: function (v) {
                self.longc = v * values_1.D2R;
            },
            x_0: function (v) {
                self.x0 = parseFloat(v);
            },
            y_0: function (v) {
                self.y0 = parseFloat(v);
            },
            k_0: function (v) {
                self.k0 = parseFloat(v);
            },
            k: function (v) {
                self.k0 = parseFloat(v);
            },
            a: function (v) {
                self.a = parseFloat(v);
            },
            b: function (v) {
                self.b = parseFloat(v);
            },
            r_a: function () {
                self.R_A = true;
            },
            zone: function (v) {
                self.zone = parseInt(v, 10);
            },
            south: function () {
                self.utmSouth = true;
            },
            towgs84: function (v) {
                self.datum_params = v.split(",").map(function (a) {
                    return parseFloat(a);
                });
            },
            to_meter: function (v) {
                self.to_meter = parseFloat(v);
            },
            units: function (v) {
                self.units = v;
                var unit = (0, match_1.default)(units_1.default, v);
                if (unit) {
                    self.to_meter = unit.to_meter;
                }
            },
            from_greenwich: function (v) {
                self.from_greenwich = v * values_1.D2R;
            },
            pm: function (v) {
                var pm = (0, match_1.default)(PrimeMeridian_1.default, v);
                self.from_greenwich = (pm ? pm : parseFloat(v)) * values_1.D2R;
            },
            nadgrids: function (v) {
                if (v === '@null') {
                    self.datumCode = 'none';
                }
                else {
                    self.nadgrids = v;
                }
            },
            axis: function (v) {
                var legalAxis = "ewnsud";
                if (v.length === 3 && legalAxis.indexOf(v.substr(0, 1)) !== -1 && legalAxis.indexOf(v.substr(1, 1)) !== -1 && legalAxis.indexOf(v.substr(2, 1)) !== -1) {
                    self.axis = v;
                }
            },
            approx: function () {
                self.approx = true;
            }
        };
        for (paramName in paramObj) {
            paramVal = paramObj[paramName];
            if (paramName in params) {
                paramOutname = params[paramName];
                if (typeof paramOutname === 'function') {
                    paramOutname(paramVal);
                }
                else {
                    self[paramOutname] = paramVal;
                }
            }
            else {
                self[paramName] = paramVal;
            }
        }
        if (typeof self.datumCode === 'string' && self.datumCode !== "WGS84") {
            self.datumCode = self.datumCode.toLowerCase();
        }
        return self;
    }
    exports.default = default_1;
},
/* proj4/lib/constants/values.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.PJD_3PARAM = 1;
    exports.PJD_7PARAM = 2;
    exports.PJD_GRIDSHIFT = 3;
    exports.PJD_WGS84 = 4; // WGS84 or equivalent
    exports.PJD_NODATUM = 5; // WGS84 or equivalent
    exports.SRS_WGS84_SEMIMAJOR = 6378137.0; // only used in grid shift transforms
    exports.SRS_WGS84_SEMIMINOR = 6356752.314; // only used in grid shift transforms
    exports.SRS_WGS84_ESQUARED = 0.0066943799901413165; // only used in grid shift transforms
    exports.SEC_TO_RAD = 4.84813681109535993589914102357e-6;
    exports.HALF_PI = Math.PI / 2;
    // ellipoid pj_set_ell.c
    exports.SIXTH = 0.1666666666666666667;
    /* 1/6 */
    exports.RA4 = 0.04722222222222222222;
    /* 17/360 */
    exports.RA6 = 0.02215608465608465608;
    exports.EPSLN = 1.0e-10;
    // you'd think you could use Number.EPSILON above but that makes
    // Mollweide get into an infinate loop.
    exports.D2R = 0.01745329251994329577;
    exports.R2D = 57.29577951308232088;
    exports.FORTPI = Math.PI / 4;
    exports.TWO_PI = Math.PI * 2;
    // SPI is slightly greater than Math.PI, so values that exceed the -180..180
    // degree range by a tiny amount don't get wrapped. This prevents points that
    // have drifted from their original location along the 180th meridian (due to
    // floating point error) from changing their sign.
    exports.SPI = 3.14159265359;
},
/* proj4/lib/constants/PrimeMeridian.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var exports$1 = {};
    exports.default = exports$1;
    exports$1.greenwich = 0.0; //"0dE",
    exports$1.lisbon = -9.131906111111; //"9d07'54.862\"W",
    exports$1.paris = 2.337229166667; //"2d20'14.025\"E",
    exports$1.bogota = -74.080916666667; //"74d04'51.3\"W",
    exports$1.madrid = -3.687938888889; //"3d41'16.58\"W",
    exports$1.rome = 12.452333333333; //"12d27'8.4\"E",
    exports$1.bern = 7.439583333333; //"7d26'22.5\"E",
    exports$1.jakarta = 106.807719444444; //"106d48'27.79\"E",
    exports$1.ferro = -17.666666666667; //"17d40'W",
    exports$1.brussels = 4.367975; //"4d22'4.71\"E",
    exports$1.stockholm = 18.058277777778; //"18d3'29.8\"E",
    exports$1.athens = 23.7163375; //"23d42'58.815\"E",
    exports$1.oslo = 10.722916666667; //"10d43'22.5\"E"
},
/* proj4/lib/constants/units.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = {
        ft: { to_meter: 0.3048 },
        'us-ft': { to_meter: 1200 / 3937 }
    };
},
/* proj4/lib/match.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var ignoredChar = /[\s_\-\/\(\)]/g;
    function match(obj, key) {
        if (obj[key]) {
            return obj[key];
        }
        var keys = Object.keys(obj);
        var lkey = key.toLowerCase().replace(ignoredChar, '');
        var i = -1;
        var testkey, processedKey;
        while (++i < keys.length) {
            testkey = keys[i];
            processedKey = testkey.toLowerCase().replace(ignoredChar, '');
            if (processedKey === lkey) {
                return obj[testkey];
            }
        }
    }
    exports.default = match;
},
/* wkt-parser/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var D2R = 0.01745329251994329577;
    var parser_1 = (0, tslib_1.__importDefault)(require(205) /* ./parser */);
    var process_1 = require(206) /* ./process */;
    function rename(obj, params) {
        var outName = params[0];
        var inName = params[1];
        if (!(outName in obj) && (inName in obj)) {
            obj[outName] = obj[inName];
            if (params.length === 3) {
                obj[outName] = params[2](obj[outName]);
            }
        }
    }
    function d2r(input) {
        return input * D2R;
    }
    function cleanWKT(wkt) {
        if (wkt.type === 'GEOGCS') {
            wkt.projName = 'longlat';
        }
        else if (wkt.type === 'LOCAL_CS') {
            wkt.projName = 'identity';
            wkt.local = true;
        }
        else {
            if (typeof wkt.PROJECTION === 'object') {
                wkt.projName = Object.keys(wkt.PROJECTION)[0];
            }
            else {
                wkt.projName = wkt.PROJECTION;
            }
        }
        if (wkt.AXIS) {
            var axisOrder = '';
            for (var i = 0, ii = wkt.AXIS.length; i < ii; ++i) {
                var axis = [wkt.AXIS[i][0].toLowerCase(), wkt.AXIS[i][1].toLowerCase()];
                if (axis[0].indexOf('north') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'north')) {
                    axisOrder += 'n';
                }
                else if (axis[0].indexOf('south') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'south')) {
                    axisOrder += 's';
                }
                else if (axis[0].indexOf('east') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'east')) {
                    axisOrder += 'e';
                }
                else if (axis[0].indexOf('west') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'west')) {
                    axisOrder += 'w';
                }
            }
            if (axisOrder.length === 2) {
                axisOrder += 'u';
            }
            if (axisOrder.length === 3) {
                wkt.axis = axisOrder;
            }
        }
        if (wkt.UNIT) {
            wkt.units = wkt.UNIT.name.toLowerCase();
            if (wkt.units === 'metre') {
                wkt.units = 'meter';
            }
            if (wkt.UNIT.convert) {
                if (wkt.type === 'GEOGCS') {
                    if (wkt.DATUM && wkt.DATUM.SPHEROID) {
                        wkt.to_meter = wkt.UNIT.convert * wkt.DATUM.SPHEROID.a;
                    }
                }
                else {
                    wkt.to_meter = wkt.UNIT.convert;
                }
            }
        }
        var geogcs = wkt.GEOGCS;
        if (wkt.type === 'GEOGCS') {
            geogcs = wkt;
        }
        if (geogcs) {
            //if(wkt.GEOGCS.PRIMEM&&wkt.GEOGCS.PRIMEM.convert){
            //  wkt.from_greenwich=wkt.GEOGCS.PRIMEM.convert*D2R;
            //}
            if (geogcs.DATUM) {
                wkt.datumCode = geogcs.DATUM.name.toLowerCase();
            }
            else {
                wkt.datumCode = geogcs.name.toLowerCase();
            }
            if (wkt.datumCode.slice(0, 2) === 'd_') {
                wkt.datumCode = wkt.datumCode.slice(2);
            }
            if (wkt.datumCode === 'new_zealand_geodetic_datum_1949' || wkt.datumCode === 'new_zealand_1949') {
                wkt.datumCode = 'nzgd49';
            }
            if (wkt.datumCode === 'wgs_1984' || wkt.datumCode === 'world_geodetic_system_1984') {
                if (wkt.PROJECTION === 'Mercator_Auxiliary_Sphere') {
                    wkt.sphere = true;
                }
                wkt.datumCode = 'wgs84';
            }
            if (wkt.datumCode.slice(-6) === '_ferro') {
                wkt.datumCode = wkt.datumCode.slice(0, -6);
            }
            if (wkt.datumCode.slice(-8) === '_jakarta') {
                wkt.datumCode = wkt.datumCode.slice(0, -8);
            }
            if (~wkt.datumCode.indexOf('belge')) {
                wkt.datumCode = 'rnb72';
            }
            if (geogcs.DATUM && geogcs.DATUM.SPHEROID) {
                wkt.ellps = geogcs.DATUM.SPHEROID.name.replace('_19', '').replace(/[Cc]larke\_18/, 'clrk');
                if (wkt.ellps.toLowerCase().slice(0, 13) === 'international') {
                    wkt.ellps = 'intl';
                }
                wkt.a = geogcs.DATUM.SPHEROID.a;
                wkt.rf = parseFloat(geogcs.DATUM.SPHEROID.rf, 10);
            }
            if (geogcs.DATUM && geogcs.DATUM.TOWGS84) {
                wkt.datum_params = geogcs.DATUM.TOWGS84;
            }
            if (~wkt.datumCode.indexOf('osgb_1936')) {
                wkt.datumCode = 'osgb36';
            }
            if (~wkt.datumCode.indexOf('osni_1952')) {
                wkt.datumCode = 'osni52';
            }
            if (~wkt.datumCode.indexOf('tm65')
                || ~wkt.datumCode.indexOf('geodetic_datum_of_1965')) {
                wkt.datumCode = 'ire65';
            }
            if (wkt.datumCode === 'ch1903+') {
                wkt.datumCode = 'ch1903';
            }
            if (~wkt.datumCode.indexOf('israel')) {
                wkt.datumCode = 'isr93';
            }
        }
        if (wkt.b && !isFinite(wkt.b)) {
            wkt.b = wkt.a;
        }
        function toMeter(input) {
            var ratio = wkt.to_meter || 1;
            return input * ratio;
        }
        var renamer = function (a) {
            return rename(wkt, a);
        };
        var list = [
            ['standard_parallel_1', 'Standard_Parallel_1'],
            ['standard_parallel_1', 'Latitude of 1st standard parallel'],
            ['standard_parallel_2', 'Standard_Parallel_2'],
            ['standard_parallel_2', 'Latitude of 2nd standard parallel'],
            ['false_easting', 'False_Easting'],
            ['false_easting', 'False easting'],
            ['false-easting', 'Easting at false origin'],
            ['false_northing', 'False_Northing'],
            ['false_northing', 'False northing'],
            ['false_northing', 'Northing at false origin'],
            ['central_meridian', 'Central_Meridian'],
            ['central_meridian', 'Longitude of natural origin'],
            ['central_meridian', 'Longitude of false origin'],
            ['latitude_of_origin', 'Latitude_Of_Origin'],
            ['latitude_of_origin', 'Central_Parallel'],
            ['latitude_of_origin', 'Latitude of natural origin'],
            ['latitude_of_origin', 'Latitude of false origin'],
            ['scale_factor', 'Scale_Factor'],
            ['k0', 'scale_factor'],
            ['latitude_of_center', 'Latitude_Of_Center'],
            ['latitude_of_center', 'Latitude_of_center'],
            ['lat0', 'latitude_of_center', d2r],
            ['longitude_of_center', 'Longitude_Of_Center'],
            ['longitude_of_center', 'Longitude_of_center'],
            ['longc', 'longitude_of_center', d2r],
            ['x0', 'false_easting', toMeter],
            ['y0', 'false_northing', toMeter],
            ['long0', 'central_meridian', d2r],
            ['lat0', 'latitude_of_origin', d2r],
            ['lat0', 'standard_parallel_1', d2r],
            ['lat1', 'standard_parallel_1', d2r],
            ['lat2', 'standard_parallel_2', d2r],
            ['azimuth', 'Azimuth'],
            ['alpha', 'azimuth', d2r],
            ['srsCode', 'name']
        ];
        list.forEach(renamer);
        if (!wkt.long0 && wkt.longc && (wkt.projName === 'Albers_Conic_Equal_Area' || wkt.projName === 'Lambert_Azimuthal_Equal_Area')) {
            wkt.long0 = wkt.longc;
        }
        if (!wkt.lat_ts && wkt.lat1 && (wkt.projName === 'Stereographic_South_Pole' || wkt.projName === 'Polar Stereographic (variant B)')) {
            wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90);
            wkt.lat_ts = wkt.lat1;
        }
    }
    function default_1(wkt) {
        var lisp = (0, parser_1.default)(wkt);
        var type = lisp.shift();
        var name = lisp.shift();
        lisp.unshift(['name', name]);
        lisp.unshift(['type', type]);
        var obj = {};
        (0, process_1.sExpr)(lisp, obj);
        cleanWKT(obj);
        return obj;
    }
    exports.default = default_1;
},
/* wkt-parser/parser.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = parseString;
    var NEUTRAL = 1;
    var KEYWORD = 2;
    var NUMBER = 3;
    var QUOTED = 4;
    var AFTERQUOTE = 5;
    var ENDED = -1;
    var whitespace = /\s/;
    var latin = /[A-Za-z]/;
    var keyword = /[A-Za-z84]/;
    var endThings = /[,\]]/;
    var digets = /[\d\.E\-\+]/;
    // const ignoredChar = /[\s_\-\/\(\)]/g;
    function Parser(text) {
        if (typeof text !== 'string') {
            throw new Error('not a string');
        }
        this.text = text.trim();
        this.level = 0;
        this.place = 0;
        this.root = null;
        this.stack = [];
        this.currentObject = null;
        this.state = NEUTRAL;
    }
    Parser.prototype.readCharicter = function () {
        var char = this.text[this.place++];
        if (this.state !== QUOTED) {
            while (whitespace.test(char)) {
                if (this.place >= this.text.length) {
                    return;
                }
                char = this.text[this.place++];
            }
        }
        switch (this.state) {
            case NEUTRAL:
                return this.neutral(char);
            case KEYWORD:
                return this.keyword(char);
            case QUOTED:
                return this.quoted(char);
            case AFTERQUOTE:
                return this.afterquote(char);
            case NUMBER:
                return this.number(char);
            case ENDED:
                return;
        }
    };
    Parser.prototype.afterquote = function (char) {
        if (char === '"') {
            this.word += '"';
            this.state = QUOTED;
            return;
        }
        if (endThings.test(char)) {
            this.word = this.word.trim();
            this.afterItem(char);
            return;
        }
        throw new Error('havn\'t handled "' + char + '" in afterquote yet, index ' + this.place);
    };
    Parser.prototype.afterItem = function (char) {
        if (char === ',') {
            if (this.word !== null) {
                this.currentObject.push(this.word);
            }
            this.word = null;
            this.state = NEUTRAL;
            return;
        }
        if (char === ']') {
            this.level--;
            if (this.word !== null) {
                this.currentObject.push(this.word);
                this.word = null;
            }
            this.state = NEUTRAL;
            this.currentObject = this.stack.pop();
            if (!this.currentObject) {
                this.state = ENDED;
            }
            return;
        }
    };
    Parser.prototype.number = function (char) {
        if (digets.test(char)) {
            this.word += char;
            return;
        }
        if (endThings.test(char)) {
            this.word = parseFloat(this.word);
            this.afterItem(char);
            return;
        }
        throw new Error('havn\'t handled "' + char + '" in number yet, index ' + this.place);
    };
    Parser.prototype.quoted = function (char) {
        if (char === '"') {
            this.state = AFTERQUOTE;
            return;
        }
        this.word += char;
        return;
    };
    Parser.prototype.keyword = function (char) {
        if (keyword.test(char)) {
            this.word += char;
            return;
        }
        if (char === '[') {
            var newObjects = [];
            newObjects.push(this.word);
            this.level++;
            if (this.root === null) {
                this.root = newObjects;
            }
            else {
                this.currentObject.push(newObjects);
            }
            this.stack.push(this.currentObject);
            this.currentObject = newObjects;
            this.state = NEUTRAL;
            return;
        }
        if (endThings.test(char)) {
            this.afterItem(char);
            return;
        }
        throw new Error('havn\'t handled "' + char + '" in keyword yet, index ' + this.place);
    };
    Parser.prototype.neutral = function (char) {
        if (latin.test(char)) {
            this.word = char;
            this.state = KEYWORD;
            return;
        }
        if (char === '"') {
            this.word = '';
            this.state = QUOTED;
            return;
        }
        if (digets.test(char)) {
            this.word = char;
            this.state = NUMBER;
            return;
        }
        if (endThings.test(char)) {
            this.afterItem(char);
            return;
        }
        throw new Error('havn\'t handled "' + char + '" in neutral yet, index ' + this.place);
    };
    Parser.prototype.output = function () {
        while (this.place < this.text.length) {
            this.readCharicter();
        }
        if (this.state === ENDED) {
            return this.root;
        }
        throw new Error('unable to parse string "' + this.text + '". State is ' + this.state);
    };
    function parseString(txt) {
        var parser = new Parser(txt);
        return parser.output();
    }
},
/* wkt-parser/process.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function mapit(obj, key, value) {
        if (Array.isArray(key)) {
            value.unshift(key);
            key = null;
        }
        var thing = key ? {} : obj;
        var out = value.reduce(function (newObj, item) {
            sExpr(item, newObj);
            return newObj;
        }, thing);
        if (key) {
            obj[key] = out;
        }
    }
    function sExpr(v, obj) {
        if (!Array.isArray(v)) {
            obj[v] = true;
            return;
        }
        var key = v.shift();
        if (key === 'PARAMETER') {
            key = v.shift();
        }
        if (v.length === 1) {
            if (Array.isArray(v[0])) {
                obj[key] = {};
                sExpr(v[0], obj[key]);
                return;
            }
            obj[key] = v[0];
            return;
        }
        if (!v.length) {
            obj[key] = true;
            return;
        }
        if (key === 'TOWGS84') {
            obj[key] = v;
            return;
        }
        if (key === 'AXIS') {
            if (!(key in obj)) {
                obj[key] = [];
            }
            obj[key].push(v);
            return;
        }
        if (!Array.isArray(key)) {
            obj[key] = {};
        }
        var i;
        switch (key) {
            case 'UNIT':
            case 'PRIMEM':
            case 'VERT_DATUM':
                obj[key] = {
                    name: v[0].toLowerCase(),
                    convert: v[1]
                };
                if (v.length === 3) {
                    sExpr(v[2], obj[key]);
                }
                return;
            case 'SPHEROID':
            case 'ELLIPSOID':
                obj[key] = {
                    name: v[0],
                    a: v[1],
                    rf: v[2]
                };
                if (v.length === 4) {
                    sExpr(v[3], obj[key]);
                }
                return;
            case 'PROJECTEDCRS':
            case 'PROJCRS':
            case 'GEOGCS':
            case 'GEOCCS':
            case 'PROJCS':
            case 'LOCAL_CS':
            case 'GEODCRS':
            case 'GEODETICCRS':
            case 'GEODETICDATUM':
            case 'EDATUM':
            case 'ENGINEERINGDATUM':
            case 'VERT_CS':
            case 'VERTCRS':
            case 'VERTICALCRS':
            case 'COMPD_CS':
            case 'COMPOUNDCRS':
            case 'ENGINEERINGCRS':
            case 'ENGCRS':
            case 'FITTED_CS':
            case 'LOCAL_DATUM':
            case 'DATUM':
                v[0] = ['name', v[0]];
                mapit(obj, key, v);
                return;
            default:
                i = -1;
                while (++i < v.length) {
                    if (!Array.isArray(v[i])) {
                        return sExpr(v, obj[key]);
                    }
                }
                return mapit(obj, key, v);
        }
    }
    exports.sExpr = sExpr;
},
/* proj4/lib/extend.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function default_1(destination, source) {
        destination = destination || {};
        var value, property;
        if (!source) {
            return destination;
        }
        for (property in source) {
            value = source[property];
            if (value !== undefined) {
                destination[property] = value;
            }
        }
        return destination;
    }
    exports.default = default_1;
},
/* proj4/lib/projections.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var merc_1 = (0, tslib_1.__importDefault)(require(209) /* ./projections/merc */);
    var longlat_1 = (0, tslib_1.__importDefault)(require(215) /* ./projections/longlat */);
    var projs = [merc_1.default, longlat_1.default];
    var names = {};
    var projStore = [];
    function add(proj, i) {
        var len = projStore.length;
        if (!proj.names) {
            console.log(i);
            return true;
        }
        projStore[len] = proj;
        proj.names.forEach(function (n) {
            names[n.toLowerCase()] = len;
        });
        return this;
    }
    exports.add = add;
    function get(name) {
        if (!name) {
            return false;
        }
        var n = name.toLowerCase();
        if (typeof names[n] !== 'undefined' && projStore[names[n]]) {
            return projStore[names[n]];
        }
    }
    exports.get = get;
    function start() {
        projs.forEach(add);
    }
    exports.start = start;
    exports.default = {
        start: start,
        add: add,
        get: get
    };
},
/* proj4/lib/projections/merc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var msfnz_1 = (0, tslib_1.__importDefault)(require(210) /* ../common/msfnz */);
    var adjust_lon_1 = (0, tslib_1.__importDefault)(require(211) /* ../common/adjust_lon */);
    var tsfnz_1 = (0, tslib_1.__importDefault)(require(213) /* ../common/tsfnz */);
    var phi2z_1 = (0, tslib_1.__importDefault)(require(214) /* ../common/phi2z */);
    var values_1 = require(200) /* ../constants/values */;
    function init() {
        var con = this.b / this.a;
        this.es = 1 - con * con;
        if (!('x0' in this)) {
            this.x0 = 0;
        }
        if (!('y0' in this)) {
            this.y0 = 0;
        }
        this.e = Math.sqrt(this.es);
        if (this.lat_ts) {
            if (this.sphere) {
                this.k0 = Math.cos(this.lat_ts);
            }
            else {
                this.k0 = (0, msfnz_1.default)(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
            }
        }
        else {
            if (!this.k0) {
                if (this.k) {
                    this.k0 = this.k;
                }
                else {
                    this.k0 = 1;
                }
            }
        }
    }
    exports.init = init;
    /* Mercator forward equations--mapping lat,long to x,y
      --------------------------------------------------*/
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        // convert to radians
        if (lat * values_1.R2D > 90 && lat * values_1.R2D < -90 && lon * values_1.R2D > 180 && lon * values_1.R2D < -180) {
            return null;
        }
        var x, y;
        if (Math.abs(Math.abs(lat) - values_1.HALF_PI) <= values_1.EPSLN) {
            return null;
        }
        else {
            if (this.sphere) {
                x = this.x0 + this.a * this.k0 * (0, adjust_lon_1.default)(lon - this.long0);
                y = this.y0 + this.a * this.k0 * Math.log(Math.tan(values_1.FORTPI + 0.5 * lat));
            }
            else {
                var sinphi = Math.sin(lat);
                var ts = (0, tsfnz_1.default)(this.e, lat, sinphi);
                x = this.x0 + this.a * this.k0 * (0, adjust_lon_1.default)(lon - this.long0);
                y = this.y0 - this.a * this.k0 * Math.log(ts);
            }
            p.x = x;
            p.y = y;
            return p;
        }
    }
    exports.forward = forward;
    /* Mercator inverse equations--mapping x,y to lat/long
      --------------------------------------------------*/
    function inverse(p) {
        var x = p.x - this.x0;
        var y = p.y - this.y0;
        var lon, lat;
        if (this.sphere) {
            lat = values_1.HALF_PI - 2 * Math.atan(Math.exp(-y / (this.a * this.k0)));
        }
        else {
            var ts = Math.exp(-y / (this.a * this.k0));
            lat = (0, phi2z_1.default)(this.e, ts);
            if (lat === -9999) {
                return null;
            }
        }
        lon = (0, adjust_lon_1.default)(this.long0 + x / (this.a * this.k0));
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.inverse = inverse;
    exports.names = ["Mercator", "Popular Visualisation Pseudo Mercator", "Mercator_1SP", "Mercator_Auxiliary_Sphere", "merc"];
    exports.default = {
        init: init,
        forward: forward,
        inverse: inverse,
        names: exports.names
    };
},
/* proj4/lib/common/msfnz.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function default_1(eccent, sinphi, cosphi) {
        var con = eccent * sinphi;
        return cosphi / (Math.sqrt(1 - con * con));
    }
    exports.default = default_1;
},
/* proj4/lib/common/adjust_lon.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var values_1 = require(200) /* ../constants/values */;
    var sign_1 = (0, tslib_1.__importDefault)(require(212) /* ./sign */);
    function default_1(x) {
        return (Math.abs(x) <= values_1.SPI) ? x : (x - ((0, sign_1.default)(x) * values_1.TWO_PI));
    }
    exports.default = default_1;
},
/* proj4/lib/common/sign.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function default_1(x) {
        return x < 0 ? -1 : 1;
    }
    exports.default = default_1;
},
/* proj4/lib/common/tsfnz.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var values_1 = require(200) /* ../constants/values */;
    function default_1(eccent, phi, sinphi) {
        var con = eccent * sinphi;
        var com = 0.5 * eccent;
        con = Math.pow(((1 - con) / (1 + con)), com);
        return (Math.tan(0.5 * (values_1.HALF_PI - phi)) / con);
    }
    exports.default = default_1;
},
/* proj4/lib/common/phi2z.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var values_1 = require(200) /* ../constants/values */;
    function default_1(eccent, ts) {
        var eccnth = 0.5 * eccent;
        var con, dphi;
        var phi = values_1.HALF_PI - 2 * Math.atan(ts);
        for (var i = 0; i <= 15; i++) {
            con = eccent * Math.sin(phi);
            dphi = values_1.HALF_PI - 2 * Math.atan(ts * (Math.pow(((1 - con) / (1 + con)), eccnth))) - phi;
            phi += dphi;
            if (Math.abs(dphi) <= 0.0000000001) {
                return phi;
            }
        }
        //console.log("phi2z has NoConvergence");
        return -9999;
    }
    exports.default = default_1;
},
/* proj4/lib/projections/longlat.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function init() {
        //no-op for longlat
    }
    exports.init = init;
    function identity(pt) {
        return pt;
    }
    exports.forward = identity;
    exports.inverse = identity;
    exports.names = ["longlat", "identity"];
    exports.default = {
        init: init,
        forward: identity,
        inverse: identity,
        names: exports.names
    };
},
/* proj4/lib/deriveConstants.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var values_1 = require(200) /* ./constants/values */;
    var Ellipsoid_1 = (0, tslib_1.__importStar)(require(217) /* ./constants/Ellipsoid */);
    var match_1 = (0, tslib_1.__importDefault)(require(203) /* ./match */);
    function eccentricity(a, b, rf, R_A) {
        var a2 = a * a; // used in geocentric
        var b2 = b * b; // used in geocentric
        var es = (a2 - b2) / a2; // e ^ 2
        var e = 0;
        if (R_A) {
            a *= 1 - es * (values_1.SIXTH + es * (values_1.RA4 + es * values_1.RA6));
            a2 = a * a;
            es = 0;
        }
        else {
            e = Math.sqrt(es); // eccentricity
        }
        var ep2 = (a2 - b2) / b2; // used in geocentric
        return {
            es: es,
            e: e,
            ep2: ep2
        };
    }
    exports.eccentricity = eccentricity;
    function sphere(a, b, rf, ellps, sphere) {
        if (!a) { // do we have an ellipsoid?
            var ellipse = (0, match_1.default)(Ellipsoid_1.default, ellps);
            if (!ellipse) {
                ellipse = Ellipsoid_1.WGS84;
            }
            a = ellipse.a;
            b = ellipse.b;
            rf = ellipse.rf;
        }
        if (rf && !b) {
            b = (1.0 - 1.0 / rf) * a;
        }
        if (rf === 0 || Math.abs(a - b) < values_1.EPSLN) {
            sphere = true;
            b = a;
        }
        return {
            a: a,
            b: b,
            rf: rf,
            sphere: sphere
        };
    }
    exports.sphere = sphere;
},
/* proj4/lib/constants/Ellipsoid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var exports$1 = {};
    exports.default = exports$1;
    exports$1.MERIT = {
        a: 6378137.0,
        rf: 298.257,
        ellipseName: "MERIT 1983"
    };
    exports$1.SGS85 = {
        a: 6378136.0,
        rf: 298.257,
        ellipseName: "Soviet Geodetic System 85"
    };
    exports$1.GRS80 = {
        a: 6378137.0,
        rf: 298.257222101,
        ellipseName: "GRS 1980(IUGG, 1980)"
    };
    exports$1.IAU76 = {
        a: 6378140.0,
        rf: 298.257,
        ellipseName: "IAU 1976"
    };
    exports$1.airy = {
        a: 6377563.396,
        b: 6356256.910,
        ellipseName: "Airy 1830"
    };
    exports$1.APL4 = {
        a: 6378137,
        rf: 298.25,
        ellipseName: "Appl. Physics. 1965"
    };
    exports$1.NWL9D = {
        a: 6378145.0,
        rf: 298.25,
        ellipseName: "Naval Weapons Lab., 1965"
    };
    exports$1.mod_airy = {
        a: 6377340.189,
        b: 6356034.446,
        ellipseName: "Modified Airy"
    };
    exports$1.andrae = {
        a: 6377104.43,
        rf: 300.0,
        ellipseName: "Andrae 1876 (Den., Iclnd.)"
    };
    exports$1.aust_SA = {
        a: 6378160.0,
        rf: 298.25,
        ellipseName: "Australian Natl & S. Amer. 1969"
    };
    exports$1.GRS67 = {
        a: 6378160.0,
        rf: 298.2471674270,
        ellipseName: "GRS 67(IUGG 1967)"
    };
    exports$1.bessel = {
        a: 6377397.155,
        rf: 299.1528128,
        ellipseName: "Bessel 1841"
    };
    exports$1.bess_nam = {
        a: 6377483.865,
        rf: 299.1528128,
        ellipseName: "Bessel 1841 (Namibia)"
    };
    exports$1.clrk66 = {
        a: 6378206.4,
        b: 6356583.8,
        ellipseName: "Clarke 1866"
    };
    exports$1.clrk80 = {
        a: 6378249.145,
        rf: 293.4663,
        ellipseName: "Clarke 1880 mod."
    };
    exports$1.clrk58 = {
        a: 6378293.645208759,
        rf: 294.2606763692654,
        ellipseName: "Clarke 1858"
    };
    exports$1.CPM = {
        a: 6375738.7,
        rf: 334.29,
        ellipseName: "Comm. des Poids et Mesures 1799"
    };
    exports$1.delmbr = {
        a: 6376428.0,
        rf: 311.5,
        ellipseName: "Delambre 1810 (Belgium)"
    };
    exports$1.engelis = {
        a: 6378136.05,
        rf: 298.2566,
        ellipseName: "Engelis 1985"
    };
    exports$1.evrst30 = {
        a: 6377276.345,
        rf: 300.8017,
        ellipseName: "Everest 1830"
    };
    exports$1.evrst48 = {
        a: 6377304.063,
        rf: 300.8017,
        ellipseName: "Everest 1948"
    };
    exports$1.evrst56 = {
        a: 6377301.243,
        rf: 300.8017,
        ellipseName: "Everest 1956"
    };
    exports$1.evrst69 = {
        a: 6377295.664,
        rf: 300.8017,
        ellipseName: "Everest 1969"
    };
    exports$1.evrstSS = {
        a: 6377298.556,
        rf: 300.8017,
        ellipseName: "Everest (Sabah & Sarawak)"
    };
    exports$1.fschr60 = {
        a: 6378166.0,
        rf: 298.3,
        ellipseName: "Fischer (Mercury Datum) 1960"
    };
    exports$1.fschr60m = {
        a: 6378155.0,
        rf: 298.3,
        ellipseName: "Fischer 1960"
    };
    exports$1.fschr68 = {
        a: 6378150.0,
        rf: 298.3,
        ellipseName: "Fischer 1968"
    };
    exports$1.helmert = {
        a: 6378200.0,
        rf: 298.3,
        ellipseName: "Helmert 1906"
    };
    exports$1.hough = {
        a: 6378270.0,
        rf: 297.0,
        ellipseName: "Hough"
    };
    exports$1.intl = {
        a: 6378388.0,
        rf: 297.0,
        ellipseName: "International 1909 (Hayford)"
    };
    exports$1.kaula = {
        a: 6378163.0,
        rf: 298.24,
        ellipseName: "Kaula 1961"
    };
    exports$1.lerch = {
        a: 6378139.0,
        rf: 298.257,
        ellipseName: "Lerch 1979"
    };
    exports$1.mprts = {
        a: 6397300.0,
        rf: 191.0,
        ellipseName: "Maupertius 1738"
    };
    exports$1.new_intl = {
        a: 6378157.5,
        b: 6356772.2,
        ellipseName: "New International 1967"
    };
    exports$1.plessis = {
        a: 6376523.0,
        rf: 6355863.0,
        ellipseName: "Plessis 1817 (France)"
    };
    exports$1.krass = {
        a: 6378245.0,
        rf: 298.3,
        ellipseName: "Krassovsky, 1942"
    };
    exports$1.SEasia = {
        a: 6378155.0,
        b: 6356773.3205,
        ellipseName: "Southeast Asia"
    };
    exports$1.walbeck = {
        a: 6376896.0,
        b: 6355834.8467,
        ellipseName: "Walbeck"
    };
    exports$1.WGS60 = {
        a: 6378165.0,
        rf: 298.3,
        ellipseName: "WGS 60"
    };
    exports$1.WGS66 = {
        a: 6378145.0,
        rf: 298.25,
        ellipseName: "WGS 66"
    };
    exports$1.WGS7 = {
        a: 6378135.0,
        rf: 298.26,
        ellipseName: "WGS 72"
    };
    exports.WGS84 = exports$1.WGS84 = {
        a: 6378137.0,
        rf: 298.257223563,
        ellipseName: "WGS 84"
    };
    exports$1.sphere = {
        a: 6370997.0,
        b: 6370997.0,
        ellipseName: "Normal Sphere (r=6370997)"
    };
},
/* proj4/lib/constants/Datum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var exports$1 = {};
    exports.default = exports$1;
    exports$1.wgs84 = {
        towgs84: "0,0,0",
        ellipse: "WGS84",
        datumName: "WGS84"
    };
    exports$1.ch1903 = {
        towgs84: "674.374,15.056,405.346",
        ellipse: "bessel",
        datumName: "swiss"
    };
    exports$1.ggrs87 = {
        towgs84: "-199.87,74.79,246.62",
        ellipse: "GRS80",
        datumName: "Greek_Geodetic_Reference_System_1987"
    };
    exports$1.nad83 = {
        towgs84: "0,0,0",
        ellipse: "GRS80",
        datumName: "North_American_Datum_1983"
    };
    exports$1.nad27 = {
        nadgrids: "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",
        ellipse: "clrk66",
        datumName: "North_American_Datum_1927"
    };
    exports$1.potsdam = {
        towgs84: "598.1,73.7,418.2,0.202,0.045,-2.455,6.7",
        ellipse: "bessel",
        datumName: "Potsdam Rauenberg 1950 DHDN"
    };
    exports$1.carthage = {
        towgs84: "-263.0,6.0,431.0",
        ellipse: "clark80",
        datumName: "Carthage 1934 Tunisia"
    };
    exports$1.hermannskogel = {
        towgs84: "577.326,90.129,463.919,5.137,1.474,5.297,2.4232",
        ellipse: "bessel",
        datumName: "Hermannskogel"
    };
    exports$1.osni52 = {
        towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",
        ellipse: "airy",
        datumName: "Irish National"
    };
    exports$1.ire65 = {
        towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",
        ellipse: "mod_airy",
        datumName: "Ireland 1965"
    };
    exports$1.rassadiran = {
        towgs84: "-133.63,-157.5,-158.62",
        ellipse: "intl",
        datumName: "Rassadiran"
    };
    exports$1.nzgd49 = {
        towgs84: "59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993",
        ellipse: "intl",
        datumName: "New Zealand Geodetic Datum 1949"
    };
    exports$1.osgb36 = {
        towgs84: "446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894",
        ellipse: "airy",
        datumName: "Airy 1830"
    };
    exports$1.s_jtsk = {
        towgs84: "589,76,480",
        ellipse: 'bessel',
        datumName: 'S-JTSK (Ferro)'
    };
    exports$1.beduaram = {
        towgs84: '-106,-87,188',
        ellipse: 'clrk80',
        datumName: 'Beduaram'
    };
    exports$1.gunung_segara = {
        towgs84: '-403,684,41',
        ellipse: 'bessel',
        datumName: 'Gunung Segara Jakarta'
    };
    exports$1.rnb72 = {
        towgs84: "106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1",
        ellipse: "intl",
        datumName: "Reseau National Belge 1972"
    };
},
/* proj4/lib/datum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var values_1 = require(200) /* ./constants/values */;
    function datum(datumCode, datum_params, a, b, es, ep2, nadgrids) {
        var out = {};
        if (datumCode === undefined || datumCode === 'none') {
            out.datum_type = values_1.PJD_NODATUM;
        }
        else {
            out.datum_type = values_1.PJD_WGS84;
        }
        if (datum_params) {
            out.datum_params = datum_params.map(parseFloat);
            if (out.datum_params[0] !== 0 || out.datum_params[1] !== 0 || out.datum_params[2] !== 0) {
                out.datum_type = values_1.PJD_3PARAM;
            }
            if (out.datum_params.length > 3) {
                if (out.datum_params[3] !== 0 || out.datum_params[4] !== 0 || out.datum_params[5] !== 0 || out.datum_params[6] !== 0) {
                    out.datum_type = values_1.PJD_7PARAM;
                    out.datum_params[3] *= values_1.SEC_TO_RAD;
                    out.datum_params[4] *= values_1.SEC_TO_RAD;
                    out.datum_params[5] *= values_1.SEC_TO_RAD;
                    out.datum_params[6] = (out.datum_params[6] / 1000000.0) + 1.0;
                }
            }
        }
        if (nadgrids) {
            out.datum_type = values_1.PJD_GRIDSHIFT;
            out.grids = nadgrids;
        }
        out.a = a; //datum object also uses these values
        out.b = b;
        out.es = es;
        out.ep2 = ep2;
        return out;
    }
    exports.default = datum;
},
/* proj4/lib/nadgrid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var loadedNadgrids = {};
    /**
     * Load a binary NTv2 file (.gsb) to a key that can be used in a proj string like +nadgrids=<key>. Pass the NTv2 file
     * as an ArrayBuffer.
     */
    function nadgrid(key, data) {
        var view = new DataView(data);
        var isLittleEndian = detectLittleEndian(view);
        var header = readHeader(view, isLittleEndian);
        if (header.nSubgrids > 1) {
            console.log('Only single NTv2 subgrids are currently supported, subsequent sub grids are ignored');
        }
        var subgrids = readSubgrids(view, header, isLittleEndian);
        var nadgrid = { header: header, subgrids: subgrids };
        loadedNadgrids[key] = nadgrid;
        return nadgrid;
    }
    exports.default = nadgrid;
    /**
     * Given a proj4 value for nadgrids, return an array of loaded grids
     */
    function getNadgrids(nadgrids) {
        // Format details: http://proj.maptools.org/gen_parms.html
        if (nadgrids === undefined) {
            return null;
        }
        var grids = nadgrids.split(',');
        return grids.map(parseNadgridString);
    }
    exports.getNadgrids = getNadgrids;
    function parseNadgridString(value) {
        if (value.length === 0) {
            return null;
        }
        var optional = value[0] === '@';
        if (optional) {
            value = value.slice(1);
        }
        if (value === 'null') {
            return { name: 'null', mandatory: !optional, grid: null, isNull: true };
        }
        return {
            name: value,
            mandatory: !optional,
            grid: loadedNadgrids[value] || null,
            isNull: false
        };
    }
    function secondsToRadians(seconds) {
        return (seconds / 3600) * Math.PI / 180;
    }
    function detectLittleEndian(view) {
        var nFields = view.getInt32(8, false);
        if (nFields === 11) {
            return false;
        }
        nFields = view.getInt32(8, true);
        if (nFields !== 11) {
            console.warn('Failed to detect nadgrid endian-ness, defaulting to little-endian');
        }
        return true;
    }
    function readHeader(view, isLittleEndian) {
        return {
            nFields: view.getInt32(8, isLittleEndian),
            nSubgridFields: view.getInt32(24, isLittleEndian),
            nSubgrids: view.getInt32(40, isLittleEndian),
            shiftType: decodeString(view, 56, 56 + 8).trim(),
            fromSemiMajorAxis: view.getFloat64(120, isLittleEndian),
            fromSemiMinorAxis: view.getFloat64(136, isLittleEndian),
            toSemiMajorAxis: view.getFloat64(152, isLittleEndian),
            toSemiMinorAxis: view.getFloat64(168, isLittleEndian),
        };
    }
    function decodeString(view, start, end) {
        return String.fromCharCode.apply(null, new Uint8Array(view.buffer.slice(start, end)));
    }
    function readSubgrids(view, header, isLittleEndian) {
        var gridOffset = 176;
        var grids = [];
        for (var i = 0; i < header.nSubgrids; i++) {
            var subHeader = readGridHeader(view, gridOffset, isLittleEndian);
            var nodes = readGridNodes(view, gridOffset, subHeader, isLittleEndian);
            var lngColumnCount = Math.round(1 + (subHeader.upperLongitude - subHeader.lowerLongitude) / subHeader.longitudeInterval);
            var latColumnCount = Math.round(1 + (subHeader.upperLatitude - subHeader.lowerLatitude) / subHeader.latitudeInterval);
            // Proj4 operates on radians whereas the coordinates are in seconds in the grid
            grids.push({
                ll: [secondsToRadians(subHeader.lowerLongitude), secondsToRadians(subHeader.lowerLatitude)],
                del: [secondsToRadians(subHeader.longitudeInterval), secondsToRadians(subHeader.latitudeInterval)],
                lim: [lngColumnCount, latColumnCount],
                count: subHeader.gridNodeCount,
                cvs: mapNodes(nodes)
            });
        }
        return grids;
    }
    function mapNodes(nodes) {
        return nodes.map(function (r) { return [secondsToRadians(r.longitudeShift), secondsToRadians(r.latitudeShift)]; });
    }
    function readGridHeader(view, offset, isLittleEndian) {
        return {
            name: decodeString(view, offset + 8, offset + 16).trim(),
            parent: decodeString(view, offset + 24, offset + 24 + 8).trim(),
            lowerLatitude: view.getFloat64(offset + 72, isLittleEndian),
            upperLatitude: view.getFloat64(offset + 88, isLittleEndian),
            lowerLongitude: view.getFloat64(offset + 104, isLittleEndian),
            upperLongitude: view.getFloat64(offset + 120, isLittleEndian),
            latitudeInterval: view.getFloat64(offset + 136, isLittleEndian),
            longitudeInterval: view.getFloat64(offset + 152, isLittleEndian),
            gridNodeCount: view.getInt32(offset + 168, isLittleEndian)
        };
    }
    function readGridNodes(view, offset, gridHeader, isLittleEndian) {
        var nodesOffset = offset + 176;
        var gridRecordLength = 16;
        var gridShiftRecords = [];
        for (var i = 0; i < gridHeader.gridNodeCount; i++) {
            var record = {
                latitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength, isLittleEndian),
                longitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength + 4, isLittleEndian),
                latitudeAccuracy: view.getFloat32(nodesOffset + i * gridRecordLength + 8, isLittleEndian),
                longitudeAccuracy: view.getFloat32(nodesOffset + i * gridRecordLength + 12, isLittleEndian),
            };
            gridShiftRecords.push(record);
        }
        return gridShiftRecords;
    }
},
/* proj4/lib/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var values_1 = require(200) /* ./constants/values */;
    var datum_transform_1 = (0, tslib_1.__importDefault)(require(222) /* ./datum_transform */);
    var adjust_axis_1 = (0, tslib_1.__importDefault)(require(224) /* ./adjust_axis */);
    var Proj_1 = (0, tslib_1.__importDefault)(require(195) /* ./Proj */);
    var toPoint_1 = (0, tslib_1.__importDefault)(require(225) /* ./common/toPoint */);
    var checkSanity_1 = (0, tslib_1.__importDefault)(require(226) /* ./checkSanity */);
    function checkNotWGS(source, dest) {
        return ((source.datum.datum_type === values_1.PJD_3PARAM || source.datum.datum_type === values_1.PJD_7PARAM) && dest.datumCode !== 'WGS84') || ((dest.datum.datum_type === values_1.PJD_3PARAM || dest.datum.datum_type === values_1.PJD_7PARAM) && source.datumCode !== 'WGS84');
    }
    function transform(source, dest, point, enforceAxis) {
        var wgs84;
        if (Array.isArray(point)) {
            point = (0, toPoint_1.default)(point);
        }
        (0, checkSanity_1.default)(point);
        // Workaround for datum shifts towgs84, if either source or destination projection is not wgs84
        if (source.datum && dest.datum && checkNotWGS(source, dest)) {
            wgs84 = new Proj_1.default('WGS84');
            point = transform(source, wgs84, point, enforceAxis);
            source = wgs84;
        }
        // DGR, 2010/11/12
        if (enforceAxis && source.axis !== 'enu') {
            point = (0, adjust_axis_1.default)(source, false, point);
        }
        // Transform source points to long/lat, if they aren't already.
        if (source.projName === 'longlat') {
            point = {
                x: point.x * values_1.D2R,
                y: point.y * values_1.D2R,
                z: point.z || 0
            };
        }
        else {
            if (source.to_meter) {
                point = {
                    x: point.x * source.to_meter,
                    y: point.y * source.to_meter,
                    z: point.z || 0
                };
            }
            point = source.inverse(point); // Convert Cartesian to longlat
            if (!point) {
                return;
            }
        }
        // Adjust for the prime meridian if necessary
        if (source.from_greenwich) {
            point.x += source.from_greenwich;
        }
        // Convert datums if needed, and if possible.
        point = (0, datum_transform_1.default)(source.datum, dest.datum, point);
        if (!point) {
            return;
        }
        // Adjust for the prime meridian if necessary
        if (dest.from_greenwich) {
            point = {
                x: point.x - dest.from_greenwich,
                y: point.y,
                z: point.z || 0
            };
        }
        if (dest.projName === 'longlat') {
            // convert radians to decimal degrees
            point = {
                x: point.x * values_1.R2D,
                y: point.y * values_1.R2D,
                z: point.z || 0
            };
        }
        else { // else project
            point = dest.forward(point);
            if (dest.to_meter) {
                point = {
                    x: point.x / dest.to_meter,
                    y: point.y / dest.to_meter,
                    z: point.z || 0
                };
            }
        }
        // DGR, 2010/11/12
        if (enforceAxis && dest.axis !== 'enu') {
            return (0, adjust_axis_1.default)(dest, true, point);
        }
        return point;
    }
    exports.default = transform;
},
/* proj4/lib/datum_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var values_1 = require(200) /* ./constants/values */;
    var datumUtils_1 = require(223) /* ./datumUtils */;
    var adjust_lon_1 = (0, tslib_1.__importDefault)(require(211) /* ./common/adjust_lon */);
    function checkParams(type) {
        return (type === values_1.PJD_3PARAM || type === values_1.PJD_7PARAM);
    }
    function default_1(source, dest, point) {
        // Short cut if the datums are identical.
        if ((0, datumUtils_1.compareDatums)(source, dest)) {
            return point; // in this case, zero is sucess,
            // whereas cs_compare_datums returns 1 to indicate TRUE
            // confusing, should fix this
        }
        // Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest
        if (source.datum_type === values_1.PJD_NODATUM || dest.datum_type === values_1.PJD_NODATUM) {
            return point;
        }
        // If this datum requires grid shifts, then apply it to geodetic coordinates.
        var source_a = source.a;
        var source_es = source.es;
        if (source.datum_type === values_1.PJD_GRIDSHIFT) {
            var gridShiftCode = applyGridShift(source, false, point);
            if (gridShiftCode !== 0) {
                return undefined;
            }
            source_a = values_1.SRS_WGS84_SEMIMAJOR;
            source_es = values_1.SRS_WGS84_ESQUARED;
        }
        var dest_a = dest.a;
        var dest_b = dest.b;
        var dest_es = dest.es;
        if (dest.datum_type === values_1.PJD_GRIDSHIFT) {
            dest_a = values_1.SRS_WGS84_SEMIMAJOR;
            dest_b = values_1.SRS_WGS84_SEMIMINOR;
            dest_es = values_1.SRS_WGS84_ESQUARED;
        }
        // Do we need to go through geocentric coordinates?
        if (source_es === dest_es && source_a === dest_a && !checkParams(source.datum_type) && !checkParams(dest.datum_type)) {
            return point;
        }
        // Convert to geocentric coordinates.
        point = (0, datumUtils_1.geodeticToGeocentric)(point, source_es, source_a);
        // Convert between datums
        if (checkParams(source.datum_type)) {
            point = (0, datumUtils_1.geocentricToWgs84)(point, source.datum_type, source.datum_params);
        }
        if (checkParams(dest.datum_type)) {
            point = (0, datumUtils_1.geocentricFromWgs84)(point, dest.datum_type, dest.datum_params);
        }
        point = (0, datumUtils_1.geocentricToGeodetic)(point, dest_es, dest_a, dest_b);
        if (dest.datum_type === values_1.PJD_GRIDSHIFT) {
            var destGridShiftResult = applyGridShift(dest, true, point);
            if (destGridShiftResult !== 0) {
                return undefined;
            }
        }
        return point;
    }
    exports.default = default_1;
    function applyGridShift(source, inverse, point) {
        if (source.grids === null || source.grids.length === 0) {
            console.log('Grid shift grids not found');
            return -1;
        }
        var input = { x: -point.x, y: point.y };
        var output = { x: Number.NaN, y: Number.NaN };
        var onlyMandatoryGrids = false;
        var attemptedGrids = [];
        for (var i = 0; i < source.grids.length; i++) {
            var grid = source.grids[i];
            attemptedGrids.push(grid.name);
            if (grid.isNull) {
                output = input;
                break;
            }
            onlyMandatoryGrids = grid.mandatory;
            if (grid.grid === null) {
                if (grid.mandatory) {
                    console.log("Unable to find mandatory grid '" + grid.name + "'");
                    return -1;
                }
                continue;
            }
            var subgrid = grid.grid.subgrids[0];
            // skip tables that don't match our point at all
            var epsilon = (Math.abs(subgrid.del[1]) + Math.abs(subgrid.del[0])) / 10000.0;
            var minX = subgrid.ll[0] - epsilon;
            var minY = subgrid.ll[1] - epsilon;
            var maxX = subgrid.ll[0] + (subgrid.lim[0] - 1) * subgrid.del[0] + epsilon;
            var maxY = subgrid.ll[1] + (subgrid.lim[1] - 1) * subgrid.del[1] + epsilon;
            if (minY > input.y || minX > input.x || maxY < input.y || maxX < input.x) {
                continue;
            }
            output = applySubgridShift(input, inverse, subgrid);
            if (!isNaN(output.x)) {
                break;
            }
        }
        if (isNaN(output.x)) {
            console.log("Failed to find a grid shift table for location '" +
                -input.x * values_1.R2D + " " + input.y * values_1.R2D + " tried: '" + attemptedGrids + "'");
            return -1;
        }
        point.x = -output.x;
        point.y = output.y;
        return 0;
    }
    exports.applyGridShift = applyGridShift;
    function applySubgridShift(pin, inverse, ct) {
        var val = { x: Number.NaN, y: Number.NaN };
        if (isNaN(pin.x)) {
            return val;
        }
        var tb = { x: pin.x, y: pin.y };
        tb.x -= ct.ll[0];
        tb.y -= ct.ll[1];
        tb.x = (0, adjust_lon_1.default)(tb.x - Math.PI) + Math.PI;
        var t = nadInterpolate(tb, ct);
        if (inverse) {
            if (isNaN(t.x)) {
                return val;
            }
            t.x = tb.x - t.x;
            t.y = tb.y - t.y;
            var i = 9, tol = 1e-12;
            var dif, del;
            do {
                del = nadInterpolate(t, ct);
                if (isNaN(del.x)) {
                    console.log("Inverse grid shift iteration failed, presumably at grid edge.  Using first approximation.");
                    break;
                }
                dif = { x: tb.x - (del.x + t.x), y: tb.y - (del.y + t.y) };
                t.x += dif.x;
                t.y += dif.y;
            } while (i-- && Math.abs(dif.x) > tol && Math.abs(dif.y) > tol);
            if (i < 0) {
                console.log("Inverse grid shift iterator failed to converge.");
                return val;
            }
            val.x = (0, adjust_lon_1.default)(t.x + ct.ll[0]);
            val.y = t.y + ct.ll[1];
        }
        else {
            if (!isNaN(t.x)) {
                val.x = pin.x + t.x;
                val.y = pin.y + t.y;
            }
        }
        return val;
    }
    function nadInterpolate(pin, ct) {
        var t = { x: pin.x / ct.del[0], y: pin.y / ct.del[1] };
        var indx = { x: Math.floor(t.x), y: Math.floor(t.y) };
        var frct = { x: t.x - 1.0 * indx.x, y: t.y - 1.0 * indx.y };
        var val = { x: Number.NaN, y: Number.NaN };
        var inx;
        if (indx.x < 0 || indx.x >= ct.lim[0]) {
            return val;
        }
        if (indx.y < 0 || indx.y >= ct.lim[1]) {
            return val;
        }
        inx = (indx.y * ct.lim[0]) + indx.x;
        var f00 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx++;
        var f10 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx += ct.lim[0];
        var f11 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx--;
        var f01 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        var m11 = frct.x * frct.y, m10 = frct.x * (1.0 - frct.y), m00 = (1.0 - frct.x) * (1.0 - frct.y), m01 = (1.0 - frct.x) * frct.y;
        val.x = (m00 * f00.x + m10 * f10.x + m01 * f01.x + m11 * f11.x);
        val.y = (m00 * f00.y + m10 * f10.y + m01 * f01.y + m11 * f11.y);
        return val;
    }
},
/* proj4/lib/datumUtils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var values_1 = require(200) /* ./constants/values */;
    function compareDatums(source, dest) {
        if (source.datum_type !== dest.datum_type) {
            return false; // false, datums are not equal
        }
        else if (source.a !== dest.a || Math.abs(source.es - dest.es) > 0.000000000050) {
            // the tolerance for es is to ensure that GRS80 and WGS84
            // are considered identical
            return false;
        }
        else if (source.datum_type === values_1.PJD_3PARAM) {
            return (source.datum_params[0] === dest.datum_params[0] && source.datum_params[1] === dest.datum_params[1] && source.datum_params[2] === dest.datum_params[2]);
        }
        else if (source.datum_type === values_1.PJD_7PARAM) {
            return (source.datum_params[0] === dest.datum_params[0] && source.datum_params[1] === dest.datum_params[1] && source.datum_params[2] === dest.datum_params[2] && source.datum_params[3] === dest.datum_params[3] && source.datum_params[4] === dest.datum_params[4] && source.datum_params[5] === dest.datum_params[5] && source.datum_params[6] === dest.datum_params[6]);
        }
        else {
            return true; // datums are equal
        }
    } // cs_compare_datums()
    exports.compareDatums = compareDatums;
    /*
     * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
     * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
     * according to the current ellipsoid parameters.
     *
     *    Latitude  : Geodetic latitude in radians                     (input)
     *    Longitude : Geodetic longitude in radians                    (input)
     *    Height    : Geodetic height, in meters                       (input)
     *    X         : Calculated Geocentric X coordinate, in meters    (output)
     *    Y         : Calculated Geocentric Y coordinate, in meters    (output)
     *    Z         : Calculated Geocentric Z coordinate, in meters    (output)
     *
     */
    function geodeticToGeocentric(p, es, a) {
        var Longitude = p.x;
        var Latitude = p.y;
        var Height = p.z ? p.z : 0; //Z value not always supplied
        var Rn; /*  Earth radius at location  */
        var Sin_Lat; /*  Math.sin(Latitude)  */
        var Sin2_Lat; /*  Square of Math.sin(Latitude)  */
        var Cos_Lat; /*  Math.cos(Latitude)  */
        /*
         ** Don't blow up if Latitude is just a little out of the value
         ** range as it may just be a rounding issue.  Also removed longitude
         ** test, it should be wrapped by Math.cos() and Math.sin().  NFW for PROJ.4, Sep/2001.
         */
        if (Latitude < -values_1.HALF_PI && Latitude > -1.001 * values_1.HALF_PI) {
            Latitude = -values_1.HALF_PI;
        }
        else if (Latitude > values_1.HALF_PI && Latitude < 1.001 * values_1.HALF_PI) {
            Latitude = values_1.HALF_PI;
        }
        else if (Latitude < -values_1.HALF_PI) {
            /* Latitude out of range */
            //..reportError('geocent:lat out of range:' + Latitude);
            return { x: -Infinity, y: -Infinity, z: p.z };
        }
        else if (Latitude > values_1.HALF_PI) {
            /* Latitude out of range */
            return { x: Infinity, y: Infinity, z: p.z };
        }
        if (Longitude > Math.PI) {
            Longitude -= (2 * Math.PI);
        }
        Sin_Lat = Math.sin(Latitude);
        Cos_Lat = Math.cos(Latitude);
        Sin2_Lat = Sin_Lat * Sin_Lat;
        Rn = a / (Math.sqrt(1.0e0 - es * Sin2_Lat));
        return {
            x: (Rn + Height) * Cos_Lat * Math.cos(Longitude),
            y: (Rn + Height) * Cos_Lat * Math.sin(Longitude),
            z: ((Rn * (1 - es)) + Height) * Sin_Lat
        };
    } // cs_geodetic_to_geocentric()
    exports.geodeticToGeocentric = geodeticToGeocentric;
    function geocentricToGeodetic(p, es, a, b) {
        /* local defintions and variables */
        /* end-criterium of loop, accuracy of sin(Latitude) */
        var genau = 1e-12;
        var genau2 = (genau * genau);
        var maxiter = 30;
        var P; /* distance between semi-minor axis and location */
        var RR; /* distance between center and location */
        var CT; /* sin of geocentric latitude */
        var ST; /* cos of geocentric latitude */
        var RX;
        var RK;
        var RN; /* Earth radius at location */
        var CPHI0; /* cos of start or old geodetic latitude in iterations */
        var SPHI0; /* sin of start or old geodetic latitude in iterations */
        var CPHI; /* cos of searched geodetic latitude */
        var SPHI; /* sin of searched geodetic latitude */
        var SDPHI; /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */
        var iter; /* # of continous iteration, max. 30 is always enough (s.a.) */
        var X = p.x;
        var Y = p.y;
        var Z = p.z ? p.z : 0.0; //Z value not always supplied
        var Longitude;
        var Latitude;
        var Height;
        P = Math.sqrt(X * X + Y * Y);
        RR = Math.sqrt(X * X + Y * Y + Z * Z);
        /*      special cases for latitude and longitude */
        if (P / a < genau) {
            /*  special case, if P=0. (X=0., Y=0.) */
            Longitude = 0.0;
            /*  if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
             *  of ellipsoid (=center of mass), Latitude becomes PI/2 */
            if (RR / a < genau) {
                Latitude = values_1.HALF_PI;
                Height = -b;
                return {
                    x: p.x,
                    y: p.y,
                    z: p.z
                };
            }
        }
        else {
            /*  ellipsoidal (geodetic) longitude
             *  interval: -PI < Longitude <= +PI */
            Longitude = Math.atan2(Y, X);
        }
        /* --------------------------------------------------------------
         * Following iterative algorithm was developped by
         * "Institut for Erdmessung", University of Hannover, July 1988.
         * Internet: www.ife.uni-hannover.de
         * Iterative computation of CPHI,SPHI and Height.
         * Iteration of CPHI and SPHI to 10**-12 radian resp.
         * 2*10**-7 arcsec.
         * --------------------------------------------------------------
         */
        CT = Z / RR;
        ST = P / RR;
        RX = 1.0 / Math.sqrt(1.0 - es * (2.0 - es) * ST * ST);
        CPHI0 = ST * (1.0 - es) * RX;
        SPHI0 = CT * RX;
        iter = 0;
        /* loop to find sin(Latitude) resp. Latitude
         * until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
        do {
            iter++;
            RN = a / Math.sqrt(1.0 - es * SPHI0 * SPHI0);
            /*  ellipsoidal (geodetic) height */
            Height = P * CPHI0 + Z * SPHI0 - RN * (1.0 - es * SPHI0 * SPHI0);
            RK = es * RN / (RN + Height);
            RX = 1.0 / Math.sqrt(1.0 - RK * (2.0 - RK) * ST * ST);
            CPHI = ST * (1.0 - RK) * RX;
            SPHI = CT * RX;
            SDPHI = SPHI * CPHI0 - CPHI * SPHI0;
            CPHI0 = CPHI;
            SPHI0 = SPHI;
        } while (SDPHI * SDPHI > genau2 && iter < maxiter);
        /*      ellipsoidal (geodetic) latitude */
        Latitude = Math.atan(SPHI / Math.abs(CPHI));
        return {
            x: Longitude,
            y: Latitude,
            z: Height
        };
    } // cs_geocentric_to_geodetic()
    exports.geocentricToGeodetic = geocentricToGeodetic;
    /****************************************************************/
    // pj_geocentic_to_wgs84( p )
    //  p = point to transform in geocentric coordinates (x,y,z)
    /** point object, nothing fancy, just allows values to be
        passed back and forth by reference rather than by value.
        Other point classes may be used as long as they have
        x and y properties, which will get modified in the transform method.
    */
    function geocentricToWgs84(p, datum_type, datum_params) {
        if (datum_type === values_1.PJD_3PARAM) {
            // if( x[io] === HUGE_VAL )
            //    continue;
            return {
                x: p.x + datum_params[0],
                y: p.y + datum_params[1],
                z: p.z + datum_params[2],
            };
        }
        else if (datum_type === values_1.PJD_7PARAM) {
            var Dx_BF = datum_params[0];
            var Dy_BF = datum_params[1];
            var Dz_BF = datum_params[2];
            var Rx_BF = datum_params[3];
            var Ry_BF = datum_params[4];
            var Rz_BF = datum_params[5];
            var M_BF = datum_params[6];
            // if( x[io] === HUGE_VAL )
            //    continue;
            return {
                x: M_BF * (p.x - Rz_BF * p.y + Ry_BF * p.z) + Dx_BF,
                y: M_BF * (Rz_BF * p.x + p.y - Rx_BF * p.z) + Dy_BF,
                z: M_BF * (-Ry_BF * p.x + Rx_BF * p.y + p.z) + Dz_BF
            };
        }
    } // cs_geocentric_to_wgs84
    exports.geocentricToWgs84 = geocentricToWgs84;
    /****************************************************************/
    // pj_geocentic_from_wgs84()
    //  coordinate system definition,
    //  point to transform in geocentric coordinates (x,y,z)
    function geocentricFromWgs84(p, datum_type, datum_params) {
        if (datum_type === values_1.PJD_3PARAM) {
            //if( x[io] === HUGE_VAL )
            //    continue;
            return {
                x: p.x - datum_params[0],
                y: p.y - datum_params[1],
                z: p.z - datum_params[2],
            };
        }
        else if (datum_type === values_1.PJD_7PARAM) {
            var Dx_BF = datum_params[0];
            var Dy_BF = datum_params[1];
            var Dz_BF = datum_params[2];
            var Rx_BF = datum_params[3];
            var Ry_BF = datum_params[4];
            var Rz_BF = datum_params[5];
            var M_BF = datum_params[6];
            var x_tmp = (p.x - Dx_BF) / M_BF;
            var y_tmp = (p.y - Dy_BF) / M_BF;
            var z_tmp = (p.z - Dz_BF) / M_BF;
            //if( x[io] === HUGE_VAL )
            //    continue;
            return {
                x: x_tmp + Rz_BF * y_tmp - Ry_BF * z_tmp,
                y: -Rz_BF * x_tmp + y_tmp + Rx_BF * z_tmp,
                z: Ry_BF * x_tmp - Rx_BF * y_tmp + z_tmp
            };
        } //cs_geocentric_from_wgs84()
    }
    exports.geocentricFromWgs84 = geocentricFromWgs84;
},
/* proj4/lib/adjust_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function default_1(crs, denorm, point) {
        var xin = point.x, yin = point.y, zin = point.z || 0.0;
        var v, t, i;
        var out = {};
        for (i = 0; i < 3; i++) {
            if (denorm && i === 2 && point.z === undefined) {
                continue;
            }
            if (i === 0) {
                v = xin;
                if ("ew".indexOf(crs.axis[i]) !== -1) {
                    t = 'x';
                }
                else {
                    t = 'y';
                }
            }
            else if (i === 1) {
                v = yin;
                if ("ns".indexOf(crs.axis[i]) !== -1) {
                    t = 'y';
                }
                else {
                    t = 'x';
                }
            }
            else {
                v = zin;
                t = 'z';
            }
            switch (crs.axis[i]) {
                case 'e':
                    out[t] = v;
                    break;
                case 'w':
                    out[t] = -v;
                    break;
                case 'n':
                    out[t] = v;
                    break;
                case 's':
                    out[t] = -v;
                    break;
                case 'u':
                    if (point[t] !== undefined) {
                        out.z = v;
                    }
                    break;
                case 'd':
                    if (point[t] !== undefined) {
                        out.z = -v;
                    }
                    break;
                default:
                    //console.log("ERROR: unknow axis ("+crs.axis[i]+") - check definition of "+crs.projName);
                    return null;
            }
        }
        return out;
    }
    exports.default = default_1;
},
/* proj4/lib/common/toPoint.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function default_1(array) {
        var out = {
            x: array[0],
            y: array[1]
        };
        if (array.length > 2) {
            out.z = array[2];
        }
        if (array.length > 3) {
            out.m = array[3];
        }
        return out;
    }
    exports.default = default_1;
},
/* proj4/lib/checkSanity.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function default_1(point) {
        checkCoord(point.x);
        checkCoord(point.y);
    }
    exports.default = default_1;
    function checkCoord(num) {
        if (typeof Number.isFinite === 'function') {
            if (Number.isFinite(num)) {
                return;
            }
            throw new TypeError('coordinates must be finite numbers');
        }
        if (typeof num !== 'number' || num !== num || !isFinite(num)) {
            throw new TypeError('coordinates must be finite numbers');
        }
    }
},
/* models/annotations/arrow_head.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b, _c, _d, _e;
    var model_1 = require(168) /* ../../model */;
    var view_1 = require(157) /* ../../core/view */;
    var visuals = (0, tslib_1.__importStar)(require(160) /* ../../core/visuals */);
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var ArrowHeadView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ArrowHeadView, _super);
        function ArrowHeadView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ArrowHeadView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.visuals = new visuals.Visuals(this);
        };
        ArrowHeadView.prototype.request_render = function () {
            this.parent.request_render();
        };
        Object.defineProperty(ArrowHeadView.prototype, "canvas", {
            get: function () {
                return this.parent.canvas;
            },
            enumerable: false,
            configurable: true
        });
        ArrowHeadView.prototype.set_data = function (source) {
            var e_1, _f;
            var self = this;
            try {
                for (var _g = (0, tslib_1.__values)(this.model), _h = _g.next(); !_h.done; _h = _g.next()) {
                    var prop = _h.value;
                    if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                        continue;
                    var uniform = prop.uniform(source);
                    self["" + prop.attr] = uniform;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_h && !_h.done && (_f = _g.return))
                        _f.call(_g);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        return ArrowHeadView;
    }(view_1.View));
    exports.ArrowHeadView = ArrowHeadView;
    ArrowHeadView.__name__ = "ArrowHeadView";
    var ArrowHead = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ArrowHead, _super);
        function ArrowHead(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ArrowHead;
    }(model_1.Model));
    exports.ArrowHead = ArrowHead;
    _a = ArrowHead;
    ArrowHead.__name__ = "ArrowHead";
    (function () {
        _a.define(function () {
            return ({
                size: [p.NumberSpec, 25],
            });
        });
    })();
    var OpenHeadView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(OpenHeadView, _super);
        function OpenHeadView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        OpenHeadView.prototype.clip = function (ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            var size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(0.5 * size_i, size_i);
        };
        OpenHeadView.prototype.render = function (ctx, i) {
            if (this.visuals.line.doit) {
                this.visuals.line.set_vectorize(ctx, i);
                var size_i = this.size.get(i);
                ctx.beginPath();
                ctx.moveTo(0.5 * size_i, size_i);
                ctx.lineTo(0, 0);
                ctx.lineTo(-0.5 * size_i, size_i);
                ctx.stroke();
            }
        };
        return OpenHeadView;
    }(ArrowHeadView));
    exports.OpenHeadView = OpenHeadView;
    OpenHeadView.__name__ = "OpenHeadView";
    var OpenHead = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(OpenHead, _super);
        function OpenHead(attrs) {
            return _super.call(this, attrs) || this;
        }
        return OpenHead;
    }(ArrowHead));
    exports.OpenHead = OpenHead;
    _b = OpenHead;
    OpenHead.__name__ = "OpenHead";
    (function () {
        _b.prototype.default_view = OpenHeadView;
        _b.mixins(property_mixins_1.LineVector);
    })();
    var NormalHeadView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NormalHeadView, _super);
        function NormalHeadView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        NormalHeadView.prototype.clip = function (ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            var size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, size_i);
        };
        NormalHeadView.prototype.render = function (ctx, i) {
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_vectorize(ctx, i);
                this._normal(ctx, i);
                ctx.fill();
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_vectorize(ctx, i);
                this._normal(ctx, i);
                ctx.stroke();
            }
        };
        NormalHeadView.prototype._normal = function (ctx, i) {
            var size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.closePath();
        };
        return NormalHeadView;
    }(ArrowHeadView));
    exports.NormalHeadView = NormalHeadView;
    NormalHeadView.__name__ = "NormalHeadView";
    var NormalHead = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NormalHead, _super);
        function NormalHead(attrs) {
            return _super.call(this, attrs) || this;
        }
        return NormalHead;
    }(ArrowHead));
    exports.NormalHead = NormalHead;
    _c = NormalHead;
    NormalHead.__name__ = "NormalHead";
    (function () {
        _c.prototype.default_view = NormalHeadView;
        _c.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector]);
        _c.override({
            fill_color: "black",
        });
    })();
    var VeeHeadView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VeeHeadView, _super);
        function VeeHeadView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        VeeHeadView.prototype.clip = function (ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            var size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0.5 * size_i);
            ctx.lineTo(0.5 * size_i, size_i);
        };
        VeeHeadView.prototype.render = function (ctx, i) {
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_vectorize(ctx, i);
                this._vee(ctx, i);
                ctx.fill();
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_vectorize(ctx, i);
                this._vee(ctx, i);
                ctx.stroke();
            }
        };
        VeeHeadView.prototype._vee = function (ctx, i) {
            var size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0.5 * size_i);
            ctx.closePath();
        };
        return VeeHeadView;
    }(ArrowHeadView));
    exports.VeeHeadView = VeeHeadView;
    VeeHeadView.__name__ = "VeeHeadView";
    var VeeHead = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VeeHead, _super);
        function VeeHead(attrs) {
            return _super.call(this, attrs) || this;
        }
        return VeeHead;
    }(ArrowHead));
    exports.VeeHead = VeeHead;
    _d = VeeHead;
    VeeHead.__name__ = "VeeHead";
    (function () {
        _d.prototype.default_view = VeeHeadView;
        _d.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector]);
        _d.override({
            fill_color: "black",
        });
    })();
    var TeeHeadView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TeeHeadView, _super);
        function TeeHeadView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TeeHeadView.prototype.render = function (ctx, i) {
            if (this.visuals.line.doit) {
                this.visuals.line.set_vectorize(ctx, i);
                var size_i = this.size.get(i);
                ctx.beginPath();
                ctx.moveTo(0.5 * size_i, 0);
                ctx.lineTo(-0.5 * size_i, 0);
                ctx.stroke();
            }
        };
        TeeHeadView.prototype.clip = function (_ctx, _i) { };
        return TeeHeadView;
    }(ArrowHeadView));
    exports.TeeHeadView = TeeHeadView;
    TeeHeadView.__name__ = "TeeHeadView";
    var TeeHead = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TeeHead, _super);
        function TeeHead(attrs) {
            return _super.call(this, attrs) || this;
        }
        return TeeHead;
    }(ArrowHead));
    exports.TeeHead = TeeHead;
    _e = TeeHead;
    TeeHead.__name__ = "TeeHead";
    (function () {
        _e.prototype.default_view = TeeHeadView;
        _e.mixins(property_mixins_1.LineVector);
    })();
},
/* core/build_views.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var array_1 = require(126) /* ./util/array */;
    function _build_view(view_cls, model, options) {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var view;
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        view = new view_cls((0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), { model: model }));
                        view.initialize();
                        return [4 /*yield*/, view.lazy_initialize()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, view];
                }
            });
        });
    }
    function build_view(model, options, cls) {
        if (options === void 0) {
            options = { parent: null };
        }
        if (cls === void 0) {
            cls = function (model) { return model.default_view; };
        }
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var view;
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, _build_view(cls(model), model, options)];
                    case 1:
                        view = _a.sent();
                        view.connect_signals();
                        return [2 /*return*/, view];
                }
            });
        });
    }
    exports.build_view = build_view;
    function build_views(view_storage, models, options, cls) {
        if (options === void 0) {
            options = { parent: null };
        }
        if (cls === void 0) {
            cls = function (model) { return model.default_view; };
        }
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var to_remove, to_remove_1, to_remove_1_1, model, created_views, new_models, new_models_1, new_models_1_1, model, view, e_1_1, created_views_1, created_views_1_1, view;
            var e_2, _a, e_1, _b, e_3, _c;
            return (0, tslib_1.__generator)(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        to_remove = (0, array_1.difference)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(view_storage.keys()), false), models);
                        try {
                            for (to_remove_1 = (0, tslib_1.__values)(to_remove), to_remove_1_1 = to_remove_1.next(); !to_remove_1_1.done; to_remove_1_1 = to_remove_1.next()) {
                                model = to_remove_1_1.value;
                                view_storage.get(model).remove();
                                view_storage.delete(model);
                            }
                        }
                        catch (e_2_1) {
                            e_2 = { error: e_2_1 };
                        }
                        finally {
                            try {
                                if (to_remove_1_1 && !to_remove_1_1.done && (_a = to_remove_1.return))
                                    _a.call(to_remove_1);
                            }
                            finally {
                                if (e_2)
                                    throw e_2.error;
                            }
                        }
                        created_views = [];
                        new_models = models.filter(function (model) { return !view_storage.has(model); });
                        _d.label = 1;
                    case 1:
                        _d.trys.push([1, 6, 7, 8]);
                        new_models_1 = (0, tslib_1.__values)(new_models), new_models_1_1 = new_models_1.next();
                        _d.label = 2;
                    case 2:
                        if (!!new_models_1_1.done)
                            return [3 /*break*/, 5];
                        model = new_models_1_1.value;
                        return [4 /*yield*/, _build_view(cls(model), model, options)];
                    case 3:
                        view = _d.sent();
                        view_storage.set(model, view);
                        created_views.push(view);
                        _d.label = 4;
                    case 4:
                        new_models_1_1 = new_models_1.next();
                        return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 8];
                    case 6:
                        e_1_1 = _d.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 8];
                    case 7:
                        try {
                            if (new_models_1_1 && !new_models_1_1.done && (_b = new_models_1.return))
                                _b.call(new_models_1);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                        return [7 /*endfinally*/];
                    case 8:
                        try {
                            for (created_views_1 = (0, tslib_1.__values)(created_views), created_views_1_1 = created_views_1.next(); !created_views_1_1.done; created_views_1_1 = created_views_1.next()) {
                                view = created_views_1_1.value;
                                view.connect_signals();
                            }
                        }
                        catch (e_3_1) {
                            e_3 = { error: e_3_1 };
                        }
                        finally {
                            try {
                                if (created_views_1_1 && !created_views_1_1.done && (_c = created_views_1.return))
                                    _c.call(created_views_1);
                            }
                            finally {
                                if (e_3)
                                    throw e_3.error;
                            }
                        }
                        return [2 /*return*/, created_views];
                }
            });
        });
    }
    exports.build_views = build_views;
    function remove_views(view_storage) {
        var e_4, _a;
        try {
            for (var view_storage_1 = (0, tslib_1.__values)(view_storage), view_storage_1_1 = view_storage_1.next(); !view_storage_1_1.done; view_storage_1_1 = view_storage_1.next()) {
                var _b = (0, tslib_1.__read)(view_storage_1_1.value, 2), model = _b[0], view = _b[1];
                view.remove();
                view_storage.delete(model);
            }
        }
        catch (e_4_1) {
            e_4 = { error: e_4_1 };
        }
        finally {
            try {
                if (view_storage_1_1 && !view_storage_1_1.done && (_a = view_storage_1.return))
                    _a.call(view_storage_1);
            }
            finally {
                if (e_4)
                    throw e_4.error;
            }
        }
    }
    exports.remove_views = remove_views;
},
/* models/annotations/band.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var upper_lower_1 = require(230) /* ./upper_lower */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var BandView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BandView, _super);
        function BandView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BandView.prototype.paint = function (ctx) {
            // Draw the band body
            ctx.beginPath();
            ctx.moveTo(this._lower_sx[0], this._lower_sy[0]);
            for (var i = 0, end = this._lower_sx.length; i < end; i++) {
                ctx.lineTo(this._lower_sx[i], this._lower_sy[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (var i = this._upper_sx.length - 1; i >= 0; i--) {
                ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            // Draw the lower band edge
            ctx.beginPath();
            ctx.moveTo(this._lower_sx[0], this._lower_sy[0]);
            for (var i = 0, end = this._lower_sx.length; i < end; i++) {
                ctx.lineTo(this._lower_sx[i], this._lower_sy[i]);
            }
            this.visuals.line.apply(ctx);
            // Draw the upper band edge
            ctx.beginPath();
            ctx.moveTo(this._upper_sx[0], this._upper_sy[0]);
            for (var i = 0, end = this._upper_sx.length; i < end; i++) {
                ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
            }
            this.visuals.line.apply(ctx);
        };
        return BandView;
    }(upper_lower_1.UpperLowerView));
    exports.BandView = BandView;
    BandView.__name__ = "BandView";
    var Band = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Band, _super);
        function Band(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Band;
    }(upper_lower_1.UpperLower));
    exports.Band = Band;
    _a = Band;
    Band.__name__ = "Band";
    (function () {
        _a.prototype.default_view = BandView;
        _a.mixins([mixins.Line, mixins.Fill]);
        _a.override({
            fill_color: "#fff9ba",
            fill_alpha: 0.4,
            line_color: "#cccccc",
            line_alpha: 0.3,
        });
    })();
},
/* models/annotations/upper_lower.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var data_annotation_1 = require(184) /* ./data_annotation */;
    var enums_1 = require(135) /* ../../core/enums */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var UpperLowerView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UpperLowerView, _super);
        function UpperLowerView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        UpperLowerView.prototype.map_data = function () {
            var frame = this.plot_view.frame;
            var dim = this.model.dimension;
            var xscale = this.coordinates.x_scale;
            var yscale = this.coordinates.y_scale;
            var limit_scale = dim == "height" ? yscale : xscale;
            var base_scale = dim == "height" ? xscale : yscale;
            var limit_view = dim == "height" ? frame.bbox.yview : frame.bbox.xview;
            var base_view = dim == "height" ? frame.bbox.xview : frame.bbox.yview;
            var _lower_sx;
            if (this.model.properties.lower.units == "data")
                _lower_sx = limit_scale.v_compute(this._lower);
            else
                _lower_sx = limit_view.v_compute(this._lower);
            var _upper_sx;
            if (this.model.properties.upper.units == "data")
                _upper_sx = limit_scale.v_compute(this._upper);
            else
                _upper_sx = limit_view.v_compute(this._upper);
            var _base_sx;
            if (this.model.properties.base.units == "data")
                _base_sx = base_scale.v_compute(this._base);
            else
                _base_sx = base_view.v_compute(this._base);
            var _b = (0, tslib_1.__read)(dim == "height" ? [1, 0] : [0, 1], 2), i = _b[0], j = _b[1];
            var _lower = [_lower_sx, _base_sx];
            var _upper = [_upper_sx, _base_sx];
            this._lower_sx = _lower[i];
            this._lower_sy = _lower[j];
            this._upper_sx = _upper[i];
            this._upper_sy = _upper[j];
        };
        return UpperLowerView;
    }(data_annotation_1.DataAnnotationView));
    exports.UpperLowerView = UpperLowerView;
    UpperLowerView.__name__ = "UpperLowerView";
    var XOrYCoordinateSpec = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(XOrYCoordinateSpec, _super);
        function XOrYCoordinateSpec() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(XOrYCoordinateSpec.prototype, "dimension", {
            get: function () {
                return this.obj.dimension == "width" ? "x" : "y";
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(XOrYCoordinateSpec.prototype, "units", {
            // XXX: a hack to make a coordinate & unit spec
            get: function () {
                var _b;
                return (_b = this.spec.units) !== null && _b !== void 0 ? _b : "data";
            },
            enumerable: false,
            configurable: true
        });
        return XOrYCoordinateSpec;
    }(p.CoordinateSpec));
    exports.XOrYCoordinateSpec = XOrYCoordinateSpec;
    XOrYCoordinateSpec.__name__ = "XOrYCoordinateSpec";
    var UpperLower = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UpperLower, _super);
        function UpperLower(attrs) {
            return _super.call(this, attrs) || this;
        }
        return UpperLower;
    }(data_annotation_1.DataAnnotation));
    exports.UpperLower = UpperLower;
    _a = UpperLower;
    UpperLower.__name__ = "UpperLower";
    (function () {
        _a.define(function () {
            return ({
                dimension: [enums_1.Dimension, "height"],
                lower: [XOrYCoordinateSpec, { field: "lower" }],
                upper: [XOrYCoordinateSpec, { field: "upper" }],
                base: [XOrYCoordinateSpec, { field: "base" }],
            });
        });
    })();
},
/* models/annotations/box_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var enums_1 = require(135) /* ../../core/enums */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    exports.EDGE_TOLERANCE = 2.5;
    var BoxAnnotationView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxAnnotationView, _super);
        function BoxAnnotationView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.bbox = new bbox_1.BBox();
            return _this;
        }
        BoxAnnotationView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.change, function () { return _this.request_render(); });
        };
        BoxAnnotationView.prototype._render = function () {
            var _this = this;
            var _b = this.model, left = _b.left, right = _b.right, top = _b.top, bottom = _b.bottom;
            // don't render if *all* position are null
            if (left == null && right == null && top == null && bottom == null)
                return;
            var frame = this.plot_view.frame;
            var xscale = this.coordinates.x_scale;
            var yscale = this.coordinates.y_scale;
            var _calc_dim = function (dim, dim_units, scale, view, frame_extrema) {
                var sdim;
                if (dim != null) {
                    if (_this.model.screen)
                        sdim = dim;
                    else {
                        if (dim_units == "data")
                            sdim = scale.compute(dim);
                        else
                            sdim = view.compute(dim);
                    }
                }
                else
                    sdim = frame_extrema;
                return sdim;
            };
            this.bbox = bbox_1.BBox.from_rect({
                left: _calc_dim(left, this.model.left_units, xscale, frame.bbox.xview, frame.bbox.left),
                right: _calc_dim(right, this.model.right_units, xscale, frame.bbox.xview, frame.bbox.right),
                top: _calc_dim(top, this.model.top_units, yscale, frame.bbox.yview, frame.bbox.top),
                bottom: _calc_dim(bottom, this.model.bottom_units, yscale, frame.bbox.yview, frame.bbox.bottom),
            });
            this._paint_box();
        };
        BoxAnnotationView.prototype._paint_box = function () {
            var ctx = this.layer.ctx;
            ctx.save();
            var _b = this.bbox, left = _b.left, top = _b.top, width = _b.width, height = _b.height;
            ctx.beginPath();
            ctx.rect(left, top, width, height);
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
            this.visuals.line.apply(ctx);
            ctx.restore();
        };
        BoxAnnotationView.prototype.interactive_bbox = function () {
            var tolerance = this.model.line_width + exports.EDGE_TOLERANCE;
            return this.bbox.grow_by(tolerance);
        };
        BoxAnnotationView.prototype.interactive_hit = function (sx, sy) {
            if (this.model.in_cursor == null)
                return false;
            var bbox = this.interactive_bbox();
            return bbox.contains(sx, sy);
        };
        BoxAnnotationView.prototype.cursor = function (sx, sy) {
            var tol = 3;
            var _b = this.bbox, left = _b.left, right = _b.right, bottom = _b.bottom, top = _b.top;
            if (Math.abs(sx - left) < tol || Math.abs(sx - right) < tol)
                return this.model.ew_cursor;
            else if (Math.abs(sy - bottom) < tol || Math.abs(sy - top) < tol)
                return this.model.ns_cursor;
            else if (this.bbox.contains(sx, sy))
                return this.model.in_cursor;
            else
                return null;
        };
        return BoxAnnotationView;
    }(annotation_1.AnnotationView));
    exports.BoxAnnotationView = BoxAnnotationView;
    BoxAnnotationView.__name__ = "BoxAnnotationView";
    var BoxAnnotation = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxAnnotation, _super);
        function BoxAnnotation(attrs) {
            return _super.call(this, attrs) || this;
        }
        BoxAnnotation.prototype.update = function (_b) {
            var left = _b.left, right = _b.right, top = _b.top, bottom = _b.bottom;
            this.setv({ left: left, right: right, top: top, bottom: bottom, screen: true });
        };
        return BoxAnnotation;
    }(annotation_1.Annotation));
    exports.BoxAnnotation = BoxAnnotation;
    _a = BoxAnnotation;
    BoxAnnotation.__name__ = "BoxAnnotation";
    (function () {
        _a.prototype.default_view = BoxAnnotationView;
        _a.mixins([mixins.Line, mixins.Fill, mixins.Hatch]);
        _a.define(function (_b) {
            var Number = _b.Number, Nullable = _b.Nullable;
            return ({
                top: [Nullable(Number), null],
                top_units: [enums_1.SpatialUnits, "data"],
                bottom: [Nullable(Number), null],
                bottom_units: [enums_1.SpatialUnits, "data"],
                left: [Nullable(Number), null],
                left_units: [enums_1.SpatialUnits, "data"],
                right: [Nullable(Number), null],
                right_units: [enums_1.SpatialUnits, "data"],
                /** @deprecated */
                render_mode: [enums_1.RenderMode, "canvas"],
            });
        });
        _a.internal(function (_b) {
            var Boolean = _b.Boolean, String = _b.String, Nullable = _b.Nullable;
            return ({
                screen: [Boolean, false],
                ew_cursor: [Nullable(String), null],
                ns_cursor: [Nullable(String), null],
                in_cursor: [Nullable(String), null],
            });
        });
        _a.override({
            fill_color: "#fff9ba",
            fill_alpha: 0.4,
            line_color: "#cccccc",
            line_alpha: 0.3,
        });
    })();
},
/* models/annotations/color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var title_1 = require(233) /* ./title */;
    var cartesian_frame_1 = require(241) /* ../canvas/cartesian_frame */;
    var axes_1 = require(242) /* ../axes */;
    var ticker_1 = require(245) /* ../tickers/ticker */;
    var tickers_1 = require(283) /* ../tickers */;
    var tick_formatter_1 = require(246) /* ../formatters/tick_formatter */;
    var formatters_1 = require(307) /* ../formatters */;
    var labeling_1 = require(247) /* ../policies/labeling */;
    var color_mapper_1 = require(288) /* ../mappers/color_mapper */;
    var continuous_color_mapper_1 = require(287) /* ../mappers/continuous_color_mapper */;
    var mappers_1 = require(311) /* ../mappers */;
    var scales_1 = require(319) /* ../scales */;
    var ranges_1 = require(321) /* ../ranges */;
    var base_text_1 = require(248) /* ../text/base_text */;
    var enums_1 = require(135) /* ../../core/enums */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var array_1 = require(126) /* ../../core/util/array */;
    var layout_1 = require(322) /* ../../core/layout */;
    var alignments_1 = require(323) /* ../../core/layout/alignments */;
    var border_1 = require(326) /* ../../core/layout/border */;
    var side_panel_1 = require(238) /* ../../core/layout/side_panel */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    var types_1 = require(125) /* ../../core/util/types */;
    var MINOR_DIM = 25;
    var MAJOR_DIM_MIN_SCALAR = 0.3;
    var MAJOR_DIM_MAX_SCALAR = 0.8;
    var ColorBarView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColorBarView, _super);
        function ColorBarView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(ColorBarView.prototype, "orientation", {
            get: function () {
                return this._orientation;
            },
            enumerable: false,
            configurable: true
        });
        ColorBarView.prototype.initialize = function () {
            var _this = this;
            _super.prototype.initialize.call(this);
            var _b = this.model, ticker = _b.ticker, formatter = _b.formatter, color_mapper = _b.color_mapper;
            this._ticker = ticker != "auto" ? ticker : (function () {
                switch (true) {
                    case color_mapper instanceof mappers_1.LogColorMapper:
                        return new tickers_1.LogTicker();
                    case color_mapper instanceof mappers_1.ScanningColorMapper:
                        return new tickers_1.BinnedTicker({ mapper: color_mapper });
                    case color_mapper instanceof mappers_1.CategoricalColorMapper:
                        return new tickers_1.CategoricalTicker();
                    default:
                        return new tickers_1.BasicTicker();
                }
            })();
            this._formatter = formatter != "auto" ? formatter : (function () {
                switch (true) {
                    case _this._ticker instanceof tickers_1.LogTicker:
                        return new formatters_1.LogTickFormatter();
                    case color_mapper instanceof mappers_1.CategoricalColorMapper:
                        return new formatters_1.CategoricalTickFormatter();
                    default:
                        return new formatters_1.BasicTickFormatter();
                }
            })();
            /*
            Creates and returns a scale instance that maps the `color_mapper` range
            (low to high) to a screen space range equal to the length of the ColorBar's
            scale image. The scale is used to calculate the tick coordinates in screen
            coordinates for plotting purposes.
        
            Note: the type of color_mapper has to match the type of scale (i.e.
            a LinearColorMapper will require a corresponding LinearScale instance).
            */
            this._major_range = (function () {
                if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                    var factors = color_mapper.factors;
                    return new ranges_1.FactorRange({ factors: factors });
                }
                else if (color_mapper instanceof continuous_color_mapper_1.ContinuousColorMapper) {
                    var _b = color_mapper.metrics, min = _b.min, max = _b.max;
                    return new ranges_1.Range1d({ start: min, end: max });
                }
                else
                    (0, assert_1.unreachable)();
            })();
            this._major_scale = (function () {
                if (color_mapper instanceof mappers_1.LinearColorMapper)
                    return new scales_1.LinearScale();
                else if (color_mapper instanceof mappers_1.LogColorMapper)
                    return new scales_1.LogScale();
                else if (color_mapper instanceof mappers_1.ScanningColorMapper) {
                    var binning = color_mapper.metrics.binning;
                    return new scales_1.LinearInterpolationScale({ binning: binning });
                }
                else if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                    return new scales_1.CategoricalScale();
                }
                else
                    (0, assert_1.unreachable)();
            })();
            this._minor_range = new ranges_1.Range1d({ start: 0, end: 1 });
            this._minor_scale = new scales_1.LinearScale();
            var major_label_text = mixins.attrs_of(this.model, "major_label_", mixins.Text, true);
            var major_tick_line = mixins.attrs_of(this.model, "major_tick_", mixins.Line, true);
            var minor_tick_line = mixins.attrs_of(this.model, "minor_tick_", mixins.Line, true);
            var title_text = mixins.attrs_of(this.model, "title_", mixins.Text);
            var AxisCls = (function () {
                if (color_mapper instanceof mappers_1.CategoricalColorMapper)
                    return axes_1.CategoricalAxis;
                else if (color_mapper instanceof mappers_1.LogColorMapper)
                    return axes_1.LogAxis;
                else
                    return axes_1.LinearAxis;
            })();
            this._axis = new AxisCls((0, tslib_1.__assign)((0, tslib_1.__assign)((0, tslib_1.__assign)({ ticker: this._ticker, formatter: this._formatter, major_tick_in: this.model.major_tick_in, major_tick_out: this.model.major_tick_out, minor_tick_in: this.model.minor_tick_in, minor_tick_out: this.model.minor_tick_out, major_label_standoff: this.model.label_standoff, major_label_overrides: this.model.major_label_overrides, major_label_policy: this.model.major_label_policy, axis_line_color: null }, major_label_text), major_tick_line), minor_tick_line));
            var title = this.model.title;
            if (title) {
                this._title = new title_1.Title((0, tslib_1.__assign)({ text: title, standoff: this.model.title_standoff }, title_text));
            }
        };
        ColorBarView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var self, parent, _b, _c;
                return (0, tslib_1.__generator)(this, function (_d) {
                    switch (_d.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _d.sent();
                            self = this;
                            parent = {
                                get parent() {
                                    return self.parent;
                                },
                                get root() {
                                    return self.root;
                                },
                                get frame() {
                                    return self._frame;
                                },
                                get canvas_view() {
                                    return self.parent.canvas_view;
                                },
                                request_layout: function () {
                                    self.parent.request_layout();
                                },
                            };
                            _b = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(this._axis, { parent: parent })];
                        case 2:
                            _b._axis_view = _d.sent();
                            if (!(this._title != null))
                                return [3 /*break*/, 4];
                            _c = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(this._title, { parent: parent })];
                        case 3:
                            _c._title_view = _d.sent();
                            _d.label = 4;
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        ColorBarView.prototype.remove = function () {
            var _b;
            (_b = this._title_view) === null || _b === void 0 ? void 0 : _b.remove();
            this._axis_view.remove();
            _super.prototype.remove.call(this);
        };
        ColorBarView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            // TODO: this.connect(this.model.change, () => this.plot_view.invalidate_layout())
            this.connect(this._ticker.change, function () { return _this.request_render(); });
            this.connect(this._formatter.change, function () { return _this.request_render(); });
            this.connect(this.model.color_mapper.metrics_change, function () {
                var range = _this._major_range;
                var scale = _this._major_scale;
                var color_mapper = _this.model.color_mapper;
                if (color_mapper instanceof continuous_color_mapper_1.ContinuousColorMapper && range instanceof ranges_1.Range1d) {
                    var _b = color_mapper.metrics, min = _b.min, max = _b.max;
                    range.setv({ start: min, end: max });
                }
                if (color_mapper instanceof mappers_1.ScanningColorMapper && scale instanceof scales_1.LinearInterpolationScale) {
                    var binning = color_mapper.metrics.binning;
                    scale.binning = binning;
                }
                _this._set_canvas_image();
                _this.plot_view.request_layout(); // this.request_render()
            });
        };
        ColorBarView.prototype._set_canvas_image = function () {
            var _this = this;
            var orientation = this.orientation;
            var palette = (function () {
                var palette = _this.model.color_mapper.palette;
                if (orientation == "vertical")
                    return (0, array_1.reversed)(palette);
                else
                    return palette;
            })();
            var _b = (0, tslib_1.__read)((function () {
                if (orientation == "vertical")
                    return [1, palette.length];
                else
                    return [palette.length, 1];
            })(), 2), w = _b[0], h = _b[1];
            var canvas = this._image = document.createElement("canvas");
            canvas.width = w;
            canvas.height = h;
            var image_ctx = canvas.getContext("2d");
            var image_data = image_ctx.getImageData(0, 0, w, h);
            // We always want to draw the entire palette linearly, so we create a new
            // LinearColorMapper instance and map a monotonic range of values with
            // length = palette.length to get each palette color in order.
            var cmap = new mappers_1.LinearColorMapper({ palette: palette }).rgba_mapper;
            var buf8 = cmap.v_compute((0, array_1.range)(0, palette.length));
            image_data.data.set(buf8);
            image_ctx.putImageData(image_data, 0, 0);
        };
        ColorBarView.prototype.update_layout = function () {
            var _this = this;
            var _b = this.model, location = _b.location, w = _b.width, h = _b.height, padding = _b.padding, margin = _b.margin;
            var _c = (0, tslib_1.__read)((function () {
                if ((0, types_1.isString)(location)) {
                    switch (location) {
                        case "top_left":
                            return ["start", "start"];
                        case "top":
                        case "top_center":
                            return ["start", "center"];
                        case "top_right":
                            return ["start", "end"];
                        case "bottom_left":
                            return ["end", "start"];
                        case "bottom":
                        case "bottom_center":
                            return ["end", "center"];
                        case "bottom_right":
                            return ["end", "end"];
                        case "left":
                        case "center_left":
                            return ["center", "start"];
                        case "center":
                        case "center_center":
                            return ["center", "center"];
                        case "right":
                        case "center_right":
                            return ["center", "end"];
                    }
                }
                else
                    return ["end", "start"]; // "bottom_left"
            })(), 2), valign = _c[0], halign = _c[1];
            var orientation = this._orientation = (function () {
                var orientation = _this.model.orientation;
                if (orientation == "auto") {
                    if (_this.panel != null)
                        return _this.panel.is_horizontal ? "horizontal" : "vertical";
                    else {
                        if (halign == "start" || halign == "end" || (halign == "center" && valign == "center"))
                            return "vertical";
                        else
                            return "horizontal";
                    }
                }
                else
                    return orientation;
            })();
            var center_panel = new alignments_1.NodeLayout();
            var top_panel = new alignments_1.VStack();
            var bottom_panel = new alignments_1.VStack();
            var left_panel = new alignments_1.HStack();
            var right_panel = new alignments_1.HStack();
            center_panel.absolute = true;
            top_panel.absolute = true;
            bottom_panel.absolute = true;
            left_panel.absolute = true;
            right_panel.absolute = true;
            var _d = (0, tslib_1.__read)((function () {
                if (orientation == "horizontal")
                    return [_this._major_scale, _this._minor_scale, _this._major_range, _this._minor_range];
                else
                    return [_this._minor_scale, _this._major_scale, _this._minor_range, _this._major_range];
            })(), 4), x_scale = _d[0], y_scale = _d[1], x_range = _d[2], y_range = _d[3];
            this._frame = new cartesian_frame_1.CartesianFrame(x_scale, y_scale, x_range, y_range);
            center_panel.on_resize(function (bbox) { return _this._frame.set_geometry(bbox); });
            var layout = new border_1.BorderLayout();
            this._inner_layout = layout;
            layout.absolute = true;
            layout.center_panel = center_panel;
            layout.top_panel = top_panel;
            layout.bottom_panel = bottom_panel;
            layout.left_panel = left_panel;
            layout.right_panel = right_panel;
            var padding_box = { left: padding, right: padding, top: padding, bottom: padding };
            var margin_box = (function () {
                if (_this.panel == null) {
                    if ((0, types_1.isString)(location))
                        return { left: margin, right: margin, top: margin, bottom: margin };
                    else {
                        var _b = (0, tslib_1.__read)(location, 2), left = _b[0], bottom = _b[1];
                        return { left: left, right: margin, top: margin, bottom: bottom };
                    }
                }
                else {
                    /**
                     * XXX: alignment is broken in Grid, which is used to govern positioning of a ColorBar
                     * in side panels. Earlier attempts at fixing this failed and resulted in a multitude
                     * or regressions in various places in the layout. So instead of this, let's assume that
                     * the positioning is always at "start" regardless of configuration, and fix this here
                     * by manually computing "center" and "end" alignment.
                     */
                    if ((0, types_1.isString)(location)) {
                        layout.fixup_geometry = function (outer, inner) {
                            var origin = outer;
                            if (orientation == "horizontal") {
                                var top = outer.top, width = outer.width, height = outer.height;
                                if (halign == "end") {
                                    var right = _this.layout.bbox.right;
                                    outer = new bbox_1.BBox({ right: right, top: top, width: width, height: height });
                                }
                                else if (halign == "center") {
                                    var hcenter = _this.layout.bbox.hcenter;
                                    outer = new bbox_1.BBox({ hcenter: Math.round(hcenter), top: top, width: width, height: height });
                                }
                            }
                            else {
                                var left = outer.left, width = outer.width, height = outer.height;
                                if (valign == "end") {
                                    var bottom = _this.layout.bbox.bottom;
                                    outer = new bbox_1.BBox({ left: left, bottom: bottom, width: width, height: height });
                                }
                                else if (valign == "center") {
                                    var vcenter = _this.layout.bbox.vcenter;
                                    outer = new bbox_1.BBox({ left: left, vcenter: Math.round(vcenter), width: width, height: height });
                                }
                            }
                            if (inner != null) {
                                var dh = outer.left - origin.left;
                                var dv = outer.top - origin.top;
                                var left = inner.left, top = inner.top, width = inner.width, height = inner.height;
                                inner = new bbox_1.BBox({ left: left + dh, top: top + dv, width: width, height: height });
                            }
                            return [outer, inner];
                        };
                        return undefined;
                    }
                    else {
                        var _c = (0, tslib_1.__read)(location, 2), left_1 = _c[0], bottom_1 = _c[1];
                        layout.fixup_geometry = function (outer, inner) {
                            var origin = outer;
                            var grid = _this.layout.bbox;
                            var width = outer.width, height = outer.height;
                            outer = new bbox_1.BBox({ left: grid.left + left_1, bottom: grid.bottom - bottom_1, width: width, height: height });
                            if (inner != null) {
                                var dh = outer.left - origin.left;
                                var dv = outer.top - origin.top;
                                var left_2 = inner.left, top = inner.top, width_1 = inner.width, height_1 = inner.height;
                                inner = new bbox_1.BBox({ left: left_2 + dh, top: top + dv, width: width_1, height: height_1 });
                            }
                            return [outer, inner];
                        };
                        return { left: left_1, right: 0, top: 0, bottom: bottom_1 };
                    }
                }
            })();
            layout.padding = padding_box;
            var major_policy;
            var major_size;
            var min_major_size;
            var max_major_size;
            if (this.panel != null) {
                major_policy = "max";
                major_size = undefined;
                min_major_size = undefined;
                max_major_size = undefined;
            }
            else {
                if ((orientation == "horizontal" ? w : h) == "auto") {
                    major_policy = "fixed";
                    major_size = this.model.color_mapper.palette.length * MINOR_DIM;
                    min_major_size = { percent: MAJOR_DIM_MIN_SCALAR };
                    max_major_size = { percent: MAJOR_DIM_MAX_SCALAR };
                }
                else {
                    major_policy = "fit";
                    major_size = undefined;
                }
            }
            if (orientation == "horizontal") {
                var width = w == "auto" ? undefined : w;
                var height = h == "auto" ? MINOR_DIM : h;
                layout.set_sizing({
                    width_policy: major_policy, height_policy: "min",
                    width: major_size, min_width: min_major_size, max_width: max_major_size,
                    halign: halign,
                    valign: valign,
                    margin: margin_box,
                });
                layout.center_panel.set_sizing({ width_policy: w == "auto" ? "fit" : "fixed", height_policy: "fixed", width: width, height: height });
            }
            else {
                var width = w == "auto" ? MINOR_DIM : w;
                var height = h == "auto" ? undefined : h;
                layout.set_sizing({
                    width_policy: "min", height_policy: major_policy,
                    height: major_size, min_height: min_major_size, max_height: max_major_size,
                    halign: halign,
                    valign: valign,
                    margin: margin_box,
                });
                layout.center_panel.set_sizing({ width_policy: "fixed", height_policy: h == "auto" ? "fit" : "fixed", width: width, height: height });
            }
            top_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            left_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            right_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            var _title_view = this._title_view;
            if (_title_view != null) {
                if (orientation == "horizontal") {
                    _title_view.panel = new side_panel_1.Panel("above");
                    _title_view.update_layout();
                    top_panel.children.push(_title_view.layout);
                }
                else {
                    _title_view.panel = new side_panel_1.Panel("left");
                    _title_view.update_layout();
                    left_panel.children.push(_title_view.layout);
                }
            }
            var panel = this.panel;
            var side = (function () {
                if (panel != null && orientation == panel.orientation)
                    return panel.side;
                else
                    return orientation == "horizontal" ? "below" : "right";
            })();
            var stack = (function () {
                switch (side) {
                    case "above":
                        return top_panel;
                    case "below":
                        return bottom_panel;
                    case "left":
                        return left_panel;
                    case "right":
                        return right_panel;
                }
            })();
            var _axis_view = this._axis_view;
            _axis_view.panel = new side_panel_1.Panel(side);
            _axis_view.update_layout();
            stack.children.push(_axis_view.layout);
            if (this.panel != null) {
                var outer = new layout_1.Grid([{ layout: layout, row: 0, col: 0 }]);
                outer.absolute = true;
                if (orientation == "horizontal") {
                    outer.set_sizing({ width_policy: "max", height_policy: "min" });
                }
                else {
                    outer.set_sizing({ width_policy: "min", height_policy: "max" });
                }
                this.layout = outer;
            }
            else {
                this.layout = this._inner_layout;
            }
            var visible = this.model.visible;
            this.layout.sizing.visible = visible;
            this._set_canvas_image();
        };
        ColorBarView.prototype._render = function () {
            var _b;
            var ctx = this.layer.ctx;
            ctx.save();
            this._paint_bbox(ctx, this._inner_layout.bbox);
            this._paint_image(ctx, this._inner_layout.center_panel.bbox);
            (_b = this._title_view) === null || _b === void 0 ? void 0 : _b.render();
            this._axis_view.render();
            ctx.restore();
        };
        ColorBarView.prototype._paint_bbox = function (ctx, bbox) {
            var x = bbox.x, y = bbox.y;
            var width = bbox.width, height = bbox.height;
            // XXX: shrink outline region by 1px to make right and bottom lines visible
            // if they are on the edge of the canvas.
            if (x + width >= this.parent.canvas_view.bbox.width) {
                width -= 1;
            }
            if (y + height >= this.parent.canvas_view.bbox.height) {
                height -= 1;
            }
            ctx.save();
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_value(ctx);
                ctx.fillRect(x, y, width, height);
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_value(ctx);
                ctx.strokeRect(x, y, width, height);
            }
            ctx.restore();
        };
        ColorBarView.prototype._paint_image = function (ctx, bbox) {
            var x = bbox.x, y = bbox.y, width = bbox.width, height = bbox.height;
            ctx.save();
            ctx.setImageSmoothingEnabled(false);
            ctx.globalAlpha = this.model.scale_alpha;
            ctx.drawImage(this._image, x, y, width, height);
            if (this.visuals.bar_line.doit) {
                this.visuals.bar_line.set_value(ctx);
                ctx.strokeRect(x, y, width, height);
            }
            ctx.restore();
        };
        ColorBarView.prototype.serializable_state = function () {
            var _b = _super.prototype.serializable_state.call(this), _c = _b.children, children = _c === void 0 ? [] : _c, state = (0, tslib_1.__rest)(_b, ["children"]);
            if (this._title_view != null)
                children.push(this._title_view.serializable_state());
            children.push(this._axis_view.serializable_state());
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, state), { children: children });
        };
        return ColorBarView;
    }(annotation_1.AnnotationView));
    exports.ColorBarView = ColorBarView;
    ColorBarView.__name__ = "ColorBarView";
    var ColorBar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColorBar, _super);
        function ColorBar(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ColorBar;
    }(annotation_1.Annotation));
    exports.ColorBar = ColorBar;
    _a = ColorBar;
    ColorBar.__name__ = "ColorBar";
    (function () {
        _a.prototype.default_view = ColorBarView;
        _a.mixins([
            ["major_label_", mixins.Text],
            ["title_", mixins.Text],
            ["major_tick_", mixins.Line],
            ["minor_tick_", mixins.Line],
            ["border_", mixins.Line],
            ["bar_", mixins.Line],
            ["background_", mixins.Fill],
        ]);
        _a.define(function (_b) {
            var Alpha = _b.Alpha, Number = _b.Number, String = _b.String, Tuple = _b.Tuple, Dict = _b.Dict, Or = _b.Or, Ref = _b.Ref, Auto = _b.Auto, Nullable = _b.Nullable;
            return ({
                location: [Or(enums_1.Anchor, Tuple(Number, Number)), "top_right"],
                orientation: [Or(enums_1.Orientation, Auto), "auto"],
                title: [Nullable(String), null],
                title_standoff: [Number, 2],
                width: [Or(Number, Auto), "auto"],
                height: [Or(Number, Auto), "auto"],
                scale_alpha: [Alpha, 1.0],
                ticker: [Or(Ref(ticker_1.Ticker), Auto), "auto"],
                formatter: [Or(Ref(tick_formatter_1.TickFormatter), Auto), "auto"],
                major_label_overrides: [Dict(Or(String, Ref(base_text_1.BaseText))), {}],
                major_label_policy: [Ref(labeling_1.LabelingPolicy), function () { return new labeling_1.NoOverlap(); }],
                color_mapper: [Ref(color_mapper_1.ColorMapper)],
                label_standoff: [Number, 5],
                margin: [Number, 30],
                padding: [Number, 10],
                major_tick_in: [Number, 5],
                major_tick_out: [Number, 0],
                minor_tick_in: [Number, 0],
                minor_tick_out: [Number, 0],
            });
        });
        _a.override({
            background_fill_color: "#ffffff",
            background_fill_alpha: 0.95,
            bar_line_color: null,
            border_line_color: null,
            major_label_text_font_size: "11px",
            major_tick_line_color: "#ffffff",
            minor_tick_line_color: null,
            title_text_font_size: "13px",
            title_text_font_style: "italic",
        });
    })();
},
/* models/annotations/title.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var text_annotation_1 = require(234) /* ./text_annotation */;
    var enums_1 = require(135) /* ../../core/enums */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var TitleView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TitleView, _super);
        function TitleView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TitleView.prototype._get_location = function () {
            var hmargin = this.model.offset;
            var vmargin = this.model.standoff / 2;
            var sx, sy;
            var bbox = this.layout.bbox;
            switch (this.panel.side) {
                case "above":
                case "below": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sy = bbox.top + vmargin;
                            break;
                        case "middle":
                            sy = bbox.vcenter;
                            break;
                        case "bottom":
                            sy = bbox.bottom - vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sx = bbox.left + hmargin;
                            break;
                        case "center":
                            sx = bbox.hcenter;
                            break;
                        case "right":
                            sx = bbox.right - hmargin;
                            break;
                    }
                    break;
                }
                case "left": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sx = bbox.left + vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.right - vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sy = bbox.bottom - hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.top + hmargin;
                            break;
                    }
                    break;
                }
                case "right": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sx = bbox.right - vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.left + vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sy = bbox.top + hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.bottom - hmargin;
                            break;
                    }
                    break;
                }
            }
            return [sx, sy];
        };
        TitleView.prototype._render = function () {
            var text = this.model.text;
            if (text == null || text.length == 0)
                return;
            this.model.text_baseline = this.model.vertical_align;
            this.model.text_align = this.model.align;
            var _b = (0, tslib_1.__read)(this._get_location(), 2), sx = _b[0], sy = _b[1];
            var angle = this.panel.get_label_angle_heuristic("parallel");
            var draw = this.model.render_mode == "canvas" ? this._canvas_text.bind(this) : this._css_text.bind(this);
            draw(this.layer.ctx, text, sx, sy, angle);
        };
        TitleView.prototype._get_size = function () {
            var text = this.model.text;
            var graphics = new graphics_1.TextBox({ text: text });
            graphics.visuals = this.visuals.text.values();
            var _b = graphics.size(), width = _b.width, height = _b.height;
            // XXX: The magic 2px is for backwards compatibility. This will be removed at
            // some point, but currently there is no point breaking half of visual tests.
            return { width: width, height: height == 0 ? 0 : 2 + height + this.model.standoff };
        };
        return TitleView;
    }(text_annotation_1.TextAnnotationView));
    exports.TitleView = TitleView;
    TitleView.__name__ = "TitleView";
    var Title = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Title, _super);
        function Title(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Title;
    }(text_annotation_1.TextAnnotation));
    exports.Title = Title;
    _a = Title;
    Title.__name__ = "Title";
    (function () {
        _a.prototype.default_view = TitleView;
        _a.mixins([
            mixins.Text,
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
        ]);
        _a.define(function (_b) {
            var Number = _b.Number, String = _b.String;
            return ({
                text: [String, ""],
                vertical_align: [enums_1.VerticalAlign, "bottom"],
                align: [enums_1.TextAlign, "left"],
                offset: [Number, 0],
                standoff: [Number, 10],
            });
        });
        _a.prototype._props.text_align.options.internal = true;
        _a.prototype._props.text_baseline.options.internal = true;
        _a.override({
            text_font_size: "13px",
            text_font_style: "bold",
            text_line_height: 1.0,
            background_fill_color: null,
            border_line_color: null,
        });
    })();
},
/* models/annotations/text_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var dom_1 = require(158) /* ../../core/dom */;
    var enums_1 = require(135) /* ../../core/enums */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var side_panel_1 = require(238) /* ../../core/layout/side_panel */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var TextAnnotationView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextAnnotationView, _super);
        function TextAnnotationView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TextAnnotationView.prototype.update_layout = function () {
            var _this = this;
            var panel = this.panel;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, function () { return _this.get_size(); }, true);
            else
                this.layout = undefined;
        };
        TextAnnotationView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            if (this.model.render_mode == "css") {
                this.el = (0, dom_1.div)();
                this.plot_view.canvas_view.add_overlay(this.el);
            }
        };
        TextAnnotationView.prototype.remove = function () {
            if (this.el != null)
                (0, dom_1.remove)(this.el);
            _super.prototype.remove.call(this);
        };
        TextAnnotationView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            if (this.model.render_mode == "css") {
                // dispatch CSS update immediately
                this.connect(this.model.change, function () { return _this.render(); });
            }
            else {
                this.connect(this.model.change, function () { return _this.request_render(); });
            }
        };
        TextAnnotationView.prototype.render = function () {
            if (!this.model.visible && this.model.render_mode == "css")
                (0, dom_1.undisplay)(this.el);
            _super.prototype.render.call(this);
        };
        TextAnnotationView.prototype._canvas_text = function (ctx, text, sx, sy, angle) {
            var graphics = new graphics_1.TextBox({ text: text });
            graphics.angle = angle;
            graphics.position = { sx: sx, sy: sy };
            graphics.visuals = this.visuals.text.values();
            var _b = this.visuals, background_fill = _b.background_fill, border_line = _b.border_line;
            if (background_fill.doit || border_line.doit) {
                var _c = graphics.rect(), p0 = _c.p0, p1 = _c.p1, p2 = _c.p2, p3 = _c.p3;
                ctx.beginPath();
                ctx.moveTo(p0.x, p0.y);
                ctx.lineTo(p1.x, p1.y);
                ctx.lineTo(p2.x, p2.y);
                ctx.lineTo(p3.x, p3.y);
                ctx.closePath();
                this.visuals.background_fill.apply(ctx);
                this.visuals.border_line.apply(ctx);
            }
            if (this.visuals.text.doit)
                graphics.paint(ctx);
        };
        TextAnnotationView.prototype._css_text = function (ctx, text, sx, sy, angle) {
            var _this = this;
            var el = this.el;
            (0, assert_1.assert)(el != null);
            (0, dom_1.undisplay)(el);
            el.textContent = text;
            this.visuals.text.set_value(ctx);
            el.style.position = "absolute";
            el.style.left = sx + "px";
            el.style.top = sy + "px";
            el.style.color = ctx.fillStyle;
            el.style.font = ctx.font;
            el.style.lineHeight = "normal"; // needed to prevent ipynb css override
            el.style.whiteSpace = "pre";
            var _b = (0, tslib_1.__read)((function () {
                switch (_this.visuals.text.text_align.get_value()) {
                    case "left": return ["left", "0%"];
                    case "center": return ["center", "-50%"];
                    case "right": return ["right", "-100%"];
                }
            })(), 2), x_anchor = _b[0], x_t = _b[1];
            var _c = (0, tslib_1.__read)((function () {
                switch (_this.visuals.text.text_baseline.get_value()) {
                    case "top": return ["top", "0%"];
                    case "middle": return ["center", "-50%"];
                    case "bottom": return ["bottom", "-100%"];
                    default: return ["center", "-50%"]; // "baseline"
                }
            })(), 2), y_anchor = _c[0], y_t = _c[1];
            var transform = "translate(" + x_t + ", " + y_t + ")";
            if (angle) {
                transform += "rotate(" + angle + "rad)";
            }
            el.style.transformOrigin = x_anchor + " " + y_anchor;
            el.style.transform = transform;
            if (this.layout == null) {
                // const {bbox} = this.plot_view.frame
                // const {left, right, top, bottom} = bbox
                // el.style.clipPath = ???
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_value(ctx);
                el.style.backgroundColor = ctx.fillStyle;
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_value(ctx);
                // attempt to support vector-style ("8 4 8") line dashing for css mode
                el.style.borderStyle = ctx.lineDash.length < 2 ? "solid" : "dashed";
                el.style.borderWidth = ctx.lineWidth + "px";
                el.style.borderColor = ctx.strokeStyle;
            }
            (0, dom_1.display)(el);
        };
        return TextAnnotationView;
    }(annotation_1.AnnotationView));
    exports.TextAnnotationView = TextAnnotationView;
    TextAnnotationView.__name__ = "TextAnnotationView";
    var TextAnnotation = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextAnnotation, _super);
        function TextAnnotation(attrs) {
            return _super.call(this, attrs) || this;
        }
        return TextAnnotation;
    }(annotation_1.Annotation));
    exports.TextAnnotation = TextAnnotation;
    _a = TextAnnotation;
    TextAnnotation.__name__ = "TextAnnotation";
    (function () {
        _a.define(function () {
            return ({
                /** @deprecated */
                render_mode: [enums_1.RenderMode, "canvas"],
            });
        });
    })();
},
/* core/graphics.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var bbox_1 = require(180) /* ./util/bbox */;
    var text_1 = require(236) /* ./util/text */;
    var array_1 = require(126) /* ./util/array */;
    var types_1 = require(125) /* ./util/types */;
    var affine_1 = require(237) /* ./util/affine */;
    var color_1 = require(137) /* ./util/color */;
    exports.text_width = (function () {
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        var current_font = "";
        return function (text, font) {
            if (font != current_font) {
                current_font = font;
                ctx.font = font;
            }
            return ctx.measureText(text).width;
        };
    })();
    var GraphicsBox = /** @class */ (function () {
        function GraphicsBox() {
            this._position = { sx: 0, sy: 0 };
            this.font_size_scale = 1.0;
            this.align = "left";
            this._base_font_size = 13; // the same as .bk-root's font-size (13px)
            this._x_anchor = "left";
            this._y_anchor = "center";
        }
        Object.defineProperty(GraphicsBox.prototype, "base_font_size", {
            get: function () {
                return this._base_font_size;
            },
            set: function (v) {
                if (v != null)
                    this._base_font_size = v;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(GraphicsBox.prototype, "position", {
            get: function () {
                return this._position;
            },
            set: function (p) {
                this._position = p;
            },
            enumerable: false,
            configurable: true
        });
        GraphicsBox.prototype.infer_text_height = function () {
            return "ascent_descent";
        };
        GraphicsBox.prototype.bbox = function () {
            var _a = this.rect(), p0 = _a.p0, p1 = _a.p1, p2 = _a.p2, p3 = _a.p3;
            var left = Math.min(p0.x, p1.x, p2.x, p3.x);
            var top = Math.min(p0.y, p1.y, p2.y, p3.y);
            var right = Math.max(p0.x, p1.x, p2.x, p3.x);
            var bottom = Math.max(p0.y, p1.y, p2.y, p3.y);
            return new bbox_1.BBox({ left: left, right: right, top: top, bottom: bottom });
        };
        GraphicsBox.prototype.size = function () {
            var _a = this._size(), width = _a.width, height = _a.height;
            var angle = this.angle;
            if (!angle)
                return { width: width, height: height };
            else {
                var c = Math.cos(Math.abs(angle));
                var s = Math.sin(Math.abs(angle));
                return {
                    width: Math.abs(width * c + height * s),
                    height: Math.abs(width * s + height * c),
                };
            }
        };
        GraphicsBox.prototype.rect = function () {
            var rect = this._rect();
            var angle = this.angle;
            if (!angle)
                return rect;
            else {
                var _a = this.position, sx = _a.sx, sy = _a.sy;
                var tr = new affine_1.AffineTransform();
                tr.translate(sx, sy);
                tr.rotate(angle);
                tr.translate(-sx, -sy);
                return tr.apply_rect(rect);
            }
        };
        GraphicsBox.prototype.paint_rect = function (ctx) {
            var _a = this.rect(), p0 = _a.p0, p1 = _a.p1, p2 = _a.p2, p3 = _a.p3;
            ctx.save();
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.beginPath();
            var round = Math.round;
            ctx.moveTo(round(p0.x), round(p0.y));
            ctx.lineTo(round(p1.x), round(p1.y));
            ctx.lineTo(round(p2.x), round(p2.y));
            ctx.lineTo(round(p3.x), round(p3.y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        };
        GraphicsBox.prototype.paint_bbox = function (ctx) {
            var _a = this.bbox(), x = _a.x, y = _a.y, width = _a.width, height = _a.height;
            ctx.save();
            ctx.strokeStyle = "blue";
            ctx.lineWidth = 1;
            ctx.beginPath();
            var round = Math.round;
            ctx.moveTo(round(x), round(y));
            ctx.lineTo(round(x), round(y + height));
            ctx.lineTo(round(x + width), round(y + height));
            ctx.lineTo(round(x + width), round(y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        };
        return GraphicsBox;
    }());
    exports.GraphicsBox = GraphicsBox;
    GraphicsBox.__name__ = "GraphicsBox";
    var TextBox = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextBox, _super);
        function TextBox(_a) {
            var text = _a.text;
            var _this = _super.call(this) || this;
            _this.text = text;
            return _this;
        }
        Object.defineProperty(TextBox.prototype, "visuals", {
            //padding: Padding
            set: function (v) {
                var color = v.color;
                var alpha = v.alpha;
                var style = v.font_style;
                var size = v.font_size;
                var face = v.font;
                var _a = this, font_size_scale = _a.font_size_scale, base_font_size = _a.base_font_size;
                var res = (0, text_1.parse_css_font_size)(size);
                if (res != null) {
                    var value = res.value, unit = res.unit;
                    value *= font_size_scale;
                    if (unit == "em" && base_font_size) {
                        value *= base_font_size;
                        unit = "px";
                    }
                    size = "" + value + unit;
                }
                var font = style + " " + size + " " + face;
                this.font = font;
                this.color = (0, color_1.color2css)(color, alpha);
                this.line_height = v.line_height;
                var align = v.align;
                this._x_anchor = align;
                var baseline = v.baseline;
                this._y_anchor = (function () {
                    switch (baseline) {
                        case "top": return "top";
                        case "middle": return "center";
                        case "bottom": return "bottom";
                        default: return "baseline";
                    }
                })();
            },
            enumerable: false,
            configurable: true
        });
        TextBox.prototype.infer_text_height = function () {
            if (this.text.includes("\n"))
                return "ascent_descent";
            else {
                function is_math_like(text) {
                    var e_1, _a;
                    try {
                        for (var _b = (0, tslib_1.__values)(new Set(text)), _c = _b.next(); !_c.done; _c = _b.next()) {
                            var c = _c.value;
                            if ("0" <= c && c <= "9")
                                continue;
                            switch (c) {
                                case ",":
                                case ".":
                                case "+":
                                case "-":
                                case "\u2212":
                                case "e":
                                    continue;
                                default:
                                    return false;
                            }
                        }
                    }
                    catch (e_1_1) {
                        e_1 = { error: e_1_1 };
                    }
                    finally {
                        try {
                            if (_c && !_c.done && (_a = _b.return))
                                _a.call(_b);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                    }
                    return true;
                }
                if (is_math_like(this.text))
                    return "cap";
                else
                    return "ascent_descent";
                /*
                const {font} = this
                const fmetrics = font_metrics(font)
          
                let max_ascent = 0
                let max_descent = 0
                for (const c of this.text) {
                  const metrics = glyph_metrics(c, font)
                  max_ascent = Math.max(metrics.ascent)
                  max_descent = Math.max(metrics.descent)
                }
          
                const ascent = (() => {
                  if (max_ascent > fmetrics.cap_height)
                    return "ascent"
                  else if (max_ascent > fmetrics.x_height)
                    return "cap"
                  else
                    return "x"
                })()
          
                return max_descent > 0 ? `${ascent}_descent` as const : ascent
                */
            }
        };
        TextBox.prototype._text_line = function (fmetrics) {
            var _a;
            var metric = (_a = this.text_height_metric) !== null && _a !== void 0 ? _a : this.infer_text_height();
            var ascent = (function () {
                switch (metric) {
                    case "x":
                    case "x_descent":
                        return fmetrics.x_height;
                    case "cap":
                    case "cap_descent":
                        return fmetrics.cap_height;
                    case "ascent":
                    case "ascent_descent":
                        return fmetrics.ascent;
                }
            })();
            var descent = (function () {
                switch (metric) {
                    case "x":
                    case "cap":
                    case "ascent":
                        return 0;
                    case "x_descent":
                    case "cap_descent":
                    case "ascent_descent":
                        return fmetrics.descent;
                }
            })();
            return { height: ascent + descent, ascent: ascent, descent: descent };
        };
        Object.defineProperty(TextBox.prototype, "nlines", {
            get: function () {
                var lines = this.text.split("\n");
                return lines.length;
            },
            enumerable: false,
            configurable: true
        });
        TextBox.prototype._size = function () {
            var _a, _b;
            var font = this.font;
            var fmetrics = (0, text_1.font_metrics)(font);
            var line_spacing = (this.line_height - 1) * fmetrics.height; // TODO: max(trailing(L[n-1]), leading(L[n]))
            var empty = this.text == "";
            var lines = this.text.split("\n");
            var nlines = lines.length;
            var widths = lines.map(function (line) { return (0, exports.text_width)(line, font); });
            var text_line = this._text_line(fmetrics);
            var text_height = text_line.height * nlines;
            /*
            const heights: number[] = []
            const ascents: number[] = []
            const descents: number[] = []
        
            for (const line of lines) {
              const metrics = [...line].map((c) => glyph_metrics(c, font))
              const max_ascent = Math.max(max(metrics.map((m) => m.ascent)), fmetrics.cap_height)
              const max_descent = max(metrics.map((m) => m.descent))
              ascents.push(max_ascent)
              descents.push(max_descent)
              heights.push(max_ascent + max_descent)
            }
        
            const text_height = sum(heights)
            */
            var w_scale = ((_a = this.width) === null || _a === void 0 ? void 0 : _a.unit) == "%" ? this.width.value : 1;
            var h_scale = ((_b = this.height) === null || _b === void 0 ? void 0 : _b.unit) == "%" ? this.height.value : 1;
            var width = (0, array_1.max)(widths) * w_scale;
            var height = empty ? 0 : (text_height + line_spacing * (nlines - 1)) * h_scale;
            return { width: width, height: height, metrics: fmetrics };
        };
        TextBox.prototype._computed_position = function (size, metrics, nlines) {
            var _this = this;
            var width = size.width, height = size.height;
            var _a = this.position, sx = _a.sx, sy = _a.sy, _b = _a.x_anchor, x_anchor = _b === void 0 ? this._x_anchor : _b, _c = _a.y_anchor, y_anchor = _c === void 0 ? this._y_anchor : _c;
            var x = sx - (function () {
                if ((0, types_1.isNumber)(x_anchor))
                    return x_anchor * width;
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            var y = sy - (function () {
                var _a;
                if ((0, types_1.isNumber)(y_anchor))
                    return y_anchor * height;
                else {
                    switch (y_anchor) {
                        case "top": return 0;
                        case "center": return 0.5 * height;
                        case "bottom": return height;
                        case "baseline": {
                            if (nlines == 1) {
                                var metric = (_a = _this.text_height_metric) !== null && _a !== void 0 ? _a : _this.infer_text_height();
                                switch (metric) {
                                    case "x":
                                    case "x_descent":
                                        return metrics.x_height;
                                    case "cap":
                                    case "cap_descent":
                                        return metrics.cap_height;
                                    case "ascent":
                                    case "ascent_descent":
                                        return metrics.ascent;
                                }
                            }
                            else
                                return 0.5 * height;
                        }
                    }
                }
            })();
            return { x: x, y: y };
        };
        TextBox.prototype._rect = function () {
            var _a = this._size(), width = _a.width, height = _a.height, metrics = _a.metrics;
            var nlines = this.text.split("\n").length;
            var _b = this._computed_position({ width: width, height: height }, metrics, nlines), x = _b.x, y = _b.y;
            var bbox = new bbox_1.BBox({ x: x, y: y, width: width, height: height });
            return bbox.rect;
        };
        TextBox.prototype.paint = function (ctx) {
            var _a, _b;
            var font = this.font;
            var fmetrics = (0, text_1.font_metrics)(font);
            var line_spacing = (this.line_height - 1) * fmetrics.height; // TODO: see above
            var lines = this.text.split("\n");
            var nlines = lines.length;
            var widths = lines.map(function (line) { return (0, exports.text_width)(line, font); });
            var text_line = this._text_line(fmetrics);
            var text_height = text_line.height * nlines;
            /*
            const heights: number[] = []
            const ascents: number[] = []
            const descents: number[] = []
        
            for (const line of lines) {
              const metrics = [...line].map((c) => glyph_metrics(c, font))
              const max_ascent = Math.max(max(metrics.map((m) => m.ascent)), fmetrics.cap_height)
              const max_descent = max(metrics.map((m) => m.descent))
              ascents.push(max_ascent)
              descents.push(max_descent)
              heights.push(max_ascent + max_descent)
            }
            */
            var w_scale = ((_a = this.width) === null || _a === void 0 ? void 0 : _a.unit) == "%" ? this.width.value : 1;
            var h_scale = ((_b = this.height) === null || _b === void 0 ? void 0 : _b.unit) == "%" ? this.height.value : 1;
            var width = (0, array_1.max)(widths) * w_scale;
            var height = (text_height + line_spacing * (nlines - 1)) * h_scale;
            ctx.save();
            ctx.fillStyle = this.color;
            ctx.font = this.font;
            ctx.textAlign = "left";
            ctx.textBaseline = "alphabetic";
            var _c = this.position, sx = _c.sx, sy = _c.sy;
            var align = this.align;
            var angle = this.angle;
            if (angle) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            var _d = this._computed_position({ width: width, height: height }, fmetrics, nlines), x = _d.x, y = _d.y;
            if (align == "justify") {
                for (var i = 0; i < nlines; i++) {
                    var xij = x;
                    var line = lines[i];
                    var words = line.split(" ");
                    var nwords = words.length;
                    var word_widths = words.map(function (word) { return (0, exports.text_width)(word, font); });
                    var word_spacing = (width - (0, array_1.sum)(word_widths)) / (nwords - 1);
                    for (var j = 0; j < nwords; j++) {
                        ctx.fillText(words[j], xij, y);
                        xij += word_widths[j] + word_spacing;
                    }
                    y += /*heights[i]*/ text_line.height + line_spacing;
                }
            }
            else {
                var _loop_1 = function (i) {
                    var xi = x + (function () {
                        switch (align) {
                            case "left": return 0;
                            case "center": return 0.5 * (width - widths[i]);
                            case "right": return width - widths[i];
                        }
                    })();
                    ctx.fillStyle = this_1.color;
                    ctx.fillText(lines[i], xi, y + /*ascents[i]*/ text_line.ascent);
                    y += /*heights[i]*/ text_line.height + line_spacing;
                };
                var this_1 = this;
                for (var i = 0; i < nlines; i++) {
                    _loop_1(i);
                }
            }
            ctx.restore();
        };
        return TextBox;
    }(GraphicsBox));
    exports.TextBox = TextBox;
    TextBox.__name__ = "TextBox";
    var BaseExpo = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BaseExpo, _super);
        function BaseExpo(base, expo) {
            var _this = _super.call(this) || this;
            _this.base = base;
            _this.expo = expo;
            return _this;
        }
        Object.defineProperty(BaseExpo.prototype, "children", {
            get: function () {
                return [this.base, this.expo];
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BaseExpo.prototype, "base_font_size", {
            set: function (v) {
                _super.prototype.base_font_size = v;
                this.base.base_font_size = v;
                this.expo.base_font_size = v;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BaseExpo.prototype, "position", {
            get: function () {
                return this._position;
            },
            set: function (p) {
                this._position = p;
                var bs = this.base.size();
                var es = this.expo.size();
                var shift = this._shift_scale() * bs.height;
                var height = Math.max(bs.height, shift + es.height);
                this.base.position = {
                    sx: 0, x_anchor: "left",
                    sy: height, y_anchor: "bottom",
                };
                this.expo.position = {
                    sx: bs.width, x_anchor: "left",
                    sy: shift, y_anchor: "bottom",
                };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BaseExpo.prototype, "visuals", {
            set: function (v) {
                this.expo.font_size_scale = 0.7;
                this.base.visuals = v;
                this.expo.visuals = v;
            },
            enumerable: false,
            configurable: true
        });
        BaseExpo.prototype._shift_scale = function () {
            if (this.base instanceof TextBox && this.base.nlines == 1) {
                var _a = (0, text_1.font_metrics)(this.base.font), x_height = _a.x_height, cap_height = _a.cap_height;
                return x_height / cap_height;
            }
            else {
                return 2 / 3;
            }
        };
        BaseExpo.prototype.infer_text_height = function () {
            return this.base.infer_text_height();
        };
        BaseExpo.prototype._rect = function () {
            var bb = this.base.bbox();
            var eb = this.expo.bbox();
            var bbox = bb.union(eb);
            var _a = this._computed_position(), x = _a.x, y = _a.y;
            return bbox.translate(x, y).rect;
        };
        BaseExpo.prototype._size = function () {
            var bs = this.base.size();
            var es = this.expo.size();
            return {
                width: bs.width + es.width,
                height: Math.max(bs.height, this._shift_scale() * bs.height + es.height),
            };
        };
        BaseExpo.prototype.paint = function (ctx) {
            ctx.save();
            var angle = this.angle;
            if (angle) {
                var _a = this.position, sx = _a.sx, sy = _a.sy;
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            var _b = this._computed_position(), x = _b.x, y = _b.y;
            ctx.translate(x, y);
            this.base.paint(ctx);
            this.expo.paint(ctx);
            ctx.restore();
        };
        // paint_rect ...
        BaseExpo.prototype.paint_bbox = function (ctx) {
            var e_2, _a;
            _super.prototype.paint_bbox.call(this, ctx);
            var _b = this._computed_position(), x = _b.x, y = _b.y;
            ctx.save();
            ctx.translate(x, y);
            try {
                for (var _c = (0, tslib_1.__values)(this.children), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var child = _d.value;
                    child.paint_bbox(ctx);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return))
                        _a.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            ctx.restore();
        };
        BaseExpo.prototype._computed_position = function () {
            var _a = this._size(), width = _a.width, height = _a.height;
            var _b = this.position, sx = _b.sx, sy = _b.sy, _c = _b.x_anchor, x_anchor = _c === void 0 ? this._x_anchor : _c, _d = _b.y_anchor, y_anchor = _d === void 0 ? this._y_anchor : _d;
            var x = sx - (function () {
                if ((0, types_1.isNumber)(x_anchor))
                    return x_anchor * width;
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            var y = sy - (function () {
                if ((0, types_1.isNumber)(y_anchor))
                    return y_anchor * height;
                else {
                    switch (y_anchor) {
                        case "top": return 0;
                        case "center": return 0.5 * height;
                        case "bottom": return height;
                        case "baseline": return 0.5 * height; /* TODO */
                    }
                }
            })();
            return { x: x, y: y };
        };
        return BaseExpo;
    }(GraphicsBox));
    exports.BaseExpo = BaseExpo;
    BaseExpo.__name__ = "BaseExpo";
    var GraphicsBoxes = /** @class */ (function () {
        function GraphicsBoxes(items) {
            this.items = items;
        }
        Object.defineProperty(GraphicsBoxes.prototype, "base_font_size", {
            set: function (v) {
                var e_3, _a;
                try {
                    for (var _b = (0, tslib_1.__values)(this.items), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var item = _c.value;
                        item.base_font_size = v;
                    }
                }
                catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_3)
                            throw e_3.error;
                    }
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(GraphicsBoxes.prototype, "length", {
            get: function () {
                return this.items.length;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(GraphicsBoxes.prototype, "visuals", {
            set: function (v) {
                var e_4, _a, e_5, _b;
                try {
                    for (var _c = (0, tslib_1.__values)(this.items), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var item = _d.value;
                        item.visuals = v;
                    }
                }
                catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_a = _c.return))
                            _a.call(_c);
                    }
                    finally {
                        if (e_4)
                            throw e_4.error;
                    }
                }
                var metric_map = { x: 0, cap: 1, ascent: 2, x_descent: 3, cap_descent: 4, ascent_descent: 5 };
                var common = (0, array_1.max_by)(this.items.map(function (item) { return item.infer_text_height(); }), function (metric) { return metric_map[metric]; });
                try {
                    for (var _e = (0, tslib_1.__values)(this.items), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var item = _f.value;
                        item.text_height_metric = common;
                    }
                }
                catch (e_5_1) {
                    e_5 = { error: e_5_1 };
                }
                finally {
                    try {
                        if (_f && !_f.done && (_b = _e.return))
                            _b.call(_e);
                    }
                    finally {
                        if (e_5)
                            throw e_5.error;
                    }
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(GraphicsBoxes.prototype, "angle", {
            set: function (a) {
                var e_6, _a;
                try {
                    for (var _b = (0, tslib_1.__values)(this.items), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var item = _c.value;
                        item.angle = a;
                    }
                }
                catch (e_6_1) {
                    e_6 = { error: e_6_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_6)
                            throw e_6.error;
                    }
                }
            },
            enumerable: false,
            configurable: true
        });
        GraphicsBoxes.prototype.max_size = function () {
            var e_7, _a;
            var width = 0;
            var height = 0;
            try {
                for (var _b = (0, tslib_1.__values)(this.items), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var item = _c.value;
                    var size = item.size();
                    width = Math.max(width, size.width);
                    height = Math.max(height, size.height);
                }
            }
            catch (e_7_1) {
                e_7 = { error: e_7_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_7)
                        throw e_7.error;
                }
            }
            return { width: width, height: height };
        };
        return GraphicsBoxes;
    }());
    exports.GraphicsBoxes = GraphicsBoxes;
    GraphicsBoxes.__name__ = "GraphicsBoxes";
},
/* core/util/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var assert_1 = require(127) /* ./assert */;
    var has_OffscreenCanvas = (function () {
        try {
            return typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(0, 0).getContext("2d") != null;
        }
        catch (_a) {
            return false;
        }
    })();
    var _offscreen_canvas = (function () {
        if (has_OffscreenCanvas)
            return function (w, h) { return new OffscreenCanvas(w, h); };
        else {
            return function (w, h) {
                var canvas = document.createElement("canvas");
                canvas.width = w;
                canvas.height = h;
                return canvas;
            };
        }
    })();
    var _native_font_metrics = (function () {
        var canvas = _offscreen_canvas(0, 0);
        var ctx = canvas.getContext("2d");
        return function (font) {
            ctx.font = font;
            var cap_metrics = ctx.measureText("M");
            var x_metrics = ctx.measureText("x");
            var metrics = ctx.measureText("ÅŚg|");
            var font_ascent = metrics.fontBoundingBoxAscent;
            var font_descent = metrics.fontBoundingBoxDescent;
            if (font_ascent != null && font_descent != null) {
                return {
                    height: font_ascent + font_descent,
                    ascent: font_ascent,
                    descent: font_descent,
                    cap_height: cap_metrics.actualBoundingBoxAscent,
                    x_height: x_metrics.actualBoundingBoxAscent,
                };
            }
            var text_ascent = metrics.actualBoundingBoxAscent;
            var text_descent = metrics.actualBoundingBoxDescent;
            if (text_ascent != null && text_descent != null) {
                return {
                    height: text_ascent + text_descent,
                    ascent: text_ascent,
                    descent: text_descent,
                    cap_height: cap_metrics.actualBoundingBoxAscent,
                    x_height: x_metrics.actualBoundingBoxAscent,
                };
            }
            (0, assert_1.unreachable)();
        };
    })();
    var _native_glyph_metrics = (function () {
        var canvas = _offscreen_canvas(0, 0);
        var ctx = canvas.getContext("2d");
        return function (glyph, font) {
            ctx.font = font;
            var metrics = ctx.measureText(glyph);
            var glyph_ascent = metrics.actualBoundingBoxAscent;
            var glyph_descent = metrics.actualBoundingBoxDescent;
            if (glyph_ascent != null && glyph_descent != null) {
                return {
                    width: metrics.width,
                    height: glyph_ascent + glyph_descent,
                    ascent: glyph_ascent,
                    descent: glyph_descent,
                };
            }
            (0, assert_1.unreachable)();
        };
    })();
    var _internal_font_metrics = (function () {
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        var cwidth = -1;
        var cheight = -1;
        return function (font, scale) {
            var e_1, _a, e_2, _b, e_3, _c;
            if (scale === void 0) {
                scale = 1;
            }
            ctx.font = font;
            var _em = ctx.measureText("M").width;
            var em = _em * scale;
            var width = Math.ceil(em);
            var height = Math.ceil(2.0 * em);
            var baseline = Math.ceil(1.5 * em);
            if (cwidth < width) {
                cwidth = width;
                canvas.width = width;
            }
            if (cheight < height) {
                cheight = height;
                canvas.height = height;
            }
            ctx.save();
            ctx.scale(scale, scale);
            ctx.fillStyle = "#f00";
            ctx.fillRect(0, 0, width, height);
            var measure_ascent = function (data) {
                var k = 0;
                for (var i = 0; i <= baseline; i++) {
                    for (var j = 0; j < width; j++, k += 4)
                        if (data[k] != 255)
                            return baseline - i;
                }
                return 0;
            };
            var measure_descent = function (data) {
                var k = data.length - 4;
                for (var i = height; i >= baseline; i--) {
                    for (var j = 0; j < width; j++, k -= 4)
                        if (data[k] != 255)
                            return i - baseline;
                }
                return 0;
            };
            ctx.font = font;
            ctx.fillStyle = "#000";
            try {
                for (var _d = (0, tslib_1.__values)("xa"), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var c = _e.value;
                    ctx.fillText(c, 0, baseline / scale);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_a = _d.return))
                        _a.call(_d);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            var data0 = ctx.getImageData(0, 0, width, height).data;
            var x_height = measure_ascent(data0) / scale;
            try {
                for (var _f = (0, tslib_1.__values)("ASQ"), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var c = _g.value;
                    ctx.fillText(c, 0, baseline / scale);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_b = _f.return))
                        _b.call(_f);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            var data1 = ctx.getImageData(0, 0, width, height).data;
            var cap_height = measure_ascent(data1) / scale;
            try {
                for (var _h = (0, tslib_1.__values)("ÅŚgy"), _j = _h.next(); !_j.done; _j = _h.next()) {
                    var c = _j.value;
                    ctx.fillText(c, 0, baseline / scale);
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_j && !_j.done && (_c = _h.return))
                        _c.call(_h);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            var data2 = ctx.getImageData(0, 0, width, height).data;
            var ascent = measure_ascent(data2) / scale;
            var descent = measure_descent(data2) / scale;
            ctx.restore();
            return { height: ascent + descent, ascent: ascent, cap_height: cap_height, x_height: x_height, descent: descent };
        };
    })();
    var _internal_glyph_metrics = (function () {
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        var cwidth = -1;
        var cheight = -1;
        return function (glyph, font, scale) {
            if (scale === void 0) {
                scale = 1;
            }
            ctx.font = font;
            var _em = ctx.measureText("M").width;
            var em = _em * scale;
            var width = Math.ceil(em);
            var height = Math.ceil(2.0 * em);
            var baseline = Math.ceil(1.5 * em);
            if (cwidth < width || cheight < height) {
                cwidth = width;
                canvas.width = width;
                cheight = height;
                canvas.height = height;
            }
            ctx.save();
            ctx.scale(scale, scale);
            ctx.fillStyle = "#f00";
            ctx.fillRect(0, 0, width, height);
            var measure_ascent = function (data) {
                var k = 0;
                for (var i = 0; i <= baseline; i++) {
                    for (var j = 0; j < width; j++, k += 4)
                        if (data[k] != 255)
                            return baseline - i;
                }
                return 0;
            };
            var measure_descent = function (data) {
                var k = data.length - 4;
                for (var i = height; i >= baseline; i--) {
                    for (var j = 0; j < width; j++, k -= 4)
                        if (data[k] != 255)
                            return i - baseline;
                }
                return 0;
            };
            ctx.font = font;
            ctx.fillStyle = "#000";
            ctx.fillText(glyph, 0, baseline / scale);
            var size = ctx.measureText(glyph);
            var data = ctx.getImageData(0, 0, width, height).data;
            var ascent = measure_ascent(data) / scale;
            var descent = measure_descent(data) / scale;
            ctx.restore();
            return { width: size.width, height: ascent + descent, ascent: ascent, descent: descent };
        };
    })();
    var _font_metrics = (function () {
        try {
            _native_font_metrics("normal 10px sans-serif");
            return _native_font_metrics;
        }
        catch (_a) {
            return _internal_font_metrics;
        }
    })();
    var _glyph_metrics = (function () {
        try {
            _native_glyph_metrics("A", "normal 10px sans-serif");
            return _native_glyph_metrics;
        }
        catch (_a) {
            return _internal_glyph_metrics;
        }
    })();
    var _metrics_cache = new Map();
    function font_metrics(font) {
        var metrics = _metrics_cache.get(font);
        if (metrics == null) {
            // TODO: document.fonts.check(font)
            metrics = { font: _font_metrics(font), glyphs: new Map() };
            _metrics_cache.set(font, metrics);
        }
        return metrics.font;
    }
    exports.font_metrics = font_metrics;
    function glyph_metrics(glyph, font) {
        var metrics = _metrics_cache.get(font);
        if (metrics == null) {
            font_metrics(font);
            metrics = _metrics_cache.get(font);
        }
        var glyph_metrics = metrics.glyphs.get(glyph);
        if (glyph_metrics == null) {
            glyph_metrics = _glyph_metrics(glyph, font);
            metrics.glyphs.set(glyph, glyph_metrics);
        }
        return glyph_metrics;
    }
    exports.glyph_metrics = glyph_metrics;
    function parse_css_font_size(size) {
        var match = size.match(/^\s*(\d+(\.\d+)?)(\w+)\s*$/);
        if (match != null) {
            var _a = (0, tslib_1.__read)(match, 4), value = _a[1], unit = _a[3];
            var number = Number(value);
            if (isFinite(number))
                return { value: number, unit: unit };
        }
        return null;
    }
    exports.parse_css_font_size = parse_css_font_size;
},
/* core/util/affine.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var sin = Math.sin, cos = Math.cos;
    var AffineTransform = /** @class */ (function () {
        function AffineTransform(a, b, c, d, e, f) {
            if (a === void 0) {
                a = 1;
            }
            if (b === void 0) {
                b = 0;
            }
            if (c === void 0) {
                c = 0;
            }
            if (d === void 0) {
                d = 1;
            }
            if (e === void 0) {
                e = 0;
            }
            if (f === void 0) {
                f = 0;
            }
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.e = e;
            this.f = f;
        }
        AffineTransform.prototype.toString = function () {
            var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, e = _a.e, f = _a.f;
            return "matrix(" + a + ", " + b + ", " + c + ", " + d + ", " + e + ", " + f + ")";
        };
        AffineTransform.from_DOMMatrix = function (matrix) {
            var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, e = matrix.e, f = matrix.f;
            return new AffineTransform(a, b, c, d, e, f);
        };
        AffineTransform.prototype.to_DOMMatrix = function () {
            var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, e = _a.e, f = _a.f;
            return new DOMMatrix([a, b, c, d, e, f]);
        };
        AffineTransform.prototype.clone = function () {
            var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, e = _a.e, f = _a.f;
            return new AffineTransform(a, b, c, d, e, f);
        };
        Object.defineProperty(AffineTransform.prototype, "is_identity", {
            get: function () {
                var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, e = _a.e, f = _a.f;
                return a == 1 && b == 0 && c == 0 && d == 1 && e == 0 && f == 0;
            },
            enumerable: false,
            configurable: true
        });
        AffineTransform.prototype.apply_point = function (p) {
            var _a = (0, tslib_1.__read)(this.apply(p.x, p.y), 2), x = _a[0], y = _a[1];
            return { x: x, y: y };
        };
        AffineTransform.prototype.apply_rect = function (rect) {
            var p0 = this.apply_point(rect.p0);
            var p1 = this.apply_point(rect.p1);
            var p2 = this.apply_point(rect.p2);
            var p3 = this.apply_point(rect.p3);
            return { p0: p0, p1: p1, p2: p2, p3: p3 };
        };
        AffineTransform.prototype.apply = function (x, y) {
            var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, e = _a.e, f = _a.f;
            return [
                a * x + c * y + e,
                b * x + d * y + f,
            ];
        };
        AffineTransform.prototype.iv_apply = function (xs, ys) {
            var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, e = _a.e, f = _a.f;
            var n = xs.length;
            for (var i = 0; i < n; i++) {
                var x = xs[i];
                var y = ys[i];
                xs[i] = a * x + c * y + e;
                ys[i] = b * x + d * y + f;
            }
        };
        AffineTransform.prototype.transform = function (A, B, C, D, E, F) {
            var _a = this, a = _a.a, b = _a.b, c = _a.c, d = _a.d, e = _a.e, f = _a.f;
            this.a = a * A + c * B;
            this.c = a * C + c * D;
            this.e = a * E + c * F + e;
            this.b = b * A + d * B;
            this.d = b * C + d * D;
            this.f = b * E + d * F + f;
            return this;
        };
        AffineTransform.prototype.translate = function (tx, ty) {
            return this.transform(1, 0, 0, 1, tx, ty);
        };
        AffineTransform.prototype.scale = function (cx, cy) {
            return this.transform(cx, 0, 0, cy, 0, 0);
        };
        AffineTransform.prototype.skew = function (sx, sy) {
            return this.transform(1, sy, sx, 1, 0, 0);
        };
        AffineTransform.prototype.rotate = function (angle) {
            var s = sin(angle);
            var c = cos(angle);
            return this.transform(c, s, -s, c, 0, 0);
        };
        AffineTransform.prototype.rotate_ccw = function (angle) {
            return this.rotate(-angle);
        };
        AffineTransform.prototype.translate_x = function (tx) {
            return this.translate(tx, 0);
        };
        AffineTransform.prototype.translate_y = function (ty) {
            return this.translate(0, ty);
        };
        AffineTransform.prototype.flip = function () {
            return this.scale(-1, -1);
        };
        AffineTransform.prototype.flip_x = function () {
            return this.scale(1, -1);
        };
        AffineTransform.prototype.flip_y = function () {
            return this.scale(-1, 1);
        };
        return AffineTransform;
    }());
    exports.AffineTransform = AffineTransform;
    AffineTransform.__name__ = "AffineTransform";
},
/* core/layout/side_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var types_1 = require(239) /* ./types */;
    var layoutable_1 = require(240) /* ./layoutable */;
    var types_2 = require(125) /* ../util/types */;
    // This table lays out the rules for configuring the baseline, alignment, etc. of
    // title text, based on it's location and orientation
    //
    // side    orient        baseline   align     angle   normal-dist
    // ------------------------------------------------------------------------------
    // above   parallel      bottom     center    0       height
    //         normal        middle     left      -90     width
    //         horizontal    bottom     center    0       height
    //         [angle > 0]   middle     left              width * sin + height * cos
    //         [angle < 0]   middle     right             width * sin + height * cos
    //
    // below   parallel      top        center    0       height
    //         normal        middle     right     90      width
    //         horizontal    top        center    0       height
    //         [angle > 0]   middle     right             width * sin + height * cos
    //         [angle < 0]   middle     left              width * sin + height * cos
    //
    // left    parallel      bottom     center    90      height
    //         normal        middle     right     0       width
    //         horizontal    middle     right     0       width
    //         [angle > 0]   middle     right             width * cos + height * sin
    //         [angle < 0]   middle     right             width * cos + height + sin
    //
    // right   parallel      bottom     center   -90      height
    //         normal        middle     left     0        width
    //         horizontal    middle     left     0        width
    //         [angle > 0]   middle     left              width * cos + height * sin
    //         [angle < 0]   middle     left              width * cos + height + sin
    var pi2 = Math.PI / 2;
    var _angle_lookup = {
        above: {
            parallel: 0,
            normal: -pi2,
            horizontal: 0,
            vertical: -pi2,
        },
        below: {
            parallel: 0,
            normal: pi2,
            horizontal: 0,
            vertical: pi2,
        },
        left: {
            parallel: -pi2,
            normal: 0,
            horizontal: 0,
            vertical: -pi2,
        },
        right: {
            parallel: pi2,
            normal: 0,
            horizontal: 0,
            vertical: pi2,
        },
    };
    var _vertical_align_lookup = {
        above: {
            parallel: "bottom",
            normal: "center",
            horizontal: "bottom",
            vertical: "center",
        },
        below: {
            parallel: "top",
            normal: "center",
            horizontal: "top",
            vertical: "center",
        },
        left: {
            parallel: "bottom",
            normal: "center",
            horizontal: "center",
            vertical: "bottom",
        },
        right: {
            parallel: "bottom",
            normal: "center",
            horizontal: "center",
            vertical: "bottom",
        },
    };
    var _align_lookup = {
        above: {
            parallel: "center",
            normal: "left",
            horizontal: "center",
            vertical: "left",
        },
        below: {
            parallel: "center",
            normal: "left",
            horizontal: "center",
            vertical: "left",
        },
        left: {
            parallel: "center",
            normal: "right",
            horizontal: "right",
            vertical: "center",
        },
        right: {
            parallel: "center",
            normal: "left",
            horizontal: "left",
            vertical: "center",
        },
    };
    var _align_lookup_negative = {
        above: "right",
        below: "left",
        left: "right",
        right: "left",
    };
    var _align_lookup_positive = {
        above: "left",
        below: "right",
        left: "right",
        right: "left",
    };
    var Panel = /** @class */ (function () {
        function Panel(side) {
            this.side = side;
        }
        Object.defineProperty(Panel.prototype, "dimension", {
            get: function () {
                return this.side == "above" || this.side == "below" ? 0 : 1;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Panel.prototype, "normals", {
            get: function () {
                switch (this.side) {
                    case "above": return [0, -1];
                    case "below": return [0, 1];
                    case "left": return [-1, 0];
                    case "right": return [1, 0];
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Panel.prototype, "orientation", {
            get: function () {
                return this.is_horizontal ? "horizontal" : "vertical";
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Panel.prototype, "is_horizontal", {
            get: function () {
                return this.dimension == 0;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Panel.prototype, "is_vertical", {
            get: function () {
                return this.dimension == 1;
            },
            enumerable: false,
            configurable: true
        });
        Panel.prototype.get_label_text_heuristics = function (orient) {
            var side = this.side;
            if ((0, types_2.isString)(orient)) {
                return {
                    vertical_align: _vertical_align_lookup[side][orient],
                    align: _align_lookup[side][orient],
                };
            }
            else {
                return {
                    vertical_align: "center",
                    align: (orient < 0 ? _align_lookup_negative : _align_lookup_positive)[side],
                };
            }
        };
        Panel.prototype.get_label_angle_heuristic = function (orient) {
            if ((0, types_2.isString)(orient))
                return _angle_lookup[this.side][orient];
            else
                return -orient;
        };
        return Panel;
    }());
    exports.Panel = Panel;
    Panel.__name__ = "Panel";
    var SideLayout = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SideLayout, _super);
        function SideLayout(panel, get_size, rotate) {
            if (rotate === void 0) {
                rotate = false;
            }
            var _this = _super.call(this) || this;
            _this.panel = panel;
            _this.get_size = get_size;
            _this.rotate = rotate;
            if (_this.panel.is_horizontal)
                _this.set_sizing({ width_policy: "max", height_policy: "fixed" });
            else
                _this.set_sizing({ width_policy: "fixed", height_policy: "max" });
            return _this;
        }
        SideLayout.prototype._content_size = function () {
            var _a = this.get_size(), width = _a.width, height = _a.height;
            if (!this.rotate || this.panel.is_horizontal)
                return new types_1.Sizeable({ width: width, height: height });
            else
                return new types_1.Sizeable({ width: height, height: width });
        };
        SideLayout.prototype.has_size_changed = function () {
            var _a = this._content_size(), width = _a.width, height = _a.height;
            if (this.panel.is_horizontal)
                return this.bbox.height != height;
            else
                return this.bbox.width != width;
        };
        return SideLayout;
    }(layoutable_1.ContentLayoutable));
    exports.SideLayout = SideLayout;
    SideLayout.__name__ = "SideLayout";
},
/* core/layout/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var kinds_1 = require(136) /* ../kinds */;
    var min = Math.min, max = Math.max;
    var Sizeable = /** @class */ (function () {
        function Sizeable(size) {
            if (size === void 0) {
                size = {};
            }
            this.width = size.width != null ? size.width : 0;
            this.height = size.height != null ? size.height : 0;
        }
        Sizeable.prototype.bounded_to = function (_a) {
            var width = _a.width, height = _a.height;
            return new Sizeable({
                width: this.width == Infinity && width != null ? width : this.width,
                height: this.height == Infinity && height != null ? height : this.height,
            });
        };
        Sizeable.prototype.expanded_to = function (_a) {
            var width = _a.width, height = _a.height;
            return new Sizeable({
                width: width != Infinity ? max(this.width, width) : this.width,
                height: height != Infinity ? max(this.height, height) : this.height,
            });
        };
        Sizeable.prototype.expand_to = function (_a) {
            var width = _a.width, height = _a.height;
            this.width = max(this.width, width);
            this.height = max(this.height, height);
        };
        Sizeable.prototype.narrowed_to = function (_a) {
            var width = _a.width, height = _a.height;
            return new Sizeable({
                width: min(this.width, width),
                height: min(this.height, height),
            });
        };
        Sizeable.prototype.narrow_to = function (_a) {
            var width = _a.width, height = _a.height;
            this.width = min(this.width, width);
            this.height = min(this.height, height);
        };
        Sizeable.prototype.grow_by = function (_a) {
            var left = _a.left, right = _a.right, top = _a.top, bottom = _a.bottom;
            var width = this.width + left + right;
            var height = this.height + top + bottom;
            return new Sizeable({ width: width, height: height });
        };
        Sizeable.prototype.shrink_by = function (_a) {
            var left = _a.left, right = _a.right, top = _a.top, bottom = _a.bottom;
            var width = max(this.width - left - right, 0);
            var height = max(this.height - top - bottom, 0);
            return new Sizeable({ width: width, height: height });
        };
        Sizeable.prototype.map = function (w_fn, h_fn) {
            return new Sizeable({
                width: w_fn(this.width),
                height: (h_fn != null ? h_fn : w_fn)(this.height),
            });
        };
        return Sizeable;
    }());
    exports.Sizeable = Sizeable;
    Sizeable.__name__ = "Sizeable";
    exports.SizingPolicy = (0, kinds_1.Enum)("fixed", "fit", "min", "max");
},
/* core/layout/layoutable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var types_1 = require(239) /* ./types */;
    var bbox_1 = require(180) /* ../util/bbox */;
    var types_2 = require(125) /* ../util/types */;
    var min = Math.min, max = Math.max, round = Math.round;
    var Layoutable = /** @class */ (function () {
        function Layoutable() {
            this.absolute = false;
            this._bbox = new bbox_1.BBox();
            this._inner_bbox = new bbox_1.BBox();
            this._dirty = false;
            this._handlers = [];
        }
        Layoutable.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                return [2 /*return*/];
            });
        };
        Object.defineProperty(Layoutable.prototype, "bbox", {
            get: function () {
                return this._bbox;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Layoutable.prototype, "inner_bbox", {
            get: function () {
                return this._inner_bbox;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Layoutable.prototype, "sizing", {
            get: function () {
                return this._sizing;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Layoutable.prototype, "visible", {
            set: function (visible) {
                this._sizing.visible = visible;
                this._dirty = true;
            },
            enumerable: false,
            configurable: true
        });
        Layoutable.prototype.set_sizing = function (sizing) {
            var _a, _b, _c, _d, _e;
            var width_policy = (_a = sizing.width_policy) !== null && _a !== void 0 ? _a : "fit";
            var width = sizing.width;
            var min_width = sizing.min_width;
            var max_width = sizing.max_width;
            var height_policy = (_b = sizing.height_policy) !== null && _b !== void 0 ? _b : "fit";
            var height = sizing.height;
            var min_height = sizing.min_height;
            var max_height = sizing.max_height;
            var aspect = sizing.aspect;
            var margin = (_c = sizing.margin) !== null && _c !== void 0 ? _c : { top: 0, right: 0, bottom: 0, left: 0 };
            var visible = sizing.visible !== false;
            var halign = (_d = sizing.halign) !== null && _d !== void 0 ? _d : "start";
            var valign = (_e = sizing.valign) !== null && _e !== void 0 ? _e : "start";
            this._sizing = {
                width_policy: width_policy,
                min_width: min_width,
                width: width,
                max_width: max_width,
                height_policy: height_policy,
                min_height: min_height,
                height: height,
                max_height: max_height,
                aspect: aspect,
                margin: margin,
                visible: visible,
                halign: halign,
                valign: valign,
                size: { width: width, height: height },
            };
            this._init();
        };
        Layoutable.prototype._init = function () { };
        Layoutable.prototype._set_geometry = function (outer, inner) {
            this._bbox = outer;
            this._inner_bbox = inner;
        };
        Layoutable.prototype.set_geometry = function (outer, inner) {
            var _a, e_1, _b;
            var fixup_geometry = this.fixup_geometry;
            if (fixup_geometry != null) {
                _a = (0, tslib_1.__read)(fixup_geometry(outer, inner), 2), outer = _a[0], inner = _a[1];
            }
            this._set_geometry(outer, inner !== null && inner !== void 0 ? inner : outer);
            try {
                for (var _c = (0, tslib_1.__values)(this._handlers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var handler = _d.value;
                    handler(this._bbox, this._inner_bbox);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        Layoutable.prototype.on_resize = function (handler) {
            this._handlers.push(handler);
        };
        Layoutable.prototype.is_width_expanding = function () {
            return this.sizing.width_policy == "max";
        };
        Layoutable.prototype.is_height_expanding = function () {
            return this.sizing.height_policy == "max";
        };
        Layoutable.prototype.apply_aspect = function (viewport, _a) {
            var width = _a.width, height = _a.height;
            var aspect = this.sizing.aspect;
            if (aspect != null) {
                var _b = this.sizing, width_policy = _b.width_policy, height_policy = _b.height_policy;
                var gt = function (width, height) {
                    var policies = { max: 4, fit: 3, min: 2, fixed: 1 };
                    return policies[width] > policies[height];
                };
                if (width_policy != "fixed" && height_policy != "fixed") {
                    if (width_policy == height_policy) {
                        var w_width = width;
                        var w_height = round(width / aspect);
                        var h_width = round(height * aspect);
                        var h_height = height;
                        var w_diff = Math.abs(viewport.width - w_width) + Math.abs(viewport.height - w_height);
                        var h_diff = Math.abs(viewport.width - h_width) + Math.abs(viewport.height - h_height);
                        if (w_diff <= h_diff) {
                            width = w_width;
                            height = w_height;
                        }
                        else {
                            width = h_width;
                            height = h_height;
                        }
                    }
                    else if (gt(width_policy, height_policy)) {
                        height = round(width / aspect);
                    }
                    else {
                        width = round(height * aspect);
                    }
                }
                else if (width_policy == "fixed") {
                    height = round(width / aspect);
                }
                else if (height_policy == "fixed") {
                    width = round(height * aspect);
                }
            }
            return { width: width, height: height };
        };
        Layoutable.prototype.measure = function (viewport_size) {
            var _this = this;
            if (!this.sizing.visible)
                return { width: 0, height: 0 };
            var exact_width = function (width) {
                return _this.sizing.width_policy == "fixed" && _this.sizing.width != null ? _this.sizing.width : width;
            };
            var exact_height = function (height) {
                return _this.sizing.height_policy == "fixed" && _this.sizing.height != null ? _this.sizing.height : height;
            };
            var viewport = new types_1.Sizeable(viewport_size)
                .shrink_by(this.sizing.margin)
                .map(exact_width, exact_height);
            var computed = this._measure(viewport);
            var clipped = this.clip_size(computed, viewport);
            var width = exact_width(clipped.width);
            var height = exact_height(clipped.height);
            var size = this.apply_aspect(viewport, { width: width, height: height });
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, computed), size);
        };
        Layoutable.prototype.compute = function (viewport) {
            if (viewport === void 0) {
                viewport = {};
            }
            var size_hint = this.measure({
                width: viewport.width != null && this.is_width_expanding() ? viewport.width : Infinity,
                height: viewport.height != null && this.is_height_expanding() ? viewport.height : Infinity,
            });
            var width = size_hint.width, height = size_hint.height;
            var outer = new bbox_1.BBox({ left: 0, top: 0, width: width, height: height });
            var inner = undefined;
            if (size_hint.inner != null) {
                var _a = size_hint.inner, left = _a.left, top = _a.top, right = _a.right, bottom = _a.bottom;
                inner = new bbox_1.BBox({ left: left, top: top, right: width - right, bottom: height - bottom });
            }
            this.set_geometry(outer, inner);
        };
        Object.defineProperty(Layoutable.prototype, "xview", {
            get: function () {
                return this.bbox.xview;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Layoutable.prototype, "yview", {
            get: function () {
                return this.bbox.yview;
            },
            enumerable: false,
            configurable: true
        });
        Layoutable.prototype.clip_size = function (size, viewport) {
            function clip(size, vsize, min_size, max_size) {
                if (min_size == null)
                    min_size = 0;
                else if (!(0, types_2.isNumber)(min_size))
                    min_size = Math.round(min_size.percent * vsize);
                if (max_size == null)
                    max_size = Infinity;
                else if (!(0, types_2.isNumber)(max_size))
                    max_size = Math.round(max_size.percent * vsize);
                return max(min_size, min(size, max_size));
            }
            return {
                width: clip(size.width, viewport.width, this.sizing.min_width, this.sizing.max_width),
                height: clip(size.height, viewport.height, this.sizing.min_height, this.sizing.max_height),
            };
        };
        Layoutable.prototype.has_size_changed = function () {
            var _dirty = this._dirty;
            this._dirty = false;
            return _dirty;
        };
        return Layoutable;
    }());
    exports.Layoutable = Layoutable;
    Layoutable.__name__ = "Layoutable";
    var LayoutItem = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LayoutItem, _super);
        function LayoutItem() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LayoutItem.prototype._measure = function (viewport) {
            var _this = this;
            var _a = this.sizing, width_policy = _a.width_policy, height_policy = _a.height_policy;
            var width = (function () {
                var width = _this.sizing.width;
                if (viewport.width == Infinity) {
                    return width !== null && width !== void 0 ? width : 0;
                }
                else {
                    switch (width_policy) {
                        case "fixed": return width !== null && width !== void 0 ? width : 0;
                        case "min": return width != null ? min(viewport.width, width) : 0;
                        case "fit": return width != null ? min(viewport.width, width) : viewport.width;
                        case "max": return width != null ? max(viewport.width, width) : viewport.width;
                    }
                }
            })();
            var height = (function () {
                var height = _this.sizing.height;
                if (viewport.height == Infinity) {
                    return height !== null && height !== void 0 ? height : 0;
                }
                else {
                    switch (height_policy) {
                        case "fixed": return height !== null && height !== void 0 ? height : 0;
                        case "min": return height != null ? min(viewport.height, height) : 0;
                        case "fit": return height != null ? min(viewport.height, height) : viewport.height;
                        case "max": return height != null ? max(viewport.height, height) : viewport.height;
                    }
                }
            })();
            return { width: width, height: height };
        };
        return LayoutItem;
    }(Layoutable));
    exports.LayoutItem = LayoutItem;
    LayoutItem.__name__ = "LayoutItem";
    var ContentLayoutable = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ContentLayoutable, _super);
        function ContentLayoutable() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ContentLayoutable.prototype._measure = function (viewport) {
            var _this = this;
            var content_size = this._content_size();
            var bounds = viewport
                .bounded_to(this.sizing.size)
                .bounded_to(content_size);
            var width = (function () {
                switch (_this.sizing.width_policy) {
                    case "fixed":
                        return _this.sizing.width != null ? _this.sizing.width : content_size.width;
                    case "min":
                        return content_size.width;
                    case "fit":
                        return bounds.width;
                    case "max":
                        return Math.max(content_size.width, bounds.width);
                }
            })();
            var height = (function () {
                switch (_this.sizing.height_policy) {
                    case "fixed":
                        return _this.sizing.height != null ? _this.sizing.height : content_size.height;
                    case "min":
                        return content_size.height;
                    case "fit":
                        return bounds.height;
                    case "max":
                        return Math.max(content_size.height, bounds.height);
                }
            })();
            return { width: width, height: height };
        };
        return ContentLayoutable;
    }(Layoutable));
    exports.ContentLayoutable = ContentLayoutable;
    ContentLayoutable.__name__ = "ContentLayoutable";
},
/* models/canvas/cartesian_frame.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var categorical_scale_1 = require(177) /* ../scales/categorical_scale */;
    var log_scale_1 = require(176) /* ../scales/log_scale */;
    var range1d_1 = require(173) /* ../ranges/range1d */;
    var data_range1d_1 = require(178) /* ../ranges/data_range1d */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    var object_1 = require(128) /* ../../core/util/object */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var CartesianFrame = /** @class */ (function () {
        function CartesianFrame(in_x_scale, in_y_scale, x_range, y_range, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales) {
            if (extra_x_ranges === void 0) {
                extra_x_ranges = {};
            }
            if (extra_y_ranges === void 0) {
                extra_y_ranges = {};
            }
            if (extra_x_scales === void 0) {
                extra_x_scales = {};
            }
            if (extra_y_scales === void 0) {
                extra_y_scales = {};
            }
            this.in_x_scale = in_x_scale;
            this.in_y_scale = in_y_scale;
            this.x_range = x_range;
            this.y_range = y_range;
            this.extra_x_ranges = extra_x_ranges;
            this.extra_y_ranges = extra_y_ranges;
            this.extra_x_scales = extra_x_scales;
            this.extra_y_scales = extra_y_scales;
            this._bbox = new bbox_1.BBox();
            (0, assert_1.assert)(in_x_scale.source_range == null && in_x_scale.target_range == null);
            (0, assert_1.assert)(in_y_scale.source_range == null && in_y_scale.target_range == null);
            this._configure_scales();
        }
        Object.defineProperty(CartesianFrame.prototype, "bbox", {
            get: function () {
                return this._bbox;
            },
            enumerable: false,
            configurable: true
        });
        CartesianFrame.prototype._get_ranges = function (range, extra_ranges) {
            return new Map((0, object_1.entries)((0, tslib_1.__assign)((0, tslib_1.__assign)({}, extra_ranges), { default: range })));
        };
        /*protected*/ CartesianFrame.prototype._get_scales = function (scale, extra_scales, ranges, frame_range) {
            var e_1, _a;
            var _b;
            var in_scales = new Map((0, object_1.entries)((0, tslib_1.__assign)((0, tslib_1.__assign)({}, extra_scales), { default: scale })));
            var scales = new Map();
            try {
                for (var ranges_1 = (0, tslib_1.__values)(ranges), ranges_1_1 = ranges_1.next(); !ranges_1_1.done; ranges_1_1 = ranges_1.next()) {
                    var _c = (0, tslib_1.__read)(ranges_1_1.value, 2), name = _c[0], range = _c[1];
                    var factor_range = range instanceof factor_range_1.FactorRange;
                    var categorical_scale = scale instanceof categorical_scale_1.CategoricalScale;
                    if (factor_range != categorical_scale) {
                        throw new Error("Range " + range.type + " is incompatible is Scale " + scale.type);
                    }
                    if (scale instanceof log_scale_1.LogScale && range instanceof data_range1d_1.DataRange1d)
                        range.scale_hint = "log";
                    var derived_scale = ((_b = in_scales.get(name)) !== null && _b !== void 0 ? _b : scale).clone();
                    derived_scale.setv({ source_range: range, target_range: frame_range });
                    scales.set(name, derived_scale);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (ranges_1_1 && !ranges_1_1.done && (_a = ranges_1.return))
                        _a.call(ranges_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return scales;
        };
        CartesianFrame.prototype._configure_frame_ranges = function () {
            // data to/from screen space transform (left-bottom <-> left-top origin)
            var bbox = this.bbox;
            this._x_target = new range1d_1.Range1d({ start: bbox.left, end: bbox.right });
            this._y_target = new range1d_1.Range1d({ start: bbox.bottom, end: bbox.top });
        };
        CartesianFrame.prototype._configure_scales = function () {
            this._configure_frame_ranges();
            this._x_ranges = this._get_ranges(this.x_range, this.extra_x_ranges);
            this._y_ranges = this._get_ranges(this.y_range, this.extra_y_ranges);
            this._x_scales = this._get_scales(this.in_x_scale, this.extra_x_scales, this._x_ranges, this._x_target);
            this._y_scales = this._get_scales(this.in_y_scale, this.extra_y_scales, this._y_ranges, this._y_target);
        };
        CartesianFrame.prototype._update_scales = function () {
            var e_2, _a, e_3, _b;
            this._configure_frame_ranges();
            try {
                for (var _c = (0, tslib_1.__values)(this._x_scales), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), scale = _e[1];
                    scale.target_range = this._x_target;
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return))
                        _a.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            try {
                for (var _f = (0, tslib_1.__values)(this._y_scales), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var _h = (0, tslib_1.__read)(_g.value, 2), scale = _h[1];
                    scale.target_range = this._y_target;
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_b = _f.return))
                        _b.call(_f);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
        };
        CartesianFrame.prototype.set_geometry = function (bbox) {
            this._bbox = bbox;
            this._update_scales();
        };
        Object.defineProperty(CartesianFrame.prototype, "x_target", {
            get: function () {
                return this._x_target;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "y_target", {
            get: function () {
                return this._y_target;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "x_ranges", {
            get: function () {
                return this._x_ranges;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "y_ranges", {
            get: function () {
                return this._y_ranges;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "x_scales", {
            get: function () {
                return this._x_scales;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "y_scales", {
            get: function () {
                return this._y_scales;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "x_scale", {
            get: function () {
                return this._x_scales.get("default");
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "y_scale", {
            get: function () {
                return this._y_scales.get("default");
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "xscales", {
            /** @deprecated */
            get: function () {
                return (0, object_1.to_object)(this.x_scales);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CartesianFrame.prototype, "yscales", {
            /** @deprecated */
            get: function () {
                return (0, object_1.to_object)(this.y_scales);
            },
            enumerable: false,
            configurable: true
        });
        return CartesianFrame;
    }());
    exports.CartesianFrame = CartesianFrame;
    CartesianFrame.__name__ = "CartesianFrame";
},
/* models/axes/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var axis_1 = require(243) /* ./axis */;
    __esExport("Axis", axis_1.Axis);
    var categorical_axis_1 = require(255) /* ./categorical_axis */;
    __esExport("CategoricalAxis", categorical_axis_1.CategoricalAxis);
    var continuous_axis_1 = require(258) /* ./continuous_axis */;
    __esExport("ContinuousAxis", continuous_axis_1.ContinuousAxis);
    var datetime_axis_1 = require(259) /* ./datetime_axis */;
    __esExport("DatetimeAxis", datetime_axis_1.DatetimeAxis);
    var linear_axis_1 = require(260) /* ./linear_axis */;
    __esExport("LinearAxis", linear_axis_1.LinearAxis);
    var log_axis_1 = require(277) /* ./log_axis */;
    __esExport("LogAxis", log_axis_1.LogAxis);
    var mercator_axis_1 = require(280) /* ./mercator_axis */;
    __esExport("MercatorAxis", mercator_axis_1.MercatorAxis);
},
/* models/axes/axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var guide_renderer_1 = require(244) /* ../renderers/guide_renderer */;
    var ticker_1 = require(245) /* ../tickers/ticker */;
    var tick_formatter_1 = require(246) /* ../formatters/tick_formatter */;
    var labeling_1 = require(247) /* ../policies/labeling */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var enums_1 = require(135) /* ../../core/enums */;
    var types_1 = require(139) /* ../../core/types */;
    var side_panel_1 = require(238) /* ../../core/layout/side_panel */;
    var array_1 = require(126) /* ../../core/util/array */;
    var object_1 = require(128) /* ../../core/util/object */;
    var types_2 = require(125) /* ../../core/util/types */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var base_text_1 = require(248) /* ../text/base_text */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var types_3 = require(125) /* ../../core/util/types */;
    var utils_1 = require(249) /* ../text/utils */;
    var abs = Math.abs;
    var AxisView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AxisView, _super);
        function AxisView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            /*private*/ _this._axis_label_view = null;
            /*private*/ _this._major_label_views = new Map();
            return _this;
        }
        AxisView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _b.sent();
                            return [4 /*yield*/, this._init_axis_label()];
                        case 2:
                            _b.sent();
                            return [4 /*yield*/, this._init_major_labels()];
                        case 3:
                            _b.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        AxisView.prototype._init_axis_label = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var axis_label, _axis_label, _b;
                return (0, tslib_1.__generator)(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            axis_label = this.model.axis_label;
                            if (!(axis_label != null))
                                return [3 /*break*/, 2];
                            _axis_label = (0, types_3.isString)(axis_label) ? (0, utils_1.parse_delimited_string)(axis_label) : axis_label;
                            _b = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(_axis_label, { parent: this })];
                        case 1:
                            _b._axis_label_view = _c.sent();
                            return [3 /*break*/, 3];
                        case 2:
                            this._axis_label_view = null;
                            _c.label = 3;
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        AxisView.prototype._init_major_labels = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var major_label_overrides, _b, _c, _d, label, label_text, _label_text, _e, _f, _g, e_1_1;
                var e_1, _h;
                return (0, tslib_1.__generator)(this, function (_j) {
                    switch (_j.label) {
                        case 0:
                            major_label_overrides = this.model.major_label_overrides;
                            _j.label = 1;
                        case 1:
                            _j.trys.push([1, 6, 7, 8]);
                            _b = (0, tslib_1.__values)((0, object_1.entries)(major_label_overrides)), _c = _b.next();
                            _j.label = 2;
                        case 2:
                            if (!!_c.done)
                                return [3 /*break*/, 5];
                            _d = (0, tslib_1.__read)(_c.value, 2), label = _d[0], label_text = _d[1];
                            _label_text = (0, types_3.isString)(label_text) ? (0, utils_1.parse_delimited_string)(label_text) : label_text;
                            _f = (_e = this._major_label_views).set;
                            _g = [label];
                            return [4 /*yield*/, (0, build_views_1.build_view)(_label_text, { parent: this })];
                        case 3:
                            _f.apply(_e, _g.concat([_j.sent()]));
                            _j.label = 4;
                        case 4:
                            _c = _b.next();
                            return [3 /*break*/, 2];
                        case 5: return [3 /*break*/, 8];
                        case 6:
                            e_1_1 = _j.sent();
                            e_1 = { error: e_1_1 };
                            return [3 /*break*/, 8];
                        case 7:
                            try {
                                if (_c && !_c.done && (_h = _b.return))
                                    _h.call(_b);
                            }
                            finally {
                                if (e_1)
                                    throw e_1.error;
                            }
                            return [7 /*endfinally*/];
                        case 8: return [2 /*return*/];
                    }
                });
            });
        };
        AxisView.prototype.update_layout = function () {
            var _this = this;
            this.layout = new side_panel_1.SideLayout(this.panel, function () { return _this.get_size(); }, true);
            this.layout.on_resize(function () { return _this._coordinates = undefined; });
        };
        AxisView.prototype.get_size = function () {
            var _b = this.model, visible = _b.visible, fixed_location = _b.fixed_location;
            if (visible && fixed_location == null && this.is_renderable) {
                var extents = this.extents;
                var height = Math.round(extents.tick + extents.tick_label + extents.axis_label);
                return { width: 0, height: height };
            }
            else
                return { width: 0, height: 0 };
        };
        Object.defineProperty(AxisView.prototype, "is_renderable", {
            get: function () {
                var _b = (0, tslib_1.__read)(this.ranges, 2), range = _b[0], cross_range = _b[1];
                return range.is_valid && cross_range.is_valid;
            },
            enumerable: false,
            configurable: true
        });
        AxisView.prototype._render = function () {
            var _b;
            if (!this.is_renderable)
                return;
            var _c = this, tick_coords = _c.tick_coords, extents = _c.extents;
            var ctx = this.layer.ctx;
            ctx.save();
            this._draw_rule(ctx, extents);
            this._draw_major_ticks(ctx, extents, tick_coords);
            this._draw_minor_ticks(ctx, extents, tick_coords);
            this._draw_major_labels(ctx, extents, tick_coords);
            this._draw_axis_label(ctx, extents, tick_coords);
            (_b = this._paint) === null || _b === void 0 ? void 0 : _b.call(this, ctx, extents, tick_coords);
            ctx.restore();
        };
        AxisView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var _b = this.model.properties, axis_label = _b.axis_label, major_label_overrides = _b.major_label_overrides;
            this.on_change(axis_label, function () {
                return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                    var _b;
                    return (0, tslib_1.__generator)(this, function (_c) {
                        switch (_c.label) {
                            case 0:
                                (_b = this._axis_label_view) === null || _b === void 0 ? void 0 : _b.remove();
                                return [4 /*yield*/, this._init_axis_label()];
                            case 1:
                                _c.sent();
                                return [2 /*return*/];
                        }
                    });
                });
            });
            this.on_change(major_label_overrides, function () {
                return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                    var _b, _c, label_view;
                    var e_2, _d;
                    return (0, tslib_1.__generator)(this, function (_e) {
                        switch (_e.label) {
                            case 0:
                                try {
                                    for (_b = (0, tslib_1.__values)(this._major_label_views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
                                        label_view = _c.value;
                                        label_view.remove();
                                    }
                                }
                                catch (e_2_1) {
                                    e_2 = { error: e_2_1 };
                                }
                                finally {
                                    try {
                                        if (_c && !_c.done && (_d = _b.return))
                                            _d.call(_b);
                                    }
                                    finally {
                                        if (e_2)
                                            throw e_2.error;
                                    }
                                }
                                return [4 /*yield*/, this._init_major_labels()];
                            case 1:
                                _e.sent();
                                return [2 /*return*/];
                        }
                    });
                });
            });
            this.connect(this.model.change, function () { return _this.plot_view.request_layout(); });
        };
        Object.defineProperty(AxisView.prototype, "needs_clip", {
            get: function () {
                return this.model.fixed_location != null;
            },
            enumerable: false,
            configurable: true
        });
        // drawing sub functions -----------------------------------------------------
        AxisView.prototype._draw_rule = function (ctx, _extents) {
            if (!this.visuals.axis_line.doit)
                return;
            var _b = (0, tslib_1.__read)(this.rule_coords, 2), xs = _b[0], ys = _b[1];
            var _c = (0, tslib_1.__read)(this.coordinates.map_to_screen(xs, ys), 2), sxs = _c[0], sys = _c[1];
            var _d = (0, tslib_1.__read)(this.normals, 2), nx = _d[0], ny = _d[1];
            var _e = (0, tslib_1.__read)(this.offsets, 2), xoff = _e[0], yoff = _e[1];
            this.visuals.axis_line.set_value(ctx);
            ctx.beginPath();
            for (var i = 0; i < sxs.length; i++) {
                var sx = Math.round(sxs[i] + nx * xoff);
                var sy = Math.round(sys[i] + ny * yoff);
                ctx.lineTo(sx, sy);
            }
            ctx.stroke();
        };
        AxisView.prototype._draw_major_ticks = function (ctx, _extents, tick_coords) {
            var tin = this.model.major_tick_in;
            var tout = this.model.major_tick_out;
            var visuals = this.visuals.major_tick_line;
            this._draw_ticks(ctx, tick_coords.major, tin, tout, visuals);
        };
        AxisView.prototype._draw_minor_ticks = function (ctx, _extents, tick_coords) {
            var tin = this.model.minor_tick_in;
            var tout = this.model.minor_tick_out;
            var visuals = this.visuals.minor_tick_line;
            this._draw_ticks(ctx, tick_coords.minor, tin, tout, visuals);
        };
        AxisView.prototype._draw_major_labels = function (ctx, extents, tick_coords) {
            var coords = tick_coords.major;
            var labels = this.compute_labels(coords[this.dimension]);
            var orient = this.model.major_label_orientation;
            var standoff = extents.tick + this.model.major_label_standoff;
            var visuals = this.visuals.major_label_text;
            this._draw_oriented_labels(ctx, labels, coords, orient, this.panel.side, standoff, visuals);
        };
        AxisView.prototype._axis_label_extent = function () {
            if (this._axis_label_view == null)
                return 0;
            var axis_label_graphics = this._axis_label_view.graphics();
            var padding = 3;
            axis_label_graphics.visuals = this.visuals.axis_label_text.values();
            axis_label_graphics.angle = this.panel.get_label_angle_heuristic("parallel");
            if ((0, types_2.isNumber)(this.plot_view.base_font_size))
                axis_label_graphics.base_font_size = this.plot_view.base_font_size;
            var size = axis_label_graphics.size();
            var extent = this.dimension == 0 ? size.height : size.width;
            var standoff = this.model.axis_label_standoff;
            return extent > 0 ? standoff + extent + padding : 0;
        };
        AxisView.prototype._draw_axis_label = function (ctx, extents, _tick_coords) {
            var _this = this;
            if (this._axis_label_view == null || this.model.fixed_location != null)
                return;
            var _b = (0, tslib_1.__read)((function () {
                var bbox = _this.layout.bbox;
                switch (_this.panel.side) {
                    case "above":
                        return [bbox.hcenter, bbox.bottom];
                    case "below":
                        return [bbox.hcenter, bbox.top];
                    case "left":
                        return [bbox.right, bbox.vcenter];
                    case "right":
                        return [bbox.left, bbox.vcenter];
                }
            })(), 2), sx = _b[0], sy = _b[1];
            var _c = (0, tslib_1.__read)(this.normals, 2), nx = _c[0], ny = _c[1];
            var standoff = extents.tick + extents.tick_label + this.model.axis_label_standoff;
            var _d = this.panel.get_label_text_heuristics("parallel"), vertical_align = _d.vertical_align, align = _d.align;
            var position = {
                sx: sx + nx * standoff,
                sy: sy + ny * standoff,
                x_anchor: align,
                y_anchor: vertical_align,
            };
            var axis_label_graphics = this._axis_label_view.graphics();
            axis_label_graphics.visuals = this.visuals.axis_label_text.values();
            axis_label_graphics.angle = this.panel.get_label_angle_heuristic("parallel");
            if (this.plot_view.base_font_size)
                axis_label_graphics.base_font_size = this.plot_view.base_font_size;
            axis_label_graphics.position = position;
            axis_label_graphics.align = align;
            axis_label_graphics.paint(ctx);
        };
        AxisView.prototype._draw_ticks = function (ctx, coords, tin, tout, visuals) {
            if (!visuals.doit)
                return;
            var _b = (0, tslib_1.__read)(coords, 2), x = _b[0], y = _b[1];
            var _c = (0, tslib_1.__read)(this.coordinates.map_to_screen(x, y), 2), sxs = _c[0], sys = _c[1];
            var _d = (0, tslib_1.__read)(this.normals, 2), nx = _d[0], ny = _d[1];
            var _e = (0, tslib_1.__read)(this.offsets, 2), xoff = _e[0], yoff = _e[1];
            var _f = (0, tslib_1.__read)([nx * (xoff - tin), ny * (yoff - tin)], 2), nxin = _f[0], nyin = _f[1];
            var _g = (0, tslib_1.__read)([nx * (xoff + tout), ny * (yoff + tout)], 2), nxout = _g[0], nyout = _g[1];
            visuals.set_value(ctx);
            ctx.beginPath();
            for (var i = 0; i < sxs.length; i++) {
                var sx0 = Math.round(sxs[i] + nxout);
                var sy0 = Math.round(sys[i] + nyout);
                var sx1 = Math.round(sxs[i] + nxin);
                var sy1 = Math.round(sys[i] + nyin);
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
            }
            ctx.stroke();
        };
        AxisView.prototype._draw_oriented_labels = function (ctx, labels, coords, orient, _side, standoff, visuals) {
            var e_3, _b;
            var _this = this;
            if (!visuals.doit || labels.length == 0)
                return;
            var _c = (0, tslib_1.__read)(coords, 2), dxs = _c[0], dys = _c[1];
            var _d = (0, tslib_1.__read)(this.coordinates.map_to_screen(dxs, dys), 2), sxs = _d[0], sys = _d[1];
            var _e = (0, tslib_1.__read)(this.offsets, 2), xoff = _e[0], yoff = _e[1];
            var _f = (0, tslib_1.__read)(this.normals, 2), nx = _f[0], ny = _f[1];
            var nxd = nx * (xoff + standoff);
            var nyd = ny * (yoff + standoff);
            var _g = this.panel.get_label_text_heuristics(orient), vertical_align = _g.vertical_align, align = _g.align;
            var angle = this.panel.get_label_angle_heuristic(orient);
            labels.visuals = visuals.values();
            labels.angle = angle;
            labels.base_font_size = this.plot_view.base_font_size;
            for (var i = 0; i < labels.length; i++) {
                var label = labels.items[i];
                label.position = {
                    sx: sxs[i] + nxd,
                    sy: sys[i] + nyd,
                    x_anchor: align,
                    y_anchor: vertical_align,
                };
                if (label instanceof graphics_1.TextBox)
                    label.align = align;
            }
            var n = labels.length;
            var indices = types_1.Indices.all_set(n);
            var items = labels.items;
            var bboxes = items.map(function (l) { return l.bbox(); });
            var dist = (function () {
                var _b = (0, tslib_1.__read)(_this.ranges, 1), range = _b[0];
                if (!range.is_reversed)
                    return _this.dimension == 0 ? function (i, j) { return bboxes[j].left - bboxes[i].right; }
                        : function (i, j) { return bboxes[i].top - bboxes[j].bottom; };
                else
                    return _this.dimension == 0 ? function (i, j) { return bboxes[i].left - bboxes[j].right; }
                        : function (i, j) { return bboxes[j].top - bboxes[i].bottom; };
            })();
            var major_label_policy = this.model.major_label_policy;
            var selected = major_label_policy.filter(indices, bboxes, dist);
            var ids = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(selected.ones()), false);
            if (ids.length != 0) {
                var cbox_1 = this.parent.canvas_view.bbox;
                var correct_x = function (k) {
                    var bbox = bboxes[k];
                    if (bbox.left < 0) {
                        var offset = -bbox.left;
                        var position = items[k].position;
                        items[k].position = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, position), { sx: position.sx + offset });
                    }
                    else if (bbox.right > cbox_1.width) {
                        var offset = bbox.right - cbox_1.width;
                        var position = items[k].position;
                        items[k].position = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, position), { sx: position.sx - offset });
                    }
                };
                var correct_y = function (k) {
                    var bbox = bboxes[k];
                    if (bbox.top < 0) {
                        var offset = -bbox.top;
                        var position = items[k].position;
                        items[k].position = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, position), { sy: position.sy + offset });
                    }
                    else if (bbox.bottom > cbox_1.height) {
                        var offset = bbox.bottom - cbox_1.height;
                        var position = items[k].position;
                        items[k].position = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, position), { sy: position.sy - offset });
                    }
                };
                var i = ids[0];
                var j = ids[ids.length - 1];
                if (this.dimension == 0) {
                    correct_x(i);
                    correct_x(j);
                }
                else {
                    correct_y(i);
                    correct_y(j);
                }
            }
            try {
                for (var selected_1 = (0, tslib_1.__values)(selected), selected_1_1 = selected_1.next(); !selected_1_1.done; selected_1_1 = selected_1.next()) {
                    var i = selected_1_1.value;
                    var label = items[i];
                    label.paint(ctx);
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (selected_1_1 && !selected_1_1.done && (_b = selected_1.return))
                        _b.call(selected_1);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
        };
        // extents sub functions -----------------------------------------------------
        /*protected*/ AxisView.prototype._tick_extent = function () {
            return this.model.major_tick_out;
        };
        AxisView.prototype._tick_label_extents = function () {
            var coords = this.tick_coords.major;
            var labels = this.compute_labels(coords[this.dimension]);
            var orient = this.model.major_label_orientation;
            var standoff = this.model.major_label_standoff;
            var visuals = this.visuals.major_label_text;
            return [this._oriented_labels_extent(labels, orient, standoff, visuals)];
        };
        Object.defineProperty(AxisView.prototype, "extents", {
            get: function () {
                var tick_labels = this._tick_label_extents();
                return {
                    tick: this._tick_extent(),
                    tick_labels: tick_labels,
                    tick_label: (0, array_1.sum)(tick_labels),
                    axis_label: this._axis_label_extent(),
                };
            },
            enumerable: false,
            configurable: true
        });
        AxisView.prototype._oriented_labels_extent = function (labels, orient, standoff, visuals) {
            if (labels.length == 0 || !visuals.doit)
                return 0;
            var angle = this.panel.get_label_angle_heuristic(orient);
            labels.visuals = visuals.values();
            labels.angle = angle;
            labels.base_font_size = this.plot_view.base_font_size;
            var size = labels.max_size();
            var extent = this.dimension == 0 ? size.height : size.width;
            var padding = 3;
            return extent > 0 ? standoff + extent + padding : 0;
        };
        Object.defineProperty(AxisView.prototype, "normals", {
            // {{{ TODO: state
            get: function () {
                return this.panel.normals;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AxisView.prototype, "dimension", {
            get: function () {
                return this.panel.dimension;
            },
            enumerable: false,
            configurable: true
        });
        AxisView.prototype.compute_labels = function (ticks) {
            var e_4, _b;
            var labels = this.model.formatter.format_graphics(ticks, this);
            var _major_label_views = this._major_label_views;
            var visited = new Set();
            for (var i = 0; i < ticks.length; i++) {
                var override = _major_label_views.get(ticks[i].toString());
                if (override != null) {
                    visited.add(override);
                    labels[i] = override.graphics();
                }
            }
            try {
                // XXX: make sure unused overrides don't prevent document idle
                for (var _c = (0, tslib_1.__values)(this._major_label_views.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var label_view = _d.value;
                    if (!visited.has(label_view)) {
                        label_view._has_finished = true;
                    }
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            return new graphics_1.GraphicsBoxes(labels);
        };
        Object.defineProperty(AxisView.prototype, "offsets", {
            get: function () {
                // If we have a fixed_position then we should respect that exactly and
                // not apply any offsets (https://github.com/bokeh/bokeh/issues/8552)
                if (this.model.fixed_location != null)
                    return [0, 0];
                var frame = this.plot_view.frame;
                var _b = (0, tslib_1.__read)([0, 0], 2), xoff = _b[0], yoff = _b[1];
                switch (this.panel.side) {
                    case "below":
                        yoff = abs(this.layout.bbox.top - frame.bbox.bottom);
                        break;
                    case "above":
                        yoff = abs(this.layout.bbox.bottom - frame.bbox.top);
                        break;
                    case "right":
                        xoff = abs(this.layout.bbox.left - frame.bbox.right);
                        break;
                    case "left":
                        xoff = abs(this.layout.bbox.right - frame.bbox.left);
                        break;
                }
                return [xoff, yoff];
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AxisView.prototype, "ranges", {
            get: function () {
                var i = this.dimension;
                var j = (i + 1) % 2;
                var ranges = this.coordinates.ranges;
                return [ranges[i], ranges[j]];
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AxisView.prototype, "computed_bounds", {
            get: function () {
                var _b = (0, tslib_1.__read)(this.ranges, 1), range = _b[0];
                var user_bounds = this.model.bounds;
                var range_bounds = [range.min, range.max];
                if (user_bounds == "auto")
                    return [range.min, range.max];
                else {
                    var start = void 0;
                    var end = void 0;
                    var _c = (0, tslib_1.__read)(user_bounds, 2), user_start = _c[0], user_end = _c[1];
                    var _d = (0, tslib_1.__read)(range_bounds, 2), range_start = _d[0], range_end = _d[1];
                    var min = Math.min, max = Math.max;
                    if (abs(user_start - user_end) > abs(range_start - range_end)) {
                        start = max(min(user_start, user_end), range_start);
                        end = min(max(user_start, user_end), range_end);
                    }
                    else {
                        start = min(user_start, user_end);
                        end = max(user_start, user_end);
                    }
                    return [start, end];
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AxisView.prototype, "rule_coords", {
            get: function () {
                var i = this.dimension;
                var j = (i + 1) % 2;
                var _b = (0, tslib_1.__read)(this.ranges, 1), range = _b[0];
                var _c = (0, tslib_1.__read)(this.computed_bounds, 2), start = _c[0], end = _c[1];
                var xs = new Array(2);
                var ys = new Array(2);
                var coords = [xs, ys];
                coords[i][0] = Math.max(start, range.min);
                coords[i][1] = Math.min(end, range.max);
                if (coords[i][0] > coords[i][1])
                    coords[i][0] = coords[i][1] = NaN;
                coords[j][0] = this.loc;
                coords[j][1] = this.loc;
                return coords;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AxisView.prototype, "tick_coords", {
            get: function () {
                var i = this.dimension;
                var j = (i + 1) % 2;
                var _b = (0, tslib_1.__read)(this.ranges, 1), range = _b[0];
                var _c = (0, tslib_1.__read)(this.computed_bounds, 2), start = _c[0], end = _c[1];
                var ticks = this.model.ticker.get_ticks(start, end, range, this.loc);
                var majors = ticks.major;
                var minors = ticks.minor;
                var xs = [];
                var ys = [];
                var coords = [xs, ys];
                var minor_xs = [];
                var minor_ys = [];
                var minor_coords = [minor_xs, minor_ys];
                var _d = (0, tslib_1.__read)([range.min, range.max], 2), range_min = _d[0], range_max = _d[1];
                for (var ii = 0; ii < majors.length; ii++) {
                    if (majors[ii] < range_min || majors[ii] > range_max)
                        continue;
                    coords[i].push(majors[ii]);
                    coords[j].push(this.loc);
                }
                for (var ii = 0; ii < minors.length; ii++) {
                    if (minors[ii] < range_min || minors[ii] > range_max)
                        continue;
                    minor_coords[i].push(minors[ii]);
                    minor_coords[j].push(this.loc);
                }
                return {
                    major: coords,
                    minor: minor_coords,
                };
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AxisView.prototype, "loc", {
            get: function () {
                var fixed_location = this.model.fixed_location;
                if (fixed_location != null) {
                    if ((0, types_2.isNumber)(fixed_location))
                        return fixed_location;
                    var _b = (0, tslib_1.__read)(this.ranges, 2), cross_range_1 = _b[1];
                    if (cross_range_1 instanceof factor_range_1.FactorRange)
                        return cross_range_1.synthetic(fixed_location);
                    (0, assert_1.unreachable)();
                }
                var _c = (0, tslib_1.__read)(this.ranges, 2), cross_range = _c[1];
                switch (this.panel.side) {
                    case "left":
                    case "below":
                        return cross_range.start;
                    case "right":
                    case "above":
                        return cross_range.end;
                }
            },
            enumerable: false,
            configurable: true
        });
        // }}}
        AxisView.prototype.serializable_state = function () {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype.serializable_state.call(this)), { bbox: this.layout.bbox.box });
        };
        AxisView.prototype.remove = function () {
            var e_5, _b;
            var _c;
            (_c = this._axis_label_view) === null || _c === void 0 ? void 0 : _c.remove();
            try {
                for (var _d = (0, tslib_1.__values)(this._major_label_views.values()), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var label_view = _e.value;
                    label_view.remove();
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            _super.prototype.remove.call(this);
        };
        AxisView.prototype.has_finished = function () {
            var e_6, _b;
            if (!_super.prototype.has_finished.call(this))
                return false;
            if (this._axis_label_view != null) {
                if (!this._axis_label_view.has_finished())
                    return false;
            }
            try {
                for (var _c = (0, tslib_1.__values)(this._major_label_views.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var label_view = _d.value;
                    if (!label_view.has_finished())
                        return false;
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            return true;
        };
        return AxisView;
    }(guide_renderer_1.GuideRendererView));
    exports.AxisView = AxisView;
    AxisView.__name__ = "AxisView";
    var Axis = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Axis, _super);
        function Axis(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Axis;
    }(guide_renderer_1.GuideRenderer));
    exports.Axis = Axis;
    _a = Axis;
    Axis.__name__ = "Axis";
    (function () {
        _a.prototype.default_view = AxisView;
        _a.mixins([
            ["axis_", mixins.Line],
            ["major_tick_", mixins.Line],
            ["minor_tick_", mixins.Line],
            ["major_label_", mixins.Text],
            ["axis_label_", mixins.Text],
        ]);
        _a.define(function (_b) {
            var Any = _b.Any, Int = _b.Int, Number = _b.Number, String = _b.String, Ref = _b.Ref, Dict = _b.Dict, Tuple = _b.Tuple, Or = _b.Or, Nullable = _b.Nullable, Auto = _b.Auto;
            return ({
                bounds: [Or(Tuple(Number, Number), Auto), "auto"],
                ticker: [Ref(ticker_1.Ticker)],
                formatter: [Ref(tick_formatter_1.TickFormatter)],
                axis_label: [Nullable(Or(String, Ref(base_text_1.BaseText))), null],
                axis_label_standoff: [Int, 5],
                major_label_standoff: [Int, 5],
                major_label_orientation: [Or(enums_1.TickLabelOrientation, Number), "horizontal"],
                major_label_overrides: [Dict(Or(String, Ref(base_text_1.BaseText))), {}],
                major_label_policy: [Ref(labeling_1.LabelingPolicy), function () { return new labeling_1.AllLabels(); }],
                major_tick_in: [Number, 2],
                major_tick_out: [Number, 6],
                minor_tick_in: [Number, 0],
                minor_tick_out: [Number, 4],
                fixed_location: [Nullable(Or(Number, Any)), null],
            });
        });
        _a.override({
            axis_line_color: "black",
            major_tick_line_color: "black",
            minor_tick_line_color: "black",
            major_label_text_font_size: "11px",
            major_label_text_align: "center",
            major_label_text_baseline: "alphabetic",
            axis_label_text_font_size: "13px",
            axis_label_text_font_style: "italic",
        });
    })();
},
/* models/renderers/guide_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var renderer_1 = require(156) /* ./renderer */;
    var GuideRendererView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GuideRendererView, _super);
        function GuideRendererView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return GuideRendererView;
    }(renderer_1.RendererView));
    exports.GuideRendererView = GuideRendererView;
    GuideRendererView.__name__ = "GuideRendererView";
    var GuideRenderer = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GuideRenderer, _super);
        function GuideRenderer(attrs) {
            return _super.call(this, attrs) || this;
        }
        return GuideRenderer;
    }(renderer_1.Renderer));
    exports.GuideRenderer = GuideRenderer;
    _a = GuideRenderer;
    GuideRenderer.__name__ = "GuideRenderer";
    (function () {
        _a.override({
            level: "guide",
        });
    })();
},
/* models/tickers/ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../../model */;
    var Ticker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Ticker, _super);
        function Ticker(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Ticker;
    }(model_1.Model));
    exports.Ticker = Ticker;
    Ticker.__name__ = "Ticker";
},
/* models/formatters/tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../../model */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var TickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TickFormatter, _super);
        function TickFormatter(attrs) {
            return _super.call(this, attrs) || this;
        }
        TickFormatter.prototype.format_graphics = function (ticks, opts) {
            return this.doFormat(ticks, opts).map(function (text) { return new graphics_1.TextBox({ text: text }); });
        };
        TickFormatter.prototype.compute = function (tick, opts) {
            return this.doFormat([tick], opts !== null && opts !== void 0 ? opts : { loc: 0 })[0];
        };
        TickFormatter.prototype.v_compute = function (tick, opts) {
            return this.doFormat(tick, opts !== null && opts !== void 0 ? opts : { loc: 0 });
        };
        return TickFormatter;
    }(model_1.Model));
    exports.TickFormatter = TickFormatter;
    TickFormatter.__name__ = "TickFormatter";
},
/* models/policies/labeling.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b;
    var model_1 = require(168) /* ../../model */;
    var object_1 = require(128) /* ../../core/util/object */;
    var string_1 = require(149) /* ../../core/util/string */;
    var types_1 = require(125) /* ../../core/util/types */;
    var types_2 = require(139) /* ../../core/types */;
    var LabelingPolicy = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LabelingPolicy, _super);
        function LabelingPolicy(attrs) {
            return _super.call(this, attrs) || this;
        }
        return LabelingPolicy;
    }(model_1.Model));
    exports.LabelingPolicy = LabelingPolicy;
    LabelingPolicy.__name__ = "LabelingPolicy";
    var AllLabels = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AllLabels, _super);
        function AllLabels(attrs) {
            return _super.call(this, attrs) || this;
        }
        AllLabels.prototype.filter = function (indices, _bboxes, _distance) {
            return indices;
        };
        return AllLabels;
    }(LabelingPolicy));
    exports.AllLabels = AllLabels;
    AllLabels.__name__ = "AllLabels";
    var NoOverlap = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NoOverlap, _super);
        function NoOverlap(attrs) {
            return _super.call(this, attrs) || this;
        }
        NoOverlap.prototype.filter = function (indices, _bboxes, distance) {
            var e_1, _c;
            var min_distance = this.min_distance;
            var k = null;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    if (k != null && distance(k, i) < min_distance)
                        indices.unset(i);
                    else
                        k = i;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_c = indices_1.return))
                        _c.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return indices;
        };
        return NoOverlap;
    }(LabelingPolicy));
    exports.NoOverlap = NoOverlap;
    _a = NoOverlap;
    NoOverlap.__name__ = "NoOverlap";
    (function () {
        _a.define(function (_c) {
            var Number = _c.Number;
            return ({
                min_distance: [Number, 5],
            });
        });
    })();
    var CustomLabelingPolicy = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomLabelingPolicy, _super);
        function CustomLabelingPolicy(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CustomLabelingPolicy.prototype, "names", {
            get: function () {
                return (0, object_1.keys)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomLabelingPolicy.prototype, "values", {
            get: function () {
                return (0, object_1.values)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomLabelingPolicy.prototype, "func", {
            get: function () {
                var code = (0, string_1.use_strict)(this.code);
                return new (types_2.GeneratorFunction.bind.apply(types_2.GeneratorFunction, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([void 0, "indices", "bboxes", "distance"], (0, tslib_1.__read)(this.names), false), [code], false)))();
            },
            enumerable: false,
            configurable: true
        });
        CustomLabelingPolicy.prototype.filter = function (indices, bboxes, distance) {
            var _c;
            var obj = Object.create(null);
            var generator = (_c = this.func).call.apply(_c, (0, tslib_1.__spreadArray)([obj, indices, bboxes, distance], (0, tslib_1.__read)(this.values), false));
            var result = generator.next();
            if (result.done && result.value !== undefined) {
                var value = result.value;
                if (value instanceof types_2.Indices)
                    return value;
                else if (value === undefined)
                    return indices;
                else if ((0, types_1.isIterable)(value))
                    return types_2.Indices.from_indices(indices.size, value);
                else
                    return types_2.Indices.all_unset(indices.size);
            }
            else {
                var array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!result.done);
                return types_2.Indices.from_indices(indices.size, array);
            }
        };
        return CustomLabelingPolicy;
    }(LabelingPolicy));
    exports.CustomLabelingPolicy = CustomLabelingPolicy;
    _b = CustomLabelingPolicy;
    CustomLabelingPolicy.__name__ = "CustomLabelingPolicy";
    (function () {
        _b.define(function (_c) {
            var Unknown = _c.Unknown, String = _c.String, Dict = _c.Dict;
            return ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            });
        });
    })();
},
/* models/text/base_text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var view_1 = require(157) /* ../../core/view */;
    var BaseTextView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BaseTextView, _super);
        function BaseTextView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return BaseTextView;
    }(view_1.View));
    exports.BaseTextView = BaseTextView;
    BaseTextView.__name__ = "BaseTextView";
    var BaseText = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BaseText, _super);
        function BaseText(attrs) {
            return _super.call(this, attrs) || this;
        }
        return BaseText;
    }(model_1.Model));
    exports.BaseText = BaseText;
    _a = BaseText;
    BaseText.__name__ = "BaseText";
    (function () {
        _a.define(function (_b) {
            var String = _b.String;
            return ({
                text: [String],
            });
        });
    })();
},
/* models/text/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var math_text_1 = require(250) /* ./math_text */;
    var plain_text_1 = require(254) /* ./plain_text */;
    var delimiters = [
        { start: "$$", end: "$$", inline: false },
        { start: "\\[", end: "\\]", inline: false },
        { start: "\\(", end: "\\)", inline: true },
    ];
    function parse_delimited_string(text) {
        var e_1, _a;
        try {
            for (var delimiters_1 = (0, tslib_1.__values)(delimiters), delimiters_1_1 = delimiters_1.next(); !delimiters_1_1.done; delimiters_1_1 = delimiters_1.next()) {
                var delim = delimiters_1_1.value;
                var n0 = text.indexOf(delim.start);
                var m0 = n0 + delim.start.length;
                if (n0 == 0) {
                    var n1 = text.indexOf(delim.end, m0);
                    var m1 = n1;
                    if (n1 == text.length - delim.end.length)
                        return new math_text_1.TeX({ text: text.slice(m0, m1), inline: delim.inline });
                    else
                        break;
                }
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (delimiters_1_1 && !delimiters_1_1.done && (_a = delimiters_1.return))
                    _a.call(delimiters_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return new plain_text_1.PlainText({ text: text });
    }
    exports.parse_delimited_string = parse_delimited_string;
},
/* models/text/math_text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b, _c;
    var types_1 = require(125) /* ../../core/util/types */;
    var image_1 = require(251) /* ../../core/util/image */;
    var color_1 = require(137) /* ../../core/util/color */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var text_1 = require(236) /* ../../core/util/text */;
    var affine_1 = require(237) /* ../../core/util/affine */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    var base_text_1 = require(248) /* ./base_text */;
    var providers_1 = require(252) /* ./providers */;
    /**
     * Helper class for rendering MathText into Canvas
     */
    var MathTextView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MathTextView, _super);
        function MathTextView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._position = { sx: 0, sy: 0 };
            // Align does nothing, needed to maintain compatibility with TextBox,
            // to align you need to use TeX Macros.
            // http://docs.mathjax.org/en/latest/input/tex/macros/index.html?highlight=align
            _this.align = "left";
            _this._x_anchor = "left";
            _this._y_anchor = "center";
            _this._base_font_size = 13; // the same as .bk-root's font-size (13px)
            _this.font_size_scale = 1.0;
            _this.svg_image = null;
            return _this;
        }
        MathTextView.prototype.graphics = function () {
            return this;
        };
        // Same for infer_text_height
        MathTextView.prototype.infer_text_height = function () {
            return "ascent_descent";
        };
        Object.defineProperty(MathTextView.prototype, "base_font_size", {
            get: function () {
                return this._base_font_size;
            },
            set: function (v) {
                if (v != null)
                    this._base_font_size = v;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(MathTextView.prototype, "has_image_loaded", {
            get: function () {
                return this.svg_image != null;
            },
            enumerable: false,
            configurable: true
        });
        MathTextView.prototype._rect = function () {
            var _d = this._size(), width = _d.width, height = _d.height;
            var _e = this._computed_position(), x = _e.x, y = _e.y;
            var bbox = new bbox_1.BBox({ x: x, y: y, width: width, height: height });
            return bbox.rect;
        };
        Object.defineProperty(MathTextView.prototype, "position", {
            get: function () {
                return this._position;
            },
            set: function (p) {
                this._position = p;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(MathTextView.prototype, "text", {
            get: function () {
                return this.model.text;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(MathTextView.prototype, "provider", {
            get: function () {
                return providers_1.default_provider;
            },
            enumerable: false,
            configurable: true
        });
        MathTextView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var _this = this;
                return (0, tslib_1.__generator)(this, function (_d) {
                    switch (_d.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _d.sent();
                            if (!(this.provider.status == "not_started"))
                                return [3 /*break*/, 3];
                            return [4 /*yield*/, this.provider.fetch()];
                        case 2:
                            _d.sent();
                            _d.label = 3;
                        case 3:
                            if (this.provider.status == "not_started" || this.provider.status == "loading")
                                this.provider.ready.connect(function () { return _this.load_image(); });
                            if (!(this.provider.status == "loaded"))
                                return [3 /*break*/, 5];
                            return [4 /*yield*/, this.load_image()];
                        case 4:
                            _d.sent();
                            _d.label = 5;
                        case 5: return [2 /*return*/];
                    }
                });
            });
        };
        MathTextView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.on_change(this.model.properties.text, function () { return _this.load_image(); });
        };
        Object.defineProperty(MathTextView.prototype, "visuals", {
            set: function (v) {
                var color = v.color;
                var alpha = v.alpha;
                var style = v.font_style;
                var size = v.font_size;
                var face = v.font;
                var _d = this, font_size_scale = _d.font_size_scale, _base_font_size = _d._base_font_size;
                var res = (0, text_1.parse_css_font_size)(size);
                if (res != null) {
                    var value = res.value, unit = res.unit;
                    value *= font_size_scale;
                    if (unit == "em" && _base_font_size) {
                        value *= _base_font_size;
                        unit = "px";
                    }
                    size = "" + value + unit;
                }
                var font = style + " " + size + " " + face;
                this.font = font;
                this.color = (0, color_1.color2css)(color, alpha);
            },
            enumerable: false,
            configurable: true
        });
        /**
         * Calculates position of element after considering
         * anchor and dimensions
         */
        MathTextView.prototype._computed_position = function () {
            var _d = this._size(), width = _d.width, height = _d.height;
            var _e = this.position, sx = _e.sx, sy = _e.sy, _f = _e.x_anchor, x_anchor = _f === void 0 ? this._x_anchor : _f, _g = _e.y_anchor, y_anchor = _g === void 0 ? this._y_anchor : _g;
            var x = sx - (function () {
                if ((0, types_1.isNumber)(x_anchor))
                    return x_anchor * width;
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            var y = sy - (function () {
                if ((0, types_1.isNumber)(y_anchor))
                    return y_anchor * height;
                else {
                    switch (y_anchor) {
                        case "top": return 0;
                        case "center": return 0.5 * height;
                        case "bottom": return height;
                        case "baseline": return 0.5 * height;
                    }
                }
            })();
            return { x: x, y: y };
        };
        /**
         * Uses the width, height and given angle to calculate the size
        */
        MathTextView.prototype.size = function () {
            var _d = this._size(), width = _d.width, height = _d.height;
            var angle = this.angle;
            if (!angle)
                return { width: width, height: height };
            else {
                var c = Math.cos(Math.abs(angle));
                var s = Math.sin(Math.abs(angle));
                return {
                    width: Math.abs(width * c + height * s),
                    height: Math.abs(width * s + height * c),
                };
            }
        };
        MathTextView.prototype.get_text_dimensions = function () {
            return {
                width: (0, graphics_1.text_width)(this.model.text, this.font),
                height: (0, text_1.font_metrics)(this.font).height,
            };
        };
        MathTextView.prototype.get_image_dimensions = function () {
            var _d, _e, _f, _g;
            var heightEx = parseFloat((_e = (_d = this.svg_element
                .getAttribute("height")) === null || _d === void 0 ? void 0 : _d.replace(/([A-z])/g, "")) !== null && _e !== void 0 ? _e : "0");
            var widthEx = parseFloat((_g = (_f = this.svg_element
                .getAttribute("width")) === null || _f === void 0 ? void 0 : _f.replace(/([A-z])/g, "")) !== null && _g !== void 0 ? _g : "0");
            return {
                width: (0, text_1.font_metrics)(this.font).x_height * widthEx,
                height: (0, text_1.font_metrics)(this.font).x_height * heightEx,
            };
        };
        MathTextView.prototype._size = function () {
            return this.has_image_loaded ? this.get_image_dimensions() : this.get_text_dimensions();
        };
        MathTextView.prototype.bbox = function () {
            var _d = this.rect(), p0 = _d.p0, p1 = _d.p1, p2 = _d.p2, p3 = _d.p3;
            var left = Math.min(p0.x, p1.x, p2.x, p3.x);
            var top = Math.min(p0.y, p1.y, p2.y, p3.y);
            var right = Math.max(p0.x, p1.x, p2.x, p3.x);
            var bottom = Math.max(p0.y, p1.y, p2.y, p3.y);
            return new bbox_1.BBox({ left: left, right: right, top: top, bottom: bottom });
        };
        MathTextView.prototype.rect = function () {
            var rect = this._rect();
            var angle = this.angle;
            if (!angle)
                return rect;
            else {
                var _d = this.position, sx = _d.sx, sy = _d.sy;
                var tr = new affine_1.AffineTransform();
                tr.translate(sx, sy);
                tr.rotate(angle);
                tr.translate(-sx, -sy);
                return tr.apply_rect(rect);
            }
        };
        MathTextView.prototype.paint_rect = function (ctx) {
            var _d = this.rect(), p0 = _d.p0, p1 = _d.p1, p2 = _d.p2, p3 = _d.p3;
            ctx.save();
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.beginPath();
            var round = Math.round;
            ctx.moveTo(round(p0.x), round(p0.y));
            ctx.lineTo(round(p1.x), round(p1.y));
            ctx.lineTo(round(p2.x), round(p2.y));
            ctx.lineTo(round(p3.x), round(p3.y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        };
        MathTextView.prototype.paint_bbox = function (ctx) {
            var _d = this.bbox(), x = _d.x, y = _d.y, width = _d.width, height = _d.height;
            ctx.save();
            ctx.strokeStyle = "blue";
            ctx.lineWidth = 1;
            ctx.beginPath();
            var round = Math.round;
            ctx.moveTo(round(x), round(y));
            ctx.lineTo(round(x), round(y + height));
            ctx.lineTo(round(x + width), round(y + height));
            ctx.lineTo(round(x + width), round(y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        };
        MathTextView.prototype.load_image = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var mathjax_element, svg_element, outer_HTML, blob, url, _d;
                return (0, tslib_1.__generator)(this, function (_e) {
                    switch (_e.label) {
                        case 0:
                            if (this.provider.MathJax == null)
                                return [2 /*return*/, null];
                            mathjax_element = this._process_text(this.model.text);
                            if (mathjax_element == null) {
                                this._has_finished = true;
                                return [2 /*return*/, null];
                            }
                            svg_element = mathjax_element.children[0];
                            this.svg_element = svg_element;
                            svg_element.setAttribute("font", this.font);
                            svg_element.setAttribute("stroke", this.color);
                            outer_HTML = svg_element.outerHTML;
                            blob = new Blob([outer_HTML], { type: "image/svg+xml" });
                            url = URL.createObjectURL(blob);
                            _e.label = 1;
                        case 1:
                            _e.trys.push([1, , 3, 4]);
                            _d = this;
                            return [4 /*yield*/, (0, image_1.load_image)(url)];
                        case 2:
                            _d.svg_image = _e.sent();
                            return [3 /*break*/, 4];
                        case 3:
                            URL.revokeObjectURL(url);
                            return [7 /*endfinally*/];
                        case 4:
                            this.parent.request_layout();
                            return [2 /*return*/, this.svg_image];
                    }
                });
            });
        };
        /**
         * Takes a Canvas' Context2d and if the image has already
         * been loaded draws the image in it otherwise draws the model's text.
        */
        MathTextView.prototype.paint = function (ctx) {
            ctx.save();
            var _d = this.position, sx = _d.sx, sy = _d.sy;
            if (this.angle) {
                ctx.translate(sx, sy);
                ctx.rotate(this.angle);
                ctx.translate(-sx, -sy);
            }
            var _e = this._computed_position(), x = _e.x, y = _e.y;
            if (this.svg_image != null) {
                var _f = this.get_image_dimensions(), width = _f.width, height = _f.height;
                ctx.drawImage(this.svg_image, x, y, width, height);
            }
            else {
                ctx.fillStyle = this.color;
                ctx.font = this.font;
                ctx.textAlign = "left";
                ctx.textBaseline = "alphabetic";
                ctx.fillText(this.model.text, x, y + (0, text_1.font_metrics)(this.font).ascent);
            }
            ctx.restore();
            if (!this._has_finished && (this.provider.status == "failed" || this.has_image_loaded)) {
                this._has_finished = true;
                this.parent.notify_finished_after_paint();
            }
        };
        return MathTextView;
    }(base_text_1.BaseTextView));
    exports.MathTextView = MathTextView;
    MathTextView.__name__ = "MathTextView";
    var MathText = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MathText, _super);
        function MathText(attrs) {
            return _super.call(this, attrs) || this;
        }
        return MathText;
    }(base_text_1.BaseText));
    exports.MathText = MathText;
    MathText.__name__ = "MathText";
    var AsciiView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AsciiView, _super);
        function AsciiView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AsciiView.prototype._process_text = function (_text) {
            return undefined; // TODO: this.provider.MathJax?.ascii2svg(text)
        };
        return AsciiView;
    }(MathTextView));
    exports.AsciiView = AsciiView;
    AsciiView.__name__ = "AsciiView";
    var Ascii = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Ascii, _super);
        function Ascii(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Ascii;
    }(MathText));
    exports.Ascii = Ascii;
    _a = Ascii;
    Ascii.__name__ = "Ascii";
    (function () {
        _a.prototype.default_view = AsciiView;
    })();
    var MathMLView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MathMLView, _super);
        function MathMLView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        MathMLView.prototype._process_text = function (text) {
            var _d;
            return (_d = this.provider.MathJax) === null || _d === void 0 ? void 0 : _d.mathml2svg(text.trim());
        };
        return MathMLView;
    }(MathTextView));
    exports.MathMLView = MathMLView;
    MathMLView.__name__ = "MathMLView";
    var MathML = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MathML, _super);
        function MathML(attrs) {
            return _super.call(this, attrs) || this;
        }
        return MathML;
    }(MathText));
    exports.MathML = MathML;
    _b = MathML;
    MathML.__name__ = "MathML";
    (function () {
        _b.prototype.default_view = MathMLView;
    })();
    var TeXView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TeXView, _super);
        function TeXView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TeXView.prototype._process_text = function (text) {
            var _d;
            // TODO: allow plot/document level configuration of macros
            return (_d = this.provider.MathJax) === null || _d === void 0 ? void 0 : _d.tex2svg(text, undefined, this.model.macros);
        };
        return TeXView;
    }(MathTextView));
    exports.TeXView = TeXView;
    TeXView.__name__ = "TeXView";
    var TeX = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TeX, _super);
        function TeX(attrs) {
            return _super.call(this, attrs) || this;
        }
        return TeX;
    }(MathText));
    exports.TeX = TeX;
    _c = TeX;
    TeX.__name__ = "TeX";
    (function () {
        _c.prototype.default_view = TeXView;
        _c.define(function (_d) {
            var Boolean = _d.Boolean, Number = _d.Number, String = _d.String, Dict = _d.Dict, Tuple = _d.Tuple, Or = _d.Or;
            return ({
                macros: [Dict(Or(String, Tuple(String, Number))), {}],
                inline: [Boolean, false],
            });
        });
    })();
},
/* core/util/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var logging_1 = require(134) /* ../logging */;
    function load_image(url, options) {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                return [2 /*return*/, new ImageLoader(url, options).promise];
            });
        });
    }
    exports.load_image = load_image;
    var ImageLoader = /** @class */ (function () {
        function ImageLoader(url, config) {
            var _this = this;
            if (config === void 0) {
                config = {};
            }
            this._image = new Image();
            this._finished = false;
            var _a = config.attempts, attempts = _a === void 0 ? 1 : _a, _b = config.timeout, timeout = _b === void 0 ? 1 : _b;
            this.promise = new Promise(function (resolve, _reject) {
                _this._image.crossOrigin = "anonymous";
                var retries = 0;
                _this._image.onerror = function () {
                    if (++retries == attempts) {
                        var message = "unable to load " + url + " image after " + attempts + " attempts";
                        logging_1.logger.warn(message);
                        if (_this._image.crossOrigin != null) {
                            logging_1.logger.warn("attempting to load " + url + " without a cross origin policy");
                            _this._image.crossOrigin = null;
                            retries = 0;
                        }
                        else {
                            if (config.failed != null)
                                config.failed();
                            return; // XXX reject(new Error(message))
                        }
                    }
                    setTimeout(function () { return _this._image.src = url; }, timeout);
                };
                _this._image.onload = function () {
                    _this._finished = true;
                    if (config.loaded != null)
                        config.loaded(_this._image);
                    resolve(_this._image);
                };
                _this._image.src = url;
            });
        }
        Object.defineProperty(ImageLoader.prototype, "finished", {
            get: function () {
                return this._finished;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ImageLoader.prototype, "image", {
            get: function () {
                if (this._finished)
                    return this._image;
                else
                    throw new Error("not loaded yet");
            },
            enumerable: false,
            configurable: true
        });
        return ImageLoader;
    }());
    exports.ImageLoader = ImageLoader;
    ImageLoader.__name__ = "ImageLoader";
},
/* models/text/providers.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var signaling_1 = require(130) /* ../../core/signaling */;
    var modules_1 = require(253) /* ../../core/util/modules */;
    var MathJaxProvider = /** @class */ (function () {
        function MathJaxProvider() {
            this.ready = new signaling_1.Signal0(this, "ready");
            this.status = "not_started";
        }
        return MathJaxProvider;
    }());
    exports.MathJaxProvider = MathJaxProvider;
    MathJaxProvider.__name__ = "MathJaxProvider";
    var NoProvider = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NoProvider, _super);
        function NoProvider() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(NoProvider.prototype, "MathJax", {
            get: function () {
                return null;
            },
            enumerable: false,
            configurable: true
        });
        NoProvider.prototype.fetch = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_a) {
                    this.status = "failed";
                    return [2 /*return*/];
                });
            });
        };
        return NoProvider;
    }(MathJaxProvider));
    exports.NoProvider = NoProvider;
    NoProvider.__name__ = "NoProvider";
    var CDNProvider = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CDNProvider, _super);
        function CDNProvider() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(CDNProvider.prototype, "MathJax", {
            get: function () {
                return typeof MathJax !== "undefined" ? MathJax : null;
            },
            enumerable: false,
            configurable: true
        });
        CDNProvider.prototype.fetch = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var script;
                var _this = this;
                return (0, tslib_1.__generator)(this, function (_a) {
                    script = document.createElement("script");
                    script.src = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js";
                    script.onload = function () {
                        _this.status = "loaded";
                        _this.ready.emit();
                    };
                    script.onerror = function () {
                        _this.status = "failed";
                    };
                    this.status = "loading";
                    document.head.appendChild(script);
                    return [2 /*return*/];
                });
            });
        };
        return CDNProvider;
    }(MathJaxProvider));
    exports.CDNProvider = CDNProvider;
    CDNProvider.__name__ = "CDNProvider";
    var BundleProvider = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BundleProvider, _super);
        function BundleProvider() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(BundleProvider.prototype, "MathJax", {
            get: function () {
                return this._mathjax;
            },
            enumerable: false,
            configurable: true
        });
        BundleProvider.prototype.fetch = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var mathjax, error_1;
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.status = "loading";
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, (0, modules_1.load_module)(Promise.resolve().then(function () { return (0, tslib_1.__importStar)(require(630) /* ./mathjax */); }))];
                        case 2:
                            mathjax = _a.sent();
                            this._mathjax = mathjax;
                            this.status = "loaded";
                            this.ready.emit();
                            return [3 /*break*/, 4];
                        case 3:
                            error_1 = _a.sent();
                            this.status = "failed";
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        return BundleProvider;
    }(MathJaxProvider));
    exports.BundleProvider = BundleProvider;
    BundleProvider.__name__ = "BundleProvider";
    exports.default_provider = new BundleProvider();
},
/* core/util/modules.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    function is_ModuleError(error) {
        return error instanceof Error && "code" in error;
    }
    /** T is of import("some/module/path") type */
    function load_module(module) {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var e_1;
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, module];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        e_1 = _a.sent();
                        // XXX: this exposes the underyling module system and hinders
                        // interoperability with other module systems and bundlers
                        if (is_ModuleError(e_1) && e_1.code === "MODULE_NOT_FOUND")
                            return [2 /*return*/, null];
                        else
                            throw e_1;
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        });
    }
    exports.load_module = load_module;
},
/* models/text/plain_text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var base_text_1 = require(248) /* ./base_text */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var PlainTextView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PlainTextView, _super);
        function PlainTextView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PlainTextView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._has_finished = true;
        };
        PlainTextView.prototype.graphics = function () {
            return new graphics_1.TextBox({ text: this.model.text });
        };
        return PlainTextView;
    }(base_text_1.BaseTextView));
    exports.PlainTextView = PlainTextView;
    PlainTextView.__name__ = "PlainTextView";
    var PlainText = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PlainText, _super);
        function PlainText(attrs) {
            return _super.call(this, attrs) || this;
        }
        return PlainText;
    }(base_text_1.BaseText));
    exports.PlainText = PlainText;
    _a = PlainText;
    PlainText.__name__ = "PlainText";
    (function () {
        _a.prototype.default_view = PlainTextView;
    })();
},
/* models/axes/categorical_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var axis_1 = require(243) /* ./axis */;
    var categorical_ticker_1 = require(256) /* ../tickers/categorical_ticker */;
    var categorical_tick_formatter_1 = require(257) /* ../formatters/categorical_tick_formatter */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var enums_1 = require(135) /* ../../core/enums */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var types_1 = require(125) /* ../../core/util/types */;
    var CategoricalAxisView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CategoricalAxisView, _super);
        function CategoricalAxisView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CategoricalAxisView.prototype._paint = function (ctx, extents, tick_coords) {
            this._draw_group_separators(ctx, extents, tick_coords);
        };
        CategoricalAxisView.prototype._draw_group_separators = function (ctx, _extents, _tick_coords) {
            var _b;
            var _c = (0, tslib_1.__read)(this.ranges, 1), range = _c[0];
            var _d = (0, tslib_1.__read)(this.computed_bounds, 2), start = _d[0], end = _d[1];
            if (!range.tops || range.tops.length < 2 || !this.visuals.separator_line.doit)
                return;
            var dim = this.dimension;
            var alt = (dim + 1) % 2;
            var coords = [[], []];
            var ind = 0;
            for (var i = 0; i < range.tops.length - 1; i++) {
                var first = void 0, last = void 0;
                for (var j = ind; j < range.factors.length; j++) {
                    if (range.factors[j][0] == range.tops[i + 1]) {
                        _b = (0, tslib_1.__read)([range.factors[j - 1], range.factors[j]], 2), first = _b[0], last = _b[1];
                        ind = j;
                        break;
                    }
                }
                var pt = (range.synthetic(first) + range.synthetic(last)) / 2;
                if (pt > start && pt < end) {
                    coords[dim].push(pt);
                    coords[alt].push(this.loc);
                }
            }
            var tex = this.extents.tick_label;
            this._draw_ticks(ctx, coords, -3, tex - 6, this.visuals.separator_line);
        };
        CategoricalAxisView.prototype._draw_major_labels = function (ctx, extents, _tick_coords) {
            var info = this._get_factor_info();
            var standoff = extents.tick + this.model.major_label_standoff;
            for (var i = 0; i < info.length; i++) {
                var _b = (0, tslib_1.__read)(info[i], 4), labels = _b[0], coords = _b[1], orient = _b[2], visuals = _b[3];
                this._draw_oriented_labels(ctx, labels, coords, orient, this.panel.side, standoff, visuals);
                standoff += extents.tick_labels[i];
            }
        };
        CategoricalAxisView.prototype._tick_label_extents = function () {
            var e_1, _b;
            var info = this._get_factor_info();
            var extents = [];
            try {
                for (var info_1 = (0, tslib_1.__values)(info), info_1_1 = info_1.next(); !info_1_1.done; info_1_1 = info_1.next()) {
                    var _c = (0, tslib_1.__read)(info_1_1.value, 4), labels = _c[0], orient = _c[2], visuals = _c[3];
                    var extent = this._oriented_labels_extent(labels, orient, this.model.major_label_standoff, visuals);
                    extents.push(extent);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (info_1_1 && !info_1_1.done && (_b = info_1.return))
                        _b.call(info_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return extents;
        };
        CategoricalAxisView.prototype._get_factor_info = function () {
            var _this = this;
            var _b = (0, tslib_1.__read)(this.ranges, 1), range = _b[0];
            var _c = (0, tslib_1.__read)(this.computed_bounds, 2), start = _c[0], end = _c[1];
            var loc = this.loc;
            var ticks = this.model.ticker.get_ticks(start, end, range, loc);
            var coords = this.tick_coords;
            var info = [];
            var map = function (labels) {
                return new graphics_1.GraphicsBoxes(labels.map(function (label) { return (0, types_1.isString)(label) ? new graphics_1.TextBox({ text: label }) : label; }));
            };
            var format = function (ticks) {
                return map(_this.model.formatter.doFormat(ticks, _this));
            };
            if (range.levels == 1) {
                var major = ticks.major;
                var labels = format(major);
                info.push([labels, coords.major, this.model.major_label_orientation, this.visuals.major_label_text]);
            }
            else if (range.levels == 2) {
                var major = ticks.major.map(function (x) { return x[1]; });
                var labels = format(major);
                info.push([labels, coords.major, this.model.major_label_orientation, this.visuals.major_label_text]);
                info.push([map(ticks.tops), coords.tops, this.model.group_label_orientation, this.visuals.group_text]);
            }
            else if (range.levels == 3) {
                var major = ticks.major.map(function (x) { return x[2]; });
                var labels = format(major);
                var mid_labels = ticks.mids.map(function (x) { return x[1]; });
                info.push([labels, coords.major, this.model.major_label_orientation, this.visuals.major_label_text]);
                info.push([map(mid_labels), coords.mids, this.model.subgroup_label_orientation, this.visuals.subgroup_text]);
                info.push([map(ticks.tops), coords.tops, this.model.group_label_orientation, this.visuals.group_text]);
            }
            return info;
        };
        Object.defineProperty(CategoricalAxisView.prototype, "tick_coords", {
            get: function () {
                var _this = this;
                var i = this.dimension;
                var j = (i + 1) % 2;
                var _b = (0, tslib_1.__read)(this.ranges, 1), range = _b[0];
                var _c = (0, tslib_1.__read)(this.computed_bounds, 2), start = _c[0], end = _c[1];
                var ticks = this.model.ticker.get_ticks(start, end, range, this.loc);
                var coords = {
                    major: [[], []],
                    mids: [[], []],
                    tops: [[], []],
                    minor: [[], []],
                };
                coords.major[i] = ticks.major;
                coords.major[j] = ticks.major.map(function () { return _this.loc; });
                if (range.levels == 3) {
                    coords.mids[i] = ticks.mids;
                    coords.mids[j] = ticks.mids.map(function () { return _this.loc; });
                }
                if (range.levels > 1) {
                    coords.tops[i] = ticks.tops;
                    coords.tops[j] = ticks.tops.map(function () { return _this.loc; });
                }
                return coords;
            },
            enumerable: false,
            configurable: true
        });
        return CategoricalAxisView;
    }(axis_1.AxisView));
    exports.CategoricalAxisView = CategoricalAxisView;
    CategoricalAxisView.__name__ = "CategoricalAxisView";
    var CategoricalAxis = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CategoricalAxis, _super);
        function CategoricalAxis(attrs) {
            return _super.call(this, attrs) || this;
        }
        return CategoricalAxis;
    }(axis_1.Axis));
    exports.CategoricalAxis = CategoricalAxis;
    _a = CategoricalAxis;
    CategoricalAxis.__name__ = "CategoricalAxis";
    (function () {
        _a.prototype.default_view = CategoricalAxisView;
        _a.mixins([
            ["separator_", mixins.Line],
            ["group_", mixins.Text],
            ["subgroup_", mixins.Text],
        ]);
        _a.define(function (_b) {
            var Number = _b.Number, Or = _b.Or;
            return ({
                group_label_orientation: [Or(enums_1.TickLabelOrientation, Number), "parallel"],
                subgroup_label_orientation: [Or(enums_1.TickLabelOrientation, Number), "parallel"],
            });
        });
        _a.override({
            ticker: function () { return new categorical_ticker_1.CategoricalTicker(); },
            formatter: function () { return new categorical_tick_formatter_1.CategoricalTickFormatter(); },
            separator_line_color: "lightgrey",
            separator_line_width: 2,
            group_text_font_style: "bold",
            group_text_font_size: "11px",
            group_text_color: "grey",
            subgroup_text_font_style: "bold",
            subgroup_text_font_size: "11px",
        });
    })();
},
/* models/tickers/categorical_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var ticker_1 = require(245) /* ./ticker */;
    var CategoricalTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CategoricalTicker, _super);
        function CategoricalTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        CategoricalTicker.prototype.get_ticks = function (start, end, range, _cross_loc) {
            var _a, _b;
            var majors = this._collect(range.factors, range, start, end);
            var tops = this._collect((_a = range.tops) !== null && _a !== void 0 ? _a : [], range, start, end);
            var mids = this._collect((_b = range.mids) !== null && _b !== void 0 ? _b : [], range, start, end);
            return {
                major: majors,
                minor: [],
                tops: tops,
                mids: mids,
            };
        };
        CategoricalTicker.prototype._collect = function (factors, range, start, end) {
            var e_1, _a;
            var result = [];
            try {
                for (var factors_1 = (0, tslib_1.__values)(factors), factors_1_1 = factors_1.next(); !factors_1_1.done; factors_1_1 = factors_1.next()) {
                    var factor = factors_1_1.value;
                    var coord = range.synthetic(factor);
                    if (coord > start && coord < end)
                        result.push(factor);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (factors_1_1 && !factors_1_1.done && (_a = factors_1.return))
                        _a.call(factors_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return result;
        };
        return CategoricalTicker;
    }(ticker_1.Ticker));
    exports.CategoricalTicker = CategoricalTicker;
    CategoricalTicker.__name__ = "CategoricalTicker";
},
/* models/formatters/categorical_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var tick_formatter_1 = require(246) /* ./tick_formatter */;
    var array_1 = require(126) /* ../../core/util/array */;
    var CategoricalTickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CategoricalTickFormatter, _super);
        function CategoricalTickFormatter(attrs) {
            return _super.call(this, attrs) || this;
        }
        CategoricalTickFormatter.prototype.doFormat = function (ticks, _opts) {
            return (0, array_1.copy)(ticks);
        };
        return CategoricalTickFormatter;
    }(tick_formatter_1.TickFormatter));
    exports.CategoricalTickFormatter = CategoricalTickFormatter;
    CategoricalTickFormatter.__name__ = "CategoricalTickFormatter";
},
/* models/axes/continuous_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var axis_1 = require(243) /* ./axis */;
    var ContinuousAxisView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ContinuousAxisView, _super);
        function ContinuousAxisView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ContinuousAxisView;
    }(axis_1.AxisView));
    exports.ContinuousAxisView = ContinuousAxisView;
    ContinuousAxisView.__name__ = "ContinuousAxisView";
    var ContinuousAxis = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ContinuousAxis, _super);
        function ContinuousAxis(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ContinuousAxis;
    }(axis_1.Axis));
    exports.ContinuousAxis = ContinuousAxis;
    ContinuousAxis.__name__ = "ContinuousAxis";
},
/* models/axes/datetime_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var linear_axis_1 = require(260) /* ./linear_axis */;
    var datetime_tick_formatter_1 = require(265) /* ../formatters/datetime_tick_formatter */;
    var datetime_ticker_1 = require(270) /* ../tickers/datetime_ticker */;
    var DatetimeAxisView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DatetimeAxisView, _super);
        function DatetimeAxisView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return DatetimeAxisView;
    }(linear_axis_1.LinearAxisView));
    exports.DatetimeAxisView = DatetimeAxisView;
    DatetimeAxisView.__name__ = "DatetimeAxisView";
    var DatetimeAxis = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DatetimeAxis, _super);
        function DatetimeAxis(attrs) {
            return _super.call(this, attrs) || this;
        }
        return DatetimeAxis;
    }(linear_axis_1.LinearAxis));
    exports.DatetimeAxis = DatetimeAxis;
    _a = DatetimeAxis;
    DatetimeAxis.__name__ = "DatetimeAxis";
    (function () {
        _a.prototype.default_view = DatetimeAxisView;
        _a.override({
            ticker: function () { return new datetime_ticker_1.DatetimeTicker(); },
            formatter: function () { return new datetime_tick_formatter_1.DatetimeTickFormatter(); },
        });
    })();
},
/* models/axes/linear_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var continuous_axis_1 = require(258) /* ./continuous_axis */;
    var basic_tick_formatter_1 = require(261) /* ../formatters/basic_tick_formatter */;
    var basic_ticker_1 = require(262) /* ../tickers/basic_ticker */;
    var LinearAxisView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LinearAxisView, _super);
        function LinearAxisView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LinearAxisView;
    }(continuous_axis_1.ContinuousAxisView));
    exports.LinearAxisView = LinearAxisView;
    LinearAxisView.__name__ = "LinearAxisView";
    var LinearAxis = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LinearAxis, _super);
        function LinearAxis(attrs) {
            return _super.call(this, attrs) || this;
        }
        return LinearAxis;
    }(continuous_axis_1.ContinuousAxis));
    exports.LinearAxis = LinearAxis;
    _a = LinearAxis;
    LinearAxis.__name__ = "LinearAxis";
    (function () {
        _a.prototype.default_view = LinearAxisView;
        _a.override({
            ticker: function () { return new basic_ticker_1.BasicTicker(); },
            formatter: function () { return new basic_tick_formatter_1.BasicTickFormatter(); },
        });
    })();
},
/* models/formatters/basic_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var tick_formatter_1 = require(246) /* ./tick_formatter */;
    var string_1 = require(149) /* ../../core/util/string */;
    function unicode_replace(input) {
        var e_1, _b;
        var output = "";
        try {
            for (var input_1 = (0, tslib_1.__values)(input), input_1_1 = input_1.next(); !input_1_1.done; input_1_1 = input_1.next()) {
                var c = input_1_1.value;
                if (c == "-")
                    output += "\u2212";
                else
                    output += c;
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (input_1_1 && !input_1_1.done && (_b = input_1.return))
                    _b.call(input_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return output;
    }
    exports.unicode_replace = unicode_replace;
    var BasicTickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BasicTickFormatter, _super);
        function BasicTickFormatter(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.last_precision = 3;
            return _this;
        }
        Object.defineProperty(BasicTickFormatter.prototype, "scientific_limit_low", {
            get: function () {
                return Math.pow(10.0, this.power_limit_low);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(BasicTickFormatter.prototype, "scientific_limit_high", {
            get: function () {
                return Math.pow(10.0, this.power_limit_high);
            },
            enumerable: false,
            configurable: true
        });
        BasicTickFormatter.prototype._need_sci = function (ticks) {
            var e_2, _b;
            if (!this.use_scientific)
                return false;
            var scientific_limit_high = this.scientific_limit_high;
            var scientific_limit_low = this.scientific_limit_low;
            var zeroish = ticks.length < 2 ? 0 : Math.abs(ticks[1] - ticks[0]) / 10000;
            try {
                for (var ticks_1 = (0, tslib_1.__values)(ticks), ticks_1_1 = ticks_1.next(); !ticks_1_1.done; ticks_1_1 = ticks_1.next()) {
                    var tick = ticks_1_1.value;
                    var tick_abs = Math.abs(tick);
                    if (tick_abs <= zeroish)
                        continue;
                    if (tick_abs >= scientific_limit_high || tick_abs <= scientific_limit_low) {
                        return true;
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (ticks_1_1 && !ticks_1_1.done && (_b = ticks_1.return))
                        _b.call(ticks_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return false;
        };
        BasicTickFormatter.prototype._format_with_precision = function (ticks, need_sci, precision) {
            if (need_sci) {
                return ticks.map(function (tick) { return unicode_replace(tick.toExponential(precision)); });
            }
            else {
                return ticks.map(function (tick) { return unicode_replace((0, string_1.to_fixed)(tick, precision)); });
            }
        };
        BasicTickFormatter.prototype._auto_precision = function (ticks, need_sci) {
            var labels = new Array(ticks.length);
            var asc = this.last_precision <= 15;
            outer: for (var x = this.last_precision; asc ? x <= 15 : x >= 1; asc ? x++ : x--) {
                if (need_sci) {
                    labels[0] = ticks[0].toExponential(x);
                    for (var i = 1; i < ticks.length; i++) {
                        if (labels[i] == labels[i - 1]) {
                            continue outer;
                        }
                    }
                    this.last_precision = x;
                    break;
                }
                else {
                    labels[0] = (0, string_1.to_fixed)(ticks[0], x);
                    for (var i = 1; i < ticks.length; i++) {
                        labels[i] = (0, string_1.to_fixed)(ticks[i], x);
                        if (labels[i] == labels[i - 1]) {
                            continue outer;
                        }
                    }
                    this.last_precision = x;
                    break;
                }
            }
            return this.last_precision;
        };
        BasicTickFormatter.prototype.doFormat = function (ticks, _opts) {
            if (ticks.length == 0)
                return [];
            var need_sci = this._need_sci(ticks);
            var precision = this.precision == "auto" ? this._auto_precision(ticks, need_sci) : this.precision;
            return this._format_with_precision(ticks, need_sci, precision);
        };
        return BasicTickFormatter;
    }(tick_formatter_1.TickFormatter));
    exports.BasicTickFormatter = BasicTickFormatter;
    _a = BasicTickFormatter;
    BasicTickFormatter.__name__ = "BasicTickFormatter";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Int = _b.Int, Auto = _b.Auto, Or = _b.Or;
            return ({
                precision: [Or(Int, Auto), "auto"],
                use_scientific: [Boolean, true],
                power_limit_high: [Int, 5],
                power_limit_low: [Int, -3],
            });
        });
    })();
},
/* models/tickers/basic_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var adaptive_ticker_1 = require(263) /* ./adaptive_ticker */;
    var BasicTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BasicTicker, _super);
        function BasicTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        return BasicTicker;
    }(adaptive_ticker_1.AdaptiveTicker));
    exports.BasicTicker = BasicTicker;
    BasicTicker.__name__ = "BasicTicker";
},
/* models/tickers/adaptive_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var continuous_ticker_1 = require(264) /* ./continuous_ticker */;
    var array_1 = require(126) /* ../../core/util/array */;
    var math_1 = require(117) /* ../../core/util/math */;
    var AdaptiveTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AdaptiveTicker, _super);
        function AdaptiveTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        AdaptiveTicker.prototype.get_min_interval = function () {
            return this.min_interval;
        };
        AdaptiveTicker.prototype.get_max_interval = function () {
            var _b;
            return (_b = this.max_interval) !== null && _b !== void 0 ? _b : Infinity;
        };
        // These arguments control the range of possible intervals.  The interval I
        // returned by get_interval() will be the one that most closely matches the
        // desired number of ticks, subject to the following constraints:
        // I = (M * B^N), where
        // M is a member of mantissas,
        // B is base,
        // and N is an integer;
        // and min_interval <= I <= max_interval.
        AdaptiveTicker.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            var prefix_mantissa = (0, array_1.nth)(this.mantissas, -1) / this.base;
            var suffix_mantissa = (0, array_1.nth)(this.mantissas, 0) * this.base;
            this.extended_mantissas = (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([prefix_mantissa], (0, tslib_1.__read)(this.mantissas), false), [suffix_mantissa], false);
            this.base_factor = this.get_min_interval() === 0.0 ? 1.0 : this.get_min_interval();
        };
        AdaptiveTicker.prototype.get_interval = function (data_low, data_high, desired_n_ticks) {
            var data_range = data_high - data_low;
            var ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
            var interval_exponent = Math.floor((0, math_1.log)(ideal_interval / this.base_factor, this.base));
            var ideal_magnitude = Math.pow(this.base, interval_exponent) * this.base_factor;
            // An untested optimization.
            //   const ideal_mantissa = ideal_interval / ideal_magnitude
            //   index = sorted_index(this.extended_mantissas, ideal_mantissa)
            //   candidate_mantissas = this.extended_mantissas[index..index + 1]
            var candidate_mantissas = this.extended_mantissas;
            var errors = candidate_mantissas.map(function (mantissa) {
                return Math.abs(desired_n_ticks - (data_range / (mantissa * ideal_magnitude)));
            });
            var best_mantissa = candidate_mantissas[(0, array_1.argmin)(errors)];
            var interval = best_mantissa * ideal_magnitude;
            return (0, math_1.clamp)(interval, this.get_min_interval(), this.get_max_interval());
        };
        return AdaptiveTicker;
    }(continuous_ticker_1.ContinuousTicker));
    exports.AdaptiveTicker = AdaptiveTicker;
    _a = AdaptiveTicker;
    AdaptiveTicker.__name__ = "AdaptiveTicker";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Array = _b.Array, Nullable = _b.Nullable;
            return ({
                base: [Number, 10.0],
                mantissas: [Array(Number), [1, 2, 5]],
                min_interval: [Number, 0.0],
                max_interval: [Nullable(Number), null],
            });
        });
    })();
},
/* models/tickers/continuous_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var ticker_1 = require(245) /* ./ticker */;
    var array_1 = require(126) /* ../../core/util/array */;
    var ContinuousTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ContinuousTicker, _super);
        function ContinuousTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        ContinuousTicker.prototype.get_ticks = function (data_low, data_high, _range, cross_loc) {
            return this.get_ticks_no_defaults(data_low, data_high, cross_loc, this.desired_num_ticks);
        };
        // The version of get_ticks() that does the work (and the version that
        // should be overridden in subclasses).
        ContinuousTicker.prototype.get_ticks_no_defaults = function (data_low, data_high, _cross_loc, desired_n_ticks) {
            var e_1, _b, e_2, _c, e_3, _d;
            var interval = this.get_interval(data_low, data_high, desired_n_ticks);
            var start_factor = Math.floor(data_low / interval);
            var end_factor = Math.ceil(data_high / interval);
            var factors;
            if (!isFinite(start_factor) || !isFinite(end_factor))
                factors = [];
            else
                factors = (0, array_1.range)(start_factor, end_factor + 1);
            var ticks = factors
                .map(function (factor) { return factor * interval; })
                .filter(function (tick) { return data_low <= tick && tick <= data_high; });
            var num_minor_ticks = this.num_minor_ticks;
            var minor_ticks = [];
            if (num_minor_ticks > 0 && ticks.length > 0) {
                var minor_interval_1 = interval / num_minor_ticks;
                var minor_offsets = (0, array_1.range)(0, num_minor_ticks).map(function (i) { return i * minor_interval_1; });
                try {
                    for (var _e = (0, tslib_1.__values)(minor_offsets.slice(1)), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var x = _f.value;
                        var mt = ticks[0] - x;
                        if (data_low <= mt && mt <= data_high) {
                            minor_ticks.push(mt);
                        }
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (_f && !_f.done && (_b = _e.return))
                            _b.call(_e);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
                try {
                    for (var ticks_1 = (0, tslib_1.__values)(ticks), ticks_1_1 = ticks_1.next(); !ticks_1_1.done; ticks_1_1 = ticks_1.next()) {
                        var tick = ticks_1_1.value;
                        try {
                            for (var minor_offsets_1 = (e_3 = void 0, (0, tslib_1.__values)(minor_offsets)), minor_offsets_1_1 = minor_offsets_1.next(); !minor_offsets_1_1.done; minor_offsets_1_1 = minor_offsets_1.next()) {
                                var x = minor_offsets_1_1.value;
                                var mt = tick + x;
                                if (data_low <= mt && mt <= data_high) {
                                    minor_ticks.push(mt);
                                }
                            }
                        }
                        catch (e_3_1) {
                            e_3 = { error: e_3_1 };
                        }
                        finally {
                            try {
                                if (minor_offsets_1_1 && !minor_offsets_1_1.done && (_d = minor_offsets_1.return))
                                    _d.call(minor_offsets_1);
                            }
                            finally {
                                if (e_3)
                                    throw e_3.error;
                            }
                        }
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (ticks_1_1 && !ticks_1_1.done && (_c = ticks_1.return))
                            _c.call(ticks_1);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
            }
            return {
                major: ticks,
                minor: minor_ticks,
            };
        };
        // Returns the interval size that would produce exactly the number of
        // desired ticks.  (In general we won't use exactly this interval, because
        // we want the ticks to be round numbers.)
        ContinuousTicker.prototype.get_ideal_interval = function (data_low, data_high, desired_n_ticks) {
            var data_range = data_high - data_low;
            return data_range / desired_n_ticks;
        };
        return ContinuousTicker;
    }(ticker_1.Ticker));
    exports.ContinuousTicker = ContinuousTicker;
    _a = ContinuousTicker;
    ContinuousTicker.__name__ = "ContinuousTicker";
    (function () {
        _a.define(function (_b) {
            var Int = _b.Int;
            return ({
                num_minor_ticks: [Int, 5],
                desired_num_ticks: [Int, 6],
            });
        });
    })();
},
/* models/formatters/datetime_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var timezone_1 = (0, tslib_1.__importDefault)(require(266) /* timezone */);
    var tick_formatter_1 = require(246) /* ./tick_formatter */;
    var logging_1 = require(134) /* ../../core/logging */;
    var templating_1 = require(267) /* ../../core/util/templating */;
    var array_1 = require(126) /* ../../core/util/array */;
    var types_1 = require(125) /* ../../core/util/types */;
    function _us(t) {
        // From double-precision unix (millisecond) timestamp get
        // microsecond since last second. Precision seems to run
        // out around the hundreds of nanoseconds scale, so rounding
        // to the nearest microsecond should round to a nice
        // microsecond / millisecond tick.
        return Math.round(((t / 1000) % 1) * 1000000);
    }
    function _array(t) {
        return (0, timezone_1.default)(t, "%Y %m %d %H %M %S").split(/\s+/).map(function (e) { return parseInt(e, 10); });
    }
    function _strftime(t, format) {
        if ((0, types_1.isFunction)(format)) {
            return format(t);
        }
        else {
            // Python's datetime library augments the microsecond directive %f, which is not
            // supported by the javascript library timezone: http://bigeasy.github.io/timezone/.
            // Use a regular expression to replace %f directive with microseconds.
            // TODO: what should we do for negative microsecond strings?
            var microsecond_replacement_string = (0, templating_1.sprintf)("$1%06d", _us(t));
            format = format.replace(/((^|[^%])(%%)*)%f/, microsecond_replacement_string);
            if (format.indexOf("%") == -1) {
                // timezone seems to ignore any strings without any formatting directives,
                // and just return the time argument back instead of the string argument.
                // But we want the string argument, in case a user supplies a format string
                // which doesn't contain a formatting directive or is only using %f.
                return format;
            }
            return (0, timezone_1.default)(t, format);
        }
    }
    // Labels of time units, from finest to coarsest.
    var format_order = [
        "microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days", "months", "years",
    ];
    var DatetimeTickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DatetimeTickFormatter, _super);
        function DatetimeTickFormatter(attrs) {
            var _this = _super.call(this, attrs) || this;
            // Whether or not to strip the leading zeros on tick labels.
            _this.strip_leading_zeros = true;
            return _this;
        }
        DatetimeTickFormatter.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            // TODO (bev) trigger update on format change
            this._update_width_formats();
        };
        DatetimeTickFormatter.prototype._update_width_formats = function () {
            var now = +(0, timezone_1.default)(new Date());
            var _widths = function (fmt_strings) {
                var sizes = fmt_strings.map(function (fmt_string) { return _strftime(now, fmt_string).length; });
                var sorted = (0, array_1.sort_by)((0, array_1.zip)(sizes, fmt_strings), function (_b) {
                    var _c = (0, tslib_1.__read)(_b, 1), size = _c[0];
                    return size;
                });
                return (0, array_1.unzip)(sorted);
            };
            this._width_formats = {
                microseconds: _widths(this.microseconds),
                milliseconds: _widths(this.milliseconds),
                seconds: _widths(this.seconds),
                minsec: _widths(this.minsec),
                minutes: _widths(this.minutes),
                hourmin: _widths(this.hourmin),
                hours: _widths(this.hours),
                days: _widths(this.days),
                months: _widths(this.months),
                years: _widths(this.years),
            };
        };
        // FIXME There is some unfortunate flicker when panning/zooming near the
        // span boundaries.
        // FIXME Rounding is weird at the 20-us scale and below.
        DatetimeTickFormatter.prototype._get_resolution_str = function (resolution_secs, span_secs) {
            // Our resolution boundaries should not be round numbers, because we want
            // them to fall between the possible tick intervals (which *are* round
            // numbers, as we've worked hard to ensure).  Consequently, we adjust the
            // resolution upwards a small amount (less than any possible step in
            // scales) to make the effective boundaries slightly lower.
            var adjusted_secs = resolution_secs * 1.1;
            switch (false) {
                case !(adjusted_secs < 1e-3): return "microseconds";
                case !(adjusted_secs < 1.0): return "milliseconds";
                case !(adjusted_secs < 60): return span_secs >= 60 ? "minsec" : "seconds";
                case !(adjusted_secs < 3600): return span_secs >= 3600 ? "hourmin" : "minutes";
                case !(adjusted_secs < (24 * 3600)): return "hours";
                case !(adjusted_secs < (31 * 24 * 3600)): return "days";
                case !(adjusted_secs < (365 * 24 * 3600)): return "months";
                default: return "years";
            }
        };
        DatetimeTickFormatter.prototype.doFormat = function (ticks, _opts) {
            var e_1, _b, e_2, _c;
            // In order to pick the right set of labels, we need to determine
            // the resolution of the ticks.  We can do this using a ticker if
            // it's provided, or by computing the resolution from the actual
            // ticks we've been given.
            if (ticks.length == 0)
                return [];
            var span = Math.abs(ticks[ticks.length - 1] - ticks[0]) / 1000.0;
            var r = span / (ticks.length - 1);
            var resol = this._get_resolution_str(r, span);
            var _d = (0, tslib_1.__read)(this._width_formats[resol], 2), _e = (0, tslib_1.__read)(_d[1], 1), format = _e[0];
            // Apply the format to the tick values
            var labels = [];
            var resol_ndx = format_order.indexOf(resol);
            // This dictionary maps the name of a time resolution (in @format_order)
            // to its index in a time.localtime() timetuple.  The default is to map
            // everything to index 0, which is year.  This is not ideal; it might cause
            // a problem with the tick at midnight, january 1st, 0 a.d. being incorrectly
            // promoted at certain tick resolutions.
            var time_tuple_ndx_for_resol = {};
            try {
                for (var format_order_1 = (0, tslib_1.__values)(format_order), format_order_1_1 = format_order_1.next(); !format_order_1_1.done; format_order_1_1 = format_order_1.next()) {
                    var fmt = format_order_1_1.value;
                    time_tuple_ndx_for_resol[fmt] = 0;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (format_order_1_1 && !format_order_1_1.done && (_b = format_order_1.return))
                        _b.call(format_order_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            time_tuple_ndx_for_resol.seconds = 5;
            time_tuple_ndx_for_resol.minsec = 4;
            time_tuple_ndx_for_resol.minutes = 4;
            time_tuple_ndx_for_resol.hourmin = 3;
            time_tuple_ndx_for_resol.hours = 3;
            try {
                // As we format each tick, check to see if we are at a boundary of the
                // next higher unit of time.  If so, replace the current format with one
                // from that resolution.  This is not the best heuristic in the world,
                // but it works!  There is some trickiness here due to having to deal
                // with hybrid formats in a reasonable manner.
                for (var ticks_1 = (0, tslib_1.__values)(ticks), ticks_1_1 = ticks_1.next(); !ticks_1_1.done; ticks_1_1 = ticks_1.next()) {
                    var t = ticks_1_1.value;
                    var s = void 0, tm = void 0;
                    try {
                        tm = _array(t);
                        s = _strftime(t, format);
                    }
                    catch (error) {
                        logging_1.logger.warn("unable to format tick for timestamp value " + t);
                        logging_1.logger.warn(" - " + error);
                        labels.push("ERR");
                        continue;
                    }
                    var hybrid_handled = false;
                    var next_ndx = resol_ndx;
                    // The way to check that we are at the boundary of the next unit of
                    // time is by checking that we have 0 units of the resolution, i.e.
                    // we are at zero minutes, so display hours, or we are at zero seconds,
                    // so display minutes (and if that is zero as well, then display hours).
                    while (tm[time_tuple_ndx_for_resol[format_order[next_ndx]]] == 0) {
                        var next_format = void 0;
                        next_ndx += 1;
                        if (next_ndx == format_order.length)
                            break;
                        if ((resol == "minsec" || resol == "hourmin") && !hybrid_handled) {
                            if ((resol == "minsec" && tm[4] == 0 && tm[5] != 0) || (resol == "hourmin" && tm[3] == 0 && tm[4] != 0)) {
                                next_format = this._width_formats[format_order[resol_ndx - 1]][1][0];
                                s = _strftime(t, next_format);
                                break;
                            }
                            else {
                                hybrid_handled = true;
                            }
                        }
                        next_format = this._width_formats[format_order[next_ndx]][1][0];
                        s = _strftime(t, next_format);
                    }
                    // TODO: should expose this in api. %H, %d, etc use leading zeros and
                    // users might prefer to see them lined up correctly.
                    if (this.strip_leading_zeros) {
                        var ss = s.replace(/^0+/g, "");
                        if (ss != s && isNaN(parseInt(ss))) {
                            // If the string can now be parsed as starting with an integer, then
                            // leave all zeros stripped, otherwise start with a zero. Hence:
                            // A label such as '000ms' should leave one zero.
                            // A label such as '001ms' or '0-1ms' should not leave a leading zero.
                            ss = "0" + ss;
                        }
                        labels.push(ss);
                    }
                    else
                        labels.push(s);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (ticks_1_1 && !ticks_1_1.done && (_c = ticks_1.return))
                        _c.call(ticks_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return labels;
        };
        return DatetimeTickFormatter;
    }(tick_formatter_1.TickFormatter));
    exports.DatetimeTickFormatter = DatetimeTickFormatter;
    _a = DatetimeTickFormatter;
    DatetimeTickFormatter.__name__ = "DatetimeTickFormatter";
    (function () {
        _a.define(function (_b) {
            var String = _b.String, Array = _b.Array;
            return ({
                microseconds: [Array(String), ["%fus"]],
                milliseconds: [Array(String), ["%3Nms", "%S.%3Ns"]],
                seconds: [Array(String), ["%Ss"]],
                minsec: [Array(String), [":%M:%S"]],
                minutes: [Array(String), [":%M", "%Mm"]],
                hourmin: [Array(String), ["%H:%M"]],
                hours: [Array(String), ["%Hh", "%H:%M"]],
                days: [Array(String), ["%m/%d", "%a%d"]],
                months: [Array(String), ["%m/%Y", "%b %Y"]],
                years: [Array(String), ["%Y"]],
            });
        });
    })();
},
/* timezone/index.js */ function _(require, module, exports, __esModule, __esExport) {
    !function (definition) {
        if (typeof module == "object" && module.exports)
            module.exports = definition();
        else if (typeof define == "function")
            define(definition);
        else
            this.tz = definition();
    }(function () {
        /*
          function die () {
            console.log.apply(console, __slice.call(arguments, 0));
            return process.exit(1);
          }
        
          function say () { return console.log.apply(console, __slice.call(arguments, 0)) }
        */
        function actualize(entry, rule, year) {
            var actualized, date = rule.day[1];
            do {
                actualized = new Date(Date.UTC(year, rule.month, Math.abs(date++)));
            } while (rule.day[0] < 7 && actualized.getUTCDay() != rule.day[0]);
            actualized = {
                clock: rule.clock,
                sort: actualized.getTime(),
                rule: rule,
                save: rule.save * 6e4,
                offset: entry.offset
            };
            actualized[actualized.clock] = actualized.sort + rule.time * 6e4;
            if (actualized.posix) {
                actualized.wallclock = actualized[actualized.clock] + (entry.offset + rule.saved);
            }
            else {
                actualized.posix = actualized[actualized.clock] - (entry.offset + rule.saved);
            }
            return actualized;
        }
        function find(request, clock, time) {
            var i, I, entry, found, zone = request[request.zone], actualized = [], abbrev, rules, j, year = new Date(time).getUTCFullYear(), off = 1;
            for (i = 1, I = zone.length; i < I; i++)
                if (zone[i][clock] <= time)
                    break;
            entry = zone[i];
            if (entry.rules) {
                rules = request[entry.rules];
                for (j = year + 1; j >= year - off; --j)
                    for (i = 0, I = rules.length; i < I; i++)
                        if (rules[i].from <= j && j <= rules[i].to)
                            actualized.push(actualize(entry, rules[i], j));
                        else if (rules[i].to < j && off == 1)
                            off = j - rules[i].to;
                actualized.sort(function (a, b) { return a.sort - b.sort; });
                for (i = 0, I = actualized.length; i < I; i++) {
                    if (time >= actualized[i][clock] && actualized[i][actualized[i].clock] > entry[actualized[i].clock])
                        found = actualized[i];
                }
            }
            if (found) {
                if (abbrev = /^(.*)\/(.*)$/.exec(entry.format)) {
                    found.abbrev = abbrev[found.save ? 2 : 1];
                }
                else {
                    found.abbrev = entry.format.replace(/%s/, found.rule.letter);
                }
            }
            return found || entry;
        }
        function convertToWallclock(request, posix) {
            if (request.zone == "UTC")
                return posix;
            request.entry = find(request, "posix", posix);
            return posix + request.entry.offset + request.entry.save;
        }
        function convertToPOSIX(request, wallclock) {
            if (request.zone == "UTC")
                return wallclock;
            var entry, diff;
            request.entry = entry = find(request, "wallclock", wallclock);
            diff = wallclock - entry.wallclock;
            return 0 < diff && diff < entry.save ? null : wallclock - entry.offset - entry.save;
        }
        function adjust(request, posix, match) {
            var increment = +(match[1] + 1) // conversion necessary for week day addition
            , offset = match[2] * increment, index = UNITS.indexOf(match[3].toLowerCase()), date;
            if (index > 9) {
                posix += offset * TIME[index - 10];
            }
            else {
                date = new Date(convertToWallclock(request, posix));
                if (index < 7) {
                    while (offset) {
                        date.setUTCDate(date.getUTCDate() + increment);
                        if (date.getUTCDay() == index)
                            offset -= increment;
                    }
                }
                else if (index == 7) {
                    date.setUTCFullYear(date.getUTCFullYear() + offset);
                }
                else if (index == 8) {
                    date.setUTCMonth(date.getUTCMonth() + offset);
                }
                else {
                    date.setUTCDate(date.getUTCDate() + offset);
                }
                if ((posix = convertToPOSIX(request, date.getTime())) == null) {
                    posix = convertToPOSIX(request, date.getTime() + 864e5 * increment) - 864e5 * increment;
                }
            }
            return posix;
        }
        function convert(vargs) {
            if (!vargs.length)
                return "1.0.23";
            var request = Object.create(this), adjustments = [], i, I, $, argument, date;
            for (i = 0; i < vargs.length; i++) { // leave the for loop alone, it works.
                argument = vargs[i];
                // https://twitter.com/bigeasy/status/215112186572439552
                if (Array.isArray(argument)) {
                    if (!i && !isNaN(argument[1])) {
                        date = argument;
                    }
                    else {
                        argument.splice.apply(vargs, [i--, 1].concat(argument));
                    }
                }
                else if (isNaN(argument)) {
                    $ = typeof argument;
                    if ($ == "string") {
                        if (~argument.indexOf("%")) {
                            request.format = argument;
                        }
                        else if (!i && argument == "*") {
                            date = argument;
                        }
                        else if (!i && ($ = /^(\d{4})-(\d{2})-(\d{2})(?:[T\s](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|(([+-])(\d{2}(:\d{2}){0,2})))?)?$/.exec(argument))) {
                            date = [];
                            date.push.apply(date, $.slice(1, 8));
                            if ($[9]) {
                                date.push($[10] + 1);
                                date.push.apply(date, $[11].split(/:/));
                            }
                            else if ($[8]) {
                                date.push(1);
                            }
                        }
                        else if (/^\w{2,3}_\w{2}$/.test(argument)) {
                            request.locale = argument;
                        }
                        else if ($ = UNIT_RE.exec(argument)) {
                            adjustments.push($);
                        }
                        else {
                            request.zone = argument;
                        }
                    }
                    else if ($ == "function") {
                        if ($ = argument.call(request))
                            return $;
                    }
                    else if (/^\w{2,3}_\w{2}$/.test(argument.name)) {
                        request[argument.name] = argument;
                    }
                    else if (argument.zones) {
                        for ($ in argument.zones)
                            request[$] = argument.zones[$];
                        for ($ in argument.rules)
                            request[$] = argument.rules[$];
                    }
                }
                else if (!i) {
                    date = argument;
                }
            }
            if (!request[request.locale])
                delete request.locale;
            if (!request[request.zone])
                delete request.zone;
            if (date != null) {
                if (date == "*") {
                    date = request.clock();
                }
                else if (Array.isArray(date)) {
                    $ = [];
                    I = !date[7];
                    for (i = 0; i < 11; i++)
                        $[i] = +(date[i] || 0); // conversion necessary for decrement
                    --$[1]; // Grr..
                    date = Date.UTC.apply(Date.UTC, $) + -$[7] * ($[8] * 36e5 + $[9] * 6e4 + $[10] * 1e3);
                }
                else {
                    date = Math.floor(date);
                }
                if (!isNaN(date)) {
                    if (I)
                        date = convertToPOSIX(request, date);
                    if (date == null)
                        return date;
                    for (i = 0, I = adjustments.length; i < I; i++) {
                        date = adjust(request, date, adjustments[i]);
                    }
                    if (!request.format)
                        return date;
                    $ = new Date(convertToWallclock(request, date));
                    return request.format.replace(/%([-0_^]?)(:{0,3})(\d*)(.)/g, function (value, flag, colons, padding, specifier) {
                        var f, fill = "0", pad;
                        if (f = request[specifier]) {
                            value = String(f.call(request, $, date, flag, colons.length));
                            if ((flag || f.style) == "_")
                                fill = " ";
                            pad = flag == "-" ? 0 : f.pad || 0;
                            while (value.length < pad)
                                value = fill + value;
                            pad = flag == "-" ? 0 : padding || f.pad;
                            while (value.length < pad)
                                value = fill + value;
                            if (specifier == "N" && pad < value.length)
                                value = value.slice(0, pad);
                            if (flag == "^")
                                value = value.toUpperCase();
                        }
                        return value;
                    });
                }
            }
            return function () { return request.convert(arguments); };
        }
        var context = { clock: function () { return +(new Date()); },
            zone: "UTC",
            entry: { abbrev: "UTC", offset: 0, save: 0 },
            UTC: 1,
            z: function (date, posix, flag, delimiters) {
                var offset = this.entry.offset + this.entry.save, seconds = Math.abs(offset / 1000), parts = [], part = 3600, i, z;
                for (i = 0; i < 3; i++) {
                    parts.push(("0" + Math.floor(seconds / part)).slice(-2));
                    seconds %= part;
                    part /= 60;
                }
                if (flag == "^" && !offset)
                    return "Z";
                if (flag == "^")
                    delimiters = 3;
                if (delimiters == 3) {
                    z = parts.join(":");
                    z = z.replace(/:00$/, "");
                    if (flag != "^")
                        z = z.replace(/:00$/, "");
                }
                else if (delimiters) {
                    z = parts.slice(0, delimiters + 1).join(":");
                    if (flag == "^")
                        z = z.replace(/:00$/, "");
                }
                else {
                    z = parts.slice(0, 2).join("");
                }
                z = (offset < 0 ? "-" : "+") + z;
                z = z.replace(/([-+])(0)/, { "_": " $1", "-": "$1" }[flag] || "$1$2");
                return z;
            },
            "%": function (date) { return "%"; },
            n: function (date) { return "\n"; },
            t: function (date) { return "\t"; },
            U: function (date) { return weekOfYear(date, 0); },
            W: function (date) { return weekOfYear(date, 1); },
            V: function (date) { return isoWeek(date)[0]; },
            G: function (date) { return isoWeek(date)[1]; },
            g: function (date) { return isoWeek(date)[1] % 100; },
            j: function (date) { return Math.floor((date.getTime() - Date.UTC(date.getUTCFullYear(), 0)) / 864e5) + 1; },
            s: function (date) { return Math.floor(date.getTime() / 1000); },
            C: function (date) { return Math.floor(date.getUTCFullYear() / 100); },
            N: function (date) { return date.getTime() % 1000 * 1000000; },
            m: function (date) { return date.getUTCMonth() + 1; },
            Y: function (date) { return date.getUTCFullYear(); },
            y: function (date) { return date.getUTCFullYear() % 100; },
            H: function (date) { return date.getUTCHours(); },
            M: function (date) { return date.getUTCMinutes(); },
            S: function (date) { return date.getUTCSeconds(); },
            e: function (date) { return date.getUTCDate(); },
            d: function (date) { return date.getUTCDate(); },
            u: function (date) { return date.getUTCDay() || 7; },
            w: function (date) { return date.getUTCDay(); },
            l: function (date) { return date.getUTCHours() % 12 || 12; },
            I: function (date) { return date.getUTCHours() % 12 || 12; },
            k: function (date) { return date.getUTCHours(); },
            Z: function (date) { return this.entry.abbrev; },
            a: function (date) { return this[this.locale].day.abbrev[date.getUTCDay()]; },
            A: function (date) { return this[this.locale].day.full[date.getUTCDay()]; },
            h: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()]; },
            b: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()]; },
            B: function (date) { return this[this.locale].month.full[date.getUTCMonth()]; },
            P: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)].toLowerCase(); },
            p: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)]; },
            R: function (date, posix) { return this.convert([posix, "%H:%M"]); },
            T: function (date, posix) { return this.convert([posix, "%H:%M:%S"]); },
            D: function (date, posix) { return this.convert([posix, "%m/%d/%y"]); },
            F: function (date, posix) { return this.convert([posix, "%Y-%m-%d"]); },
            x: function (date, posix) { return this.convert([posix, this[this.locale].date]); },
            r: function (date, posix) { return this.convert([posix, this[this.locale].time12 || '%I:%M:%S']); },
            X: function (date, posix) { return this.convert([posix, this[this.locale].time24]); },
            c: function (date, posix) { return this.convert([posix, this[this.locale].dateTime]); },
            convert: convert,
            locale: "en_US",
            en_US: {
                date: "%m/%d/%Y",
                time24: "%I:%M:%S %p",
                time12: "%I:%M:%S %p",
                dateTime: "%a %d %b %Y %I:%M:%S %p %Z",
                meridiem: ["AM", "PM"],
                month: {
                    abbrev: "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|"),
                    full: "January|February|March|April|May|June|July|August|September|October|November|December".split("|")
                },
                day: {
                    abbrev: "Sun|Mon|Tue|Wed|Thu|Fri|Sat".split("|"),
                    full: "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|")
                }
            }
        };
        var UNITS = "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|year|month|day|hour|minute|second|millisecond", UNIT_RE = new RegExp("^\\s*([+-])(\\d+)\\s+(" + UNITS + ")s?\\s*$", "i"), TIME = [36e5, 6e4, 1e3, 1];
        UNITS = UNITS.toLowerCase().split("|");
        "delmHMSUWVgCIky".replace(/./g, function (e) { context[e].pad = 2; });
        context.N.pad = 9;
        context.j.pad = 3;
        context.k.style = "_";
        context.l.style = "_";
        context.e.style = "_";
        function weekOfYear(date, startOfWeek) {
            var diff, nyd, weekStart;
            nyd = new Date(Date.UTC(date.getUTCFullYear(), 0));
            diff = Math.floor((date.getTime() - nyd.getTime()) / 864e5);
            if (nyd.getUTCDay() == startOfWeek) {
                weekStart = 0;
            }
            else {
                weekStart = 7 - nyd.getUTCDay() + startOfWeek;
                if (weekStart == 8) {
                    weekStart = 1;
                }
            }
            return diff >= weekStart ? Math.floor((diff - weekStart) / 7) + 1 : 0;
        }
        function isoWeek(date) {
            var nyd, nyy, week;
            nyy = date.getUTCFullYear();
            nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
            week = weekOfYear(date, 1) + (nyd > 1 && nyd <= 4 ? 1 : 0);
            if (!week) {
                nyy = date.getUTCFullYear() - 1;
                nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
                week = nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29) ? 53 : 52;
                return [week, date.getUTCFullYear() - 1];
            }
            else if (week == 53 && !(nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29))) {
                return [1, date.getUTCFullYear() + 1];
            }
            else {
                return [week, date.getUTCFullYear()];
            }
        }
        return function () { return context.convert(arguments); };
    });
},
/* core/util/templating.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var Numbro = (0, tslib_1.__importStar)(require(268) /* @bokeh/numbro */);
    var sprintf_js_1 = require(269) /* sprintf-js */;
    var timezone_1 = (0, tslib_1.__importDefault)(require(266) /* timezone */);
    var kinds_1 = require(136) /* ../kinds */;
    var types_1 = require(125) /* ./types */;
    exports.FormatterType = (0, kinds_1.Enum)("numeral", "printf", "datetime");
    exports.DEFAULT_FORMATTERS = {
        numeral: function (value, format, _special_vars) { return Numbro.format(value, format); },
        datetime: function (value, format, _special_vars) { return (0, timezone_1.default)(value, format); },
        printf: function (value, format, _special_vars) { return sprintf(format, value); },
    };
    function sprintf(format) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        return sprintf_js_1.sprintf.apply(void 0, (0, tslib_1.__spreadArray)([format], (0, tslib_1.__read)(args), false));
    }
    exports.sprintf = sprintf;
    function basic_formatter(value, _format, _special_vars) {
        if ((0, types_1.isNumber)(value)) {
            var format = (function () {
                switch (false) {
                    case Math.floor(value) != value:
                        return "%d";
                    case !(Math.abs(value) > 0.1) || !(Math.abs(value) < 1000):
                        return "%0.3f";
                    default:
                        return "%0.3e";
                }
            })();
            return sprintf(format, value);
        }
        else
            return "" + value; // get strings for categorical types
    }
    exports.basic_formatter = basic_formatter;
    function get_formatter(raw_spec, format, formatters) {
        // no format, use default built in formatter
        if (format == null)
            return basic_formatter;
        // format spec in the formatters dict, use that
        if (formatters != null && raw_spec in formatters) {
            var formatter_1 = formatters[raw_spec];
            if ((0, types_1.isString)(formatter_1)) {
                if (formatter_1 in exports.DEFAULT_FORMATTERS)
                    return exports.DEFAULT_FORMATTERS[formatter_1];
                else
                    throw new Error("Unknown tooltip field formatter type '" + formatter_1 + "'");
            }
            return function (value, format, special_vars) {
                return formatter_1.format(value, format, special_vars);
            };
        }
        // otherwise use "numeral" as default
        return exports.DEFAULT_FORMATTERS.numeral;
    }
    exports.get_formatter = get_formatter;
    function _get_special_value(name, special_vars) {
        if (name in special_vars)
            return special_vars[name];
        else
            throw new Error("Unknown special variable '$" + name + "'");
    }
    function _get_column_value(name, data_source, i) {
        var column = data_source.get_column(name);
        // missing column
        if (column == null)
            return null;
        // typical (non-image) index
        if ((0, types_1.isNumber)(i))
            return column[i];
        // image index
        var data = column[i.index];
        if ((0, types_1.isTypedArray)(data) || (0, types_1.isArray)(data)) {
            // inspect array of arrays
            if ((0, types_1.isArray)(data[0])) {
                var row = data[i.dim2];
                return row[i.dim1];
            }
            else
                return data[i.flat_index]; // inspect flat array
        }
        else
            return data; // inspect per-image scalar data
    }
    exports._get_column_value = _get_column_value;
    function get_value(raw_name, data_source, i, special_vars) {
        if (raw_name[0] == "$") {
            var name = raw_name.substring(1);
            return _get_special_value(name, special_vars);
        }
        else {
            var name = raw_name.substring(1).replace(/[{}]/g, "");
            return _get_column_value(name, data_source, i);
        }
    }
    exports.get_value = get_value;
    function replace_placeholders(content, data_source, i, formatters, special_vars, encode) {
        if (special_vars === void 0) {
            special_vars = {};
        }
        var str;
        var has_html;
        if ((0, types_1.isString)(content)) {
            str = content;
            has_html = false;
        }
        else {
            str = content.html;
            has_html = true;
        }
        // this handles the special case @$name, replacing it with an @var corresponding to special_vars.name
        str = str.replace(/@\$name/g, function (_match) { return "@{" + special_vars.name + "}"; });
        //
        // (?:\$\w+) - special vars: $x
        // (?:@\w+) - simple names: @foo
        // (?:@{(?:[^{}]+)})) - full names: @{one two}
        //
        // (?:{([^{}]+)})? - (optional) format for all of the above: @foo{fmt}
        //
        str = str.replace(/((?:\$\w+)|(?:@\w+)|(?:@{(?:[^{}]+)}))(?:{([^{}]+)})?/g, function (_match, spec, format) {
            var value = get_value(spec, data_source, i, special_vars);
            // missing value, return ???
            if (value == null)
                return encode ? encode("???") : "???";
            // 'safe' format, return the value as-is
            if (format == "safe") {
                has_html = true;
                return "" + value;
            }
            // format and escape everything else
            var formatter = get_formatter(spec, format, formatters);
            var result = "" + formatter(value, format, special_vars);
            return encode ? encode(result) : result;
        });
        if (!has_html)
            return str;
        else {
            var parser = new DOMParser();
            var document = parser.parseFromString(str, "text/html");
            return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(document.body.childNodes), false);
        }
    }
    exports.replace_placeholders = replace_placeholders;
},
/* @bokeh/numbro/numbro.js */ function _(require, module, exports, __esModule, __esExport) {
    /*!
     * numbro.js
     * version : 1.6.2
     * author : Företagsplatsen AB
     * license : MIT
     * http://www.foretagsplatsen.se
     */
    /************************************
        Constants
    ************************************/
    var numbro, VERSION = '1.6.2', 
    // internal storage for culture config files
    cultures = {}, 
    // Todo: Remove in 2.0.0
    languages = cultures, currentCulture = 'en-US', zeroFormat = null, defaultFormat = '0,0', defaultCurrencyFormat = '0$', 
    // check for nodeJS
    hasModule = (typeof module !== 'undefined' && module.exports), 
    // default culture
    enUS = {
        delimiters: {
            thousands: ',',
            decimal: '.'
        },
        abbreviations: {
            thousand: 'k',
            million: 'm',
            billion: 'b',
            trillion: 't'
        },
        ordinal: function (number) {
            var b = number % 10;
            return (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                    (b === 2) ? 'nd' :
                        (b === 3) ? 'rd' : 'th';
        },
        currency: {
            symbol: '$',
            position: 'prefix'
        },
        defaults: {
            currencyFormat: ',0000 a'
        },
        formats: {
            fourDigits: '0000 a',
            fullWithTwoDecimals: '$ ,0.00',
            fullWithTwoDecimalsNoCurrency: ',0.00'
        }
    };
    /************************************
        Constructors
    ************************************/
    // Numbro prototype object
    function Numbro(number) {
        this._value = number;
    }
    function zeroes(count) {
        var i, ret = '';
        for (i = 0; i < count; i++) {
            ret += '0';
        }
        return ret;
    }
    /**
     * Implementation of toFixed() for numbers with exponent > 21
     *
     *
     */
    function toFixedLarge(value, precision) {
        var mantissa, beforeDec, afterDec, exponent, str;
        str = value.toString();
        mantissa = str.split('e')[0];
        exponent = str.split('e')[1];
        beforeDec = mantissa.split('.')[0];
        afterDec = mantissa.split('.')[1] || '';
        str = beforeDec + afterDec + zeroes(exponent - afterDec.length);
        if (precision > 0) {
            str += '.' + zeroes(precision);
        }
        return str;
    }
    /**
     * Implementation of toFixed() that treats floats more like decimals
     *
     * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
     * problems for accounting- and finance-related software.
     */
    function toFixed(value, precision, roundingFunction, optionals) {
        var power = Math.pow(10, precision), optionalsRegExp, output;
        if (value.toFixed(0).search('e') > -1) {
            // Above 1e21, toFixed returns scientific notation, which
            // is useless and unexpected
            output = toFixedLarge(value, precision);
        }
        else {
            //roundingFunction = (roundingFunction !== undefined ? roundingFunction : Math.round);
            // Multiply up by precision, round accurately, then divide and use native toFixed():
            output = (roundingFunction(value * power) / power).toFixed(precision);
        }
        if (optionals) {
            optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
            output = output.replace(optionalsRegExp, '');
        }
        return output;
    }
    /************************************
        Formatting
    ************************************/
    // determine what type of formatting we need to do
    function formatNumbro(value, format, roundingFunction) {
        var output;
        // TODO: do something with `language`
        // figure out what kind of format we are dealing with
        if (format.indexOf('$') > -1) { // currency!!!!!
            output = formatCurrency(value, format, roundingFunction);
        }
        else if (format.indexOf('%') > -1) { // percentage
            output = formatPercentage(value, format, roundingFunction);
        }
        else if (format.indexOf(':') > -1) { // time
            output = formatTime(value);
        }
        else { // plain ol' numbers or bytes
            output = formatNumber(value, format, roundingFunction);
        }
        // return string
        return output;
    }
    function formatCurrency(value, originalFormat, roundingFunction) {
        var format = originalFormat, symbolIndex = format.indexOf('$'), openParenIndex = format.indexOf('('), plusSignIndex = format.indexOf('+'), minusSignIndex = format.indexOf('-'), space = '', decimalSeparator = '', spliceIndex, output;
        if (format.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            if (cultures[currentCulture].currency.position === 'infix') {
                decimalSeparator = cultures[currentCulture].currency.symbol;
                if (cultures[currentCulture].currency.spaceSeparated) {
                    decimalSeparator = ' ' + decimalSeparator + ' ';
                }
            }
            else if (cultures[currentCulture].currency.spaceSeparated) {
                space = ' ';
            }
        }
        else {
            // check for space before or after currency
            if (format.indexOf(' $') > -1) {
                space = ' ';
                format = format.replace(' $', '');
            }
            else if (format.indexOf('$ ') > -1) {
                space = ' ';
                format = format.replace('$ ', '');
            }
            else {
                format = format.replace('$', '');
            }
        }
        // Format The Number
        output = formatNumber(value, format, roundingFunction, decimalSeparator);
        if (originalFormat.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            switch (cultures[currentCulture].currency.position) {
                case 'postfix':
                    if (output.indexOf(')') > -1) {
                        output = output.split('');
                        output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                        output = output.join('');
                    }
                    else {
                        output = output + space + cultures[currentCulture].currency.symbol;
                    }
                    break;
                case 'infix':
                    break;
                case 'prefix':
                    if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
                        output = output.split('');
                        spliceIndex = Math.max(openParenIndex, minusSignIndex) + 1;
                        output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                        output = output.join('');
                    }
                    else {
                        output = cultures[currentCulture].currency.symbol + space + output;
                    }
                    break;
                default:
                    throw Error('Currency position should be among ["prefix", "infix", "postfix"]');
            }
        }
        else {
            // position the symbol
            if (symbolIndex <= 1) {
                if (output.indexOf('(') > -1 || output.indexOf('+') > -1 || output.indexOf('-') > -1) {
                    output = output.split('');
                    spliceIndex = 1;
                    if (symbolIndex < openParenIndex || symbolIndex < plusSignIndex || symbolIndex < minusSignIndex) {
                        // the symbol appears before the "(", "+" or "-"
                        spliceIndex = 0;
                    }
                    output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                    output = output.join('');
                }
                else {
                    output = cultures[currentCulture].currency.symbol + space + output;
                }
            }
            else {
                if (output.indexOf(')') > -1) {
                    output = output.split('');
                    output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                    output = output.join('');
                }
                else {
                    output = output + space + cultures[currentCulture].currency.symbol;
                }
            }
        }
        return output;
    }
    function formatPercentage(value, format, roundingFunction) {
        var space = '', output;
        value = value * 100;
        // check for space before %
        if (format.indexOf(' %') > -1) {
            space = ' ';
            format = format.replace(' %', '');
        }
        else {
            format = format.replace('%', '');
        }
        output = formatNumber(value, format, roundingFunction);
        if (output.indexOf(')') > -1) {
            output = output.split('');
            output.splice(-1, 0, space + '%');
            output = output.join('');
        }
        else {
            output = output + space + '%';
        }
        return output;
    }
    function formatTime(value) {
        var hours = Math.floor(value / 60 / 60), minutes = Math.floor((value - (hours * 60 * 60)) / 60), seconds = Math.round(value - (hours * 60 * 60) - (minutes * 60));
        return hours + ':' +
            ((minutes < 10) ? '0' + minutes : minutes) + ':' +
            ((seconds < 10) ? '0' + seconds : seconds);
    }
    function formatNumber(value, format, roundingFunction, sep) {
        var negP = false, signed = false, optDec = false, abbr = '', i, abbrK = false, // force abbreviation to thousands
        abbrM = false, // force abbreviation to millions
        abbrB = false, // force abbreviation to billions
        abbrT = false, // force abbreviation to trillions
        abbrForce = false, // force abbreviation
        bytes = '', ord = '', abs = Math.abs(value), binarySuffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'], decimalSuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max, power, totalLength, length, minimumPrecision, pow, w, intPrecision, precision, prefix, postfix, thousands, d = '', forcedNeg = false, neg = false, indexOpenP, size, indexMinus, paren = '', minlen;
        // check if number is zero and a custom zero format has been set
        if (value === 0 && zeroFormat !== null) {
            return zeroFormat;
        }
        if (!isFinite(value)) {
            return '' + value;
        }
        if (format.indexOf('{') === 0) {
            var end = format.indexOf('}');
            if (end === -1) {
                throw Error('Format should also contain a "}"');
            }
            prefix = format.slice(1, end);
            format = format.slice(end + 1);
        }
        else {
            prefix = '';
        }
        if (format.indexOf('}') === format.length - 1) {
            var start = format.indexOf('{');
            if (start === -1) {
                throw Error('Format should also contain a "{"');
            }
            postfix = format.slice(start + 1, -1);
            format = format.slice(0, start + 1);
        }
        else {
            postfix = '';
        }
        // check for min length
        var info;
        if (format.indexOf('.') === -1) {
            info = format.match(/([0-9]+).*/);
        }
        else {
            info = format.match(/([0-9]+)\..*/);
        }
        minlen = info === null ? -1 : info[1].length;
        // see if we should use parentheses for negative number or if we should prefix with a sign
        // if both are present we default to parentheses
        if (format.indexOf('-') !== -1) {
            forcedNeg = true;
        }
        if (format.indexOf('(') > -1) {
            negP = true;
            format = format.slice(1, -1);
        }
        else if (format.indexOf('+') > -1) {
            signed = true;
            format = format.replace(/\+/g, '');
        }
        // see if abbreviation is wanted
        if (format.indexOf('a') > -1) {
            intPrecision = format.split('.')[0].match(/[0-9]+/g) || ['0'];
            intPrecision = parseInt(intPrecision[0], 10);
            // check if abbreviation is specified
            abbrK = format.indexOf('aK') >= 0;
            abbrM = format.indexOf('aM') >= 0;
            abbrB = format.indexOf('aB') >= 0;
            abbrT = format.indexOf('aT') >= 0;
            abbrForce = abbrK || abbrM || abbrB || abbrT;
            // check for space before abbreviation
            if (format.indexOf(' a') > -1) {
                abbr = ' ';
                format = format.replace(' a', '');
            }
            else {
                format = format.replace('a', '');
            }
            totalLength = Math.floor(Math.log(abs) / Math.LN10) + 1;
            minimumPrecision = totalLength % 3;
            minimumPrecision = minimumPrecision === 0 ? 3 : minimumPrecision;
            if (intPrecision && abs !== 0) {
                length = Math.floor(Math.log(abs) / Math.LN10) + 1 - intPrecision;
                pow = 3 * ~~((Math.min(intPrecision, totalLength) - minimumPrecision) / 3);
                abs = abs / Math.pow(10, pow);
                if (format.indexOf('.') === -1 && intPrecision > 3) {
                    format += '[.]';
                    size = length === 0 ? 0 : 3 * ~~(length / 3) - length;
                    size = size < 0 ? size + 3 : size;
                    for (i = 0; i < size; i++) {
                        format += '0';
                    }
                }
            }
            if (Math.floor(Math.log(Math.abs(value)) / Math.LN10) + 1 !== intPrecision) {
                if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
                    // trillion
                    abbr = abbr + cultures[currentCulture].abbreviations.trillion;
                    value = value / Math.pow(10, 12);
                }
                else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
                    // billion
                    abbr = abbr + cultures[currentCulture].abbreviations.billion;
                    value = value / Math.pow(10, 9);
                }
                else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
                    // million
                    abbr = abbr + cultures[currentCulture].abbreviations.million;
                    value = value / Math.pow(10, 6);
                }
                else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
                    // thousand
                    abbr = abbr + cultures[currentCulture].abbreviations.thousand;
                    value = value / Math.pow(10, 3);
                }
            }
        }
        // see if we are formatting binary bytes
        if (format.indexOf('b') > -1) {
            // check for space before
            if (format.indexOf(' b') > -1) {
                bytes = ' ';
                format = format.replace(' b', '');
            }
            else {
                format = format.replace('b', '');
            }
            for (power = 0; power <= binarySuffixes.length; power++) {
                min = Math.pow(1024, power);
                max = Math.pow(1024, power + 1);
                if (value >= min && value < max) {
                    bytes = bytes + binarySuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }
        // see if we are formatting decimal bytes
        if (format.indexOf('d') > -1) {
            // check for space before
            if (format.indexOf(' d') > -1) {
                bytes = ' ';
                format = format.replace(' d', '');
            }
            else {
                format = format.replace('d', '');
            }
            for (power = 0; power <= decimalSuffixes.length; power++) {
                min = Math.pow(1000, power);
                max = Math.pow(1000, power + 1);
                if (value >= min && value < max) {
                    bytes = bytes + decimalSuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }
        // see if ordinal is wanted
        if (format.indexOf('o') > -1) {
            // check for space before
            if (format.indexOf(' o') > -1) {
                ord = ' ';
                format = format.replace(' o', '');
            }
            else {
                format = format.replace('o', '');
            }
            if (cultures[currentCulture].ordinal) {
                ord = ord + cultures[currentCulture].ordinal(value);
            }
        }
        if (format.indexOf('[.]') > -1) {
            optDec = true;
            format = format.replace('[.]', '.');
        }
        w = value.toString().split('.')[0];
        precision = format.split('.')[1];
        thousands = format.indexOf(',');
        if (precision) {
            if (precision.indexOf('*') !== -1) {
                d = toFixed(value, value.toString().split('.')[1].length, roundingFunction);
            }
            else {
                if (precision.indexOf('[') > -1) {
                    precision = precision.replace(']', '');
                    precision = precision.split('[');
                    d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length);
                }
                else {
                    d = toFixed(value, precision.length, roundingFunction);
                }
            }
            w = d.split('.')[0];
            if (d.split('.')[1].length) {
                var p = sep ? abbr + sep : cultures[currentCulture].delimiters.decimal;
                d = p + d.split('.')[1];
            }
            else {
                d = '';
            }
            if (optDec && Number(d.slice(1)) === 0) {
                d = '';
            }
        }
        else {
            w = toFixed(value, null, roundingFunction);
        }
        // format number
        if (w.indexOf('-') > -1) {
            w = w.slice(1);
            neg = true;
        }
        if (w.length < minlen) {
            w = new Array(minlen - w.length + 1).join('0') + w;
        }
        if (thousands > -1) {
            w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' +
                cultures[currentCulture].delimiters.thousands);
        }
        if (format.indexOf('.') === 0) {
            w = '';
        }
        indexOpenP = format.indexOf('(');
        indexMinus = format.indexOf('-');
        if (indexOpenP < indexMinus) {
            paren = ((negP && neg) ? '(' : '') + (((forcedNeg && neg) || (!negP && neg)) ? '-' : '');
        }
        else {
            paren = (((forcedNeg && neg) || (!negP && neg)) ? '-' : '') + ((negP && neg) ? '(' : '');
        }
        return prefix +
            paren + ((!neg && signed && value !== 0) ? '+' : '') +
            w + d +
            ((ord) ? ord : '') +
            ((abbr && !sep) ? abbr : '') +
            ((bytes) ? bytes : '') +
            ((negP && neg) ? ')' : '') +
            postfix;
    }
    /************************************
        Top Level Functions
    ************************************/
    numbro = function (input) {
        if (numbro.isNumbro(input)) {
            input = input.value();
        }
        else if (input === 0 || typeof input === 'undefined') {
            input = 0;
        }
        else if (!Number(input)) {
            input = numbro.fn.unformat(input);
        }
        return new Numbro(Number(input));
    };
    // version number
    numbro.version = VERSION;
    // compare numbro object
    numbro.isNumbro = function (obj) {
        return obj instanceof Numbro;
    };
    /**
     * This function allow the user to set a new language with a fallback if
     * the language does not exist. If no fallback language is provided,
     * it fallbacks to english.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `setCulture` should be used instead.
     */
    numbro.setLanguage = function (newLanguage, fallbackLanguage) {
        console.warn('`setLanguage` is deprecated since version 1.6.0. Use `setCulture` instead');
        var key = newLanguage, prefix = newLanguage.split('-')[0], matchingLanguage = null;
        if (!languages[key]) {
            Object.keys(languages).forEach(function (language) {
                if (!matchingLanguage && language.split('-')[0] === prefix) {
                    matchingLanguage = language;
                }
            });
            key = matchingLanguage || fallbackLanguage || 'en-US';
        }
        chooseCulture(key);
    };
    /**
     * This function allow the user to set a new culture with a fallback if
     * the culture does not exist. If no fallback culture is provided,
     * it fallbacks to "en-US".
     */
    numbro.setCulture = function (newCulture, fallbackCulture) {
        var key = newCulture, suffix = newCulture.split('-')[1], matchingCulture = null;
        if (!cultures[key]) {
            if (suffix) {
                Object.keys(cultures).forEach(function (language) {
                    if (!matchingCulture && language.split('-')[1] === suffix) {
                        matchingCulture = language;
                    }
                });
            }
            key = matchingCulture || fallbackCulture || 'en-US';
        }
        chooseCulture(key);
    };
    /**
     * This function will load languages and then set the global language.  If
     * no arguments are passed in, it will simply return the current global
     * language key.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.language = function (key, values) {
        console.warn('`language` is deprecated since version 1.6.0. Use `culture` instead');
        if (!key) {
            return currentCulture;
        }
        if (key && !values) {
            if (!languages[key]) {
                throw new Error('Unknown language : ' + key);
            }
            chooseCulture(key);
        }
        if (values || !languages[key]) {
            setCulture(key, values);
        }
        return numbro;
    };
    /**
     * This function will load cultures and then set the global culture.  If
     * no arguments are passed in, it will simply return the current global
     * culture code.
     */
    numbro.culture = function (code, values) {
        if (!code) {
            return currentCulture;
        }
        if (code && !values) {
            if (!cultures[code]) {
                throw new Error('Unknown culture : ' + code);
            }
            chooseCulture(code);
        }
        if (values || !cultures[code]) {
            setCulture(code, values);
        }
        return numbro;
    };
    /**
     * This function provides access to the loaded language data.  If
     * no arguments are passed in, it will simply return the current
     * global language object.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.languageData = function (key) {
        console.warn('`languageData` is deprecated since version 1.6.0. Use `cultureData` instead');
        if (!key) {
            return languages[currentCulture];
        }
        if (!languages[key]) {
            throw new Error('Unknown language : ' + key);
        }
        return languages[key];
    };
    /**
     * This function provides access to the loaded culture data.  If
     * no arguments are passed in, it will simply return the current
     * global culture object.
     */
    numbro.cultureData = function (code) {
        if (!code) {
            return cultures[currentCulture];
        }
        if (!cultures[code]) {
            throw new Error('Unknown culture : ' + code);
        }
        return cultures[code];
    };
    numbro.culture('en-US', enUS);
    /**
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `cultures` should be used instead.
     */
    numbro.languages = function () {
        console.warn('`languages` is deprecated since version 1.6.0. Use `cultures` instead');
        return languages;
    };
    numbro.cultures = function () {
        return cultures;
    };
    numbro.zeroFormat = function (format) {
        zeroFormat = typeof (format) === 'string' ? format : null;
    };
    numbro.defaultFormat = function (format) {
        defaultFormat = typeof (format) === 'string' ? format : '0.0';
    };
    numbro.defaultCurrencyFormat = function (format) {
        defaultCurrencyFormat = typeof (format) === 'string' ? format : '0$';
    };
    numbro.validate = function (val, culture) {
        var _decimalSep, _thousandSep, _currSymbol, _valArray, _abbrObj, _thousandRegEx, cultureData, temp;
        //coerce val to string
        if (typeof val !== 'string') {
            val += '';
            if (console.warn) {
                console.warn('Numbro.js: Value is not string. It has been co-erced to: ', val);
            }
        }
        //trim whitespaces from either sides
        val = val.trim();
        //if val is just digits return true
        if (!!val.match(/^\d+$/)) {
            return true;
        }
        //if val is empty return false
        if (val === '') {
            return false;
        }
        //get the decimal and thousands separator from numbro.cultureData
        try {
            //check if the culture is understood by numbro. if not, default it to current culture
            cultureData = numbro.cultureData(culture);
        }
        catch (e) {
            cultureData = numbro.cultureData(numbro.culture());
        }
        //setup the delimiters and currency symbol based on culture
        _currSymbol = cultureData.currency.symbol;
        _abbrObj = cultureData.abbreviations;
        _decimalSep = cultureData.delimiters.decimal;
        if (cultureData.delimiters.thousands === '.') {
            _thousandSep = '\\.';
        }
        else {
            _thousandSep = cultureData.delimiters.thousands;
        }
        // validating currency symbol
        temp = val.match(/^[^\d]+/);
        if (temp !== null) {
            val = val.substr(1);
            if (temp[0] !== _currSymbol) {
                return false;
            }
        }
        //validating abbreviation symbol
        temp = val.match(/[^\d]+$/);
        if (temp !== null) {
            val = val.slice(0, -1);
            if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million &&
                temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
                return false;
            }
        }
        _thousandRegEx = new RegExp(_thousandSep + '{2}');
        if (!val.match(/[^\d.,]/g)) {
            _valArray = val.split(_decimalSep);
            if (_valArray.length > 2) {
                return false;
            }
            else {
                if (_valArray.length < 2) {
                    return (!!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
                }
                else {
                    if (_valArray[0].length === 1) {
                        return (!!_valArray[0].match(/^\d+$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));
                    }
                    else {
                        return (!!_valArray[0].match(/^\d+.*\d$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));
                    }
                }
            }
        }
        return false;
    };
    /************************************
        Helpers
    ************************************/
    function setCulture(code, values) {
        cultures[code] = values;
    }
    function chooseCulture(code) {
        currentCulture = code;
        var defaults = cultures[code].defaults;
        if (defaults && defaults.format) {
            numbro.defaultFormat(defaults.format);
        }
        if (defaults && defaults.currencyFormat) {
            numbro.defaultCurrencyFormat(defaults.currencyFormat);
        }
    }
    function format(input, formatString, language, roundingFunction) {
        if (language != null && language !== numbro.culture()) {
            numbro.setCulture(language);
        }
        return formatNumbro(Number(input), formatString != null ? formatString : defaultFormat, roundingFunction == null ? Math.round : roundingFunction);
    }
    module.exports = { "format": format };
},
/* sprintf-js/src/sprintf.js */ function _(require, module, exports, __esModule, __esExport) {
    /* global window, exports, define */
    !function () {
        'use strict';
        var re = {
            not_string: /[^s]/,
            not_bool: /[^t]/,
            not_type: /[^T]/,
            not_primitive: /[^v]/,
            number: /[diefg]/,
            numeric_arg: /[bcdiefguxX]/,
            json: /[j]/,
            not_json: /[^j]/,
            text: /^[^\x25]+/,
            modulo: /^\x25{2}/,
            placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
            key: /^([a-z_][a-z_\d]*)/i,
            key_access: /^\.([a-z_][a-z_\d]*)/i,
            index_access: /^\[(\d+)\]/,
            sign: /^[+-]/
        };
        function sprintf(key) {
            // `arguments` is not an array, but should be fine for this call
            return sprintf_format(sprintf_parse(key), arguments);
        }
        function vsprintf(fmt, argv) {
            return sprintf.apply(null, [fmt].concat(argv || []));
        }
        function sprintf_format(parse_tree, argv) {
            var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign;
            for (i = 0; i < tree_length; i++) {
                if (typeof parse_tree[i] === 'string') {
                    output += parse_tree[i];
                }
                else if (typeof parse_tree[i] === 'object') {
                    ph = parse_tree[i]; // convenience purposes only
                    if (ph.keys) { // keyword argument
                        arg = argv[cursor];
                        for (k = 0; k < ph.keys.length; k++) {
                            if (arg == undefined) {
                                throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
                            }
                            arg = arg[ph.keys[k]];
                        }
                    }
                    else if (ph.param_no) { // positional argument (explicit)
                        arg = argv[ph.param_no];
                    }
                    else { // positional argument (implicit)
                        arg = argv[cursor++];
                    }
                    if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                        arg = arg();
                    }
                    if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                        throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg));
                    }
                    if (re.number.test(ph.type)) {
                        is_positive = arg >= 0;
                    }
                    switch (ph.type) {
                        case 'b':
                            arg = parseInt(arg, 10).toString(2);
                            break;
                        case 'c':
                            arg = String.fromCharCode(parseInt(arg, 10));
                            break;
                        case 'd':
                        case 'i':
                            arg = parseInt(arg, 10);
                            break;
                        case 'j':
                            arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
                            break;
                        case 'e':
                            arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
                            break;
                        case 'f':
                            arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
                            break;
                        case 'g':
                            arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
                            break;
                        case 'o':
                            arg = (parseInt(arg, 10) >>> 0).toString(8);
                            break;
                        case 's':
                            arg = String(arg);
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 't':
                            arg = String(!!arg);
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'T':
                            arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'u':
                            arg = parseInt(arg, 10) >>> 0;
                            break;
                        case 'v':
                            arg = arg.valueOf();
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'x':
                            arg = (parseInt(arg, 10) >>> 0).toString(16);
                            break;
                        case 'X':
                            arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
                            break;
                    }
                    if (re.json.test(ph.type)) {
                        output += arg;
                    }
                    else {
                        if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                            sign = is_positive ? '+' : '-';
                            arg = arg.toString().replace(re.sign, '');
                        }
                        else {
                            sign = '';
                        }
                        pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
                        pad_length = ph.width - (sign + arg).length;
                        pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '';
                        output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg);
                    }
                }
            }
            return output;
        }
        var sprintf_cache = Object.create(null);
        function sprintf_parse(fmt) {
            if (sprintf_cache[fmt]) {
                return sprintf_cache[fmt];
            }
            var _fmt = fmt, match, parse_tree = [], arg_names = 0;
            while (_fmt) {
                if ((match = re.text.exec(_fmt)) !== null) {
                    parse_tree.push(match[0]);
                }
                else if ((match = re.modulo.exec(_fmt)) !== null) {
                    parse_tree.push('%');
                }
                else if ((match = re.placeholder.exec(_fmt)) !== null) {
                    if (match[2]) {
                        arg_names |= 1;
                        var field_list = [], replacement_field = match[2], field_match = [];
                        if ((field_match = re.key.exec(replacement_field)) !== null) {
                            field_list.push(field_match[1]);
                            while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                                if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                    field_list.push(field_match[1]);
                                }
                                else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                    field_list.push(field_match[1]);
                                }
                                else {
                                    throw new SyntaxError('[sprintf] failed to parse named argument key');
                                }
                            }
                        }
                        else {
                            throw new SyntaxError('[sprintf] failed to parse named argument key');
                        }
                        match[2] = field_list;
                    }
                    else {
                        arg_names |= 2;
                    }
                    if (arg_names === 3) {
                        throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
                    }
                    parse_tree.push({
                        placeholder: match[0],
                        param_no: match[1],
                        keys: match[2],
                        sign: match[3],
                        pad_char: match[4],
                        align: match[5],
                        width: match[6],
                        precision: match[7],
                        type: match[8]
                    });
                }
                else {
                    throw new SyntaxError('[sprintf] unexpected placeholder');
                }
                _fmt = _fmt.substring(match[0].length);
            }
            return sprintf_cache[fmt] = parse_tree;
        }
        /**
         * export to either browser or node.js
         */
        /* eslint-disable quote-props */
        if (typeof exports !== 'undefined') {
            exports['sprintf'] = sprintf;
            exports['vsprintf'] = vsprintf;
        }
        if (typeof window !== 'undefined') {
            window['sprintf'] = sprintf;
            window['vsprintf'] = vsprintf;
            if (typeof define === 'function' && define['amd']) {
                define(function () {
                    return {
                        'sprintf': sprintf,
                        'vsprintf': vsprintf
                    };
                });
            }
        }
        /* eslint-enable quote-props */
    }(); // eslint-disable-line
},
/* models/tickers/datetime_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var array_1 = require(126) /* ../../core/util/array */;
    var adaptive_ticker_1 = require(263) /* ./adaptive_ticker */;
    var composite_ticker_1 = require(271) /* ./composite_ticker */;
    var days_ticker_1 = require(272) /* ./days_ticker */;
    var months_ticker_1 = require(275) /* ./months_ticker */;
    var years_ticker_1 = require(276) /* ./years_ticker */;
    var util_1 = require(274) /* ./util */;
    var DatetimeTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DatetimeTicker, _super);
        function DatetimeTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        return DatetimeTicker;
    }(composite_ticker_1.CompositeTicker));
    exports.DatetimeTicker = DatetimeTicker;
    _a = DatetimeTicker;
    DatetimeTicker.__name__ = "DatetimeTicker";
    (function () {
        _a.override({
            num_minor_ticks: 0,
            tickers: function () {
                return [
                    // Sub-second.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 5],
                        base: 10,
                        min_interval: 0,
                        max_interval: 500 * util_1.ONE_MILLI,
                        num_minor_ticks: 0,
                    }),
                    // Seconds, minutes.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 5, 10, 15, 20, 30],
                        base: 60,
                        min_interval: util_1.ONE_SECOND,
                        max_interval: 30 * util_1.ONE_MINUTE,
                        num_minor_ticks: 0,
                    }),
                    // Hours.
                    new adaptive_ticker_1.AdaptiveTicker({
                        mantissas: [1, 2, 4, 6, 8, 12],
                        base: 24.0,
                        min_interval: util_1.ONE_HOUR,
                        max_interval: 12 * util_1.ONE_HOUR,
                        num_minor_ticks: 0,
                    }),
                    // Days.
                    new days_ticker_1.DaysTicker({ days: (0, array_1.range)(1, 32) }),
                    new days_ticker_1.DaysTicker({ days: (0, array_1.range)(1, 31, 3) }),
                    new days_ticker_1.DaysTicker({ days: [1, 8, 15, 22] }),
                    new days_ticker_1.DaysTicker({ days: [1, 15] }),
                    // Months.
                    new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 1) }),
                    new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 2) }),
                    new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 4) }),
                    new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 6) }),
                    // Years
                    new years_ticker_1.YearsTicker({}),
                ];
            },
        });
    })();
},
/* models/tickers/composite_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var continuous_ticker_1 = require(264) /* ./continuous_ticker */;
    var array_1 = require(126) /* ../../core/util/array */;
    var CompositeTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CompositeTicker, _super);
        function CompositeTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CompositeTicker.prototype, "min_intervals", {
            // The tickers should be in order of increasing interval size; specifically,
            // if S comes before T, then it should be the case that
            // S.get_max_interval() < T.get_min_interval().
            // FIXME Enforce this automatically.
            get: function () {
                return this.tickers.map(function (ticker) { return ticker.get_min_interval(); });
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CompositeTicker.prototype, "max_intervals", {
            get: function () {
                return this.tickers.map(function (ticker) { return ticker.get_max_interval(); });
            },
            enumerable: false,
            configurable: true
        });
        CompositeTicker.prototype.get_min_interval = function () {
            return this.min_intervals[0];
        };
        CompositeTicker.prototype.get_max_interval = function () {
            return this.max_intervals[0];
        };
        CompositeTicker.prototype.get_best_ticker = function (data_low, data_high, desired_n_ticks) {
            var data_range = data_high - data_low;
            var ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
            var ticker_ndxs = [
                (0, array_1.sorted_index)(this.min_intervals, ideal_interval) - 1,
                (0, array_1.sorted_index)(this.max_intervals, ideal_interval),
            ];
            var intervals = [
                this.min_intervals[ticker_ndxs[0]],
                this.max_intervals[ticker_ndxs[1]],
            ];
            var errors = intervals.map(function (interval) {
                return Math.abs(desired_n_ticks - (data_range / interval));
            });
            var best_ticker;
            if ((0, array_1.is_empty)(errors.filter(function (e) { return !isNaN(e); }))) {
                // this can happen if the data isn't loaded yet, we just default to the first scale
                best_ticker = this.tickers[0];
            }
            else {
                var best_index = (0, array_1.argmin)(errors);
                var best_ticker_ndx = ticker_ndxs[best_index];
                best_ticker = this.tickers[best_ticker_ndx];
            }
            return best_ticker;
        };
        CompositeTicker.prototype.get_interval = function (data_low, data_high, desired_n_ticks) {
            var best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
            return best_ticker.get_interval(data_low, data_high, desired_n_ticks);
        };
        CompositeTicker.prototype.get_ticks_no_defaults = function (data_low, data_high, cross_loc, desired_n_ticks) {
            var best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
            return best_ticker.get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks);
        };
        return CompositeTicker;
    }(continuous_ticker_1.ContinuousTicker));
    exports.CompositeTicker = CompositeTicker;
    _a = CompositeTicker;
    CompositeTicker.__name__ = "CompositeTicker";
    (function () {
        _a.define(function (_b) {
            var Array = _b.Array, Ref = _b.Ref;
            return ({
                tickers: [Array(Ref(continuous_ticker_1.ContinuousTicker)), []],
            });
        });
    })();
},
/* models/tickers/days_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var single_interval_ticker_1 = require(273) /* ./single_interval_ticker */;
    var util_1 = require(274) /* ./util */;
    var array_1 = require(126) /* ../../core/util/array */;
    // Given a start and end time in millis, returns the shortest array of
    // consecutive months (as Dates) that surrounds both times.
    function date_range_by_month(start_time, end_time) {
        var start_date = (0, util_1.last_month_no_later_than)(new Date(start_time));
        var end_date = (0, util_1.last_month_no_later_than)(new Date(end_time));
        // XXX This is not a reliable technique in general, but it should be
        // safe when the day of the month is 1.  (The problem case is this:
        // Mar 31 -> Apr 31, which becomes May 1.)
        end_date.setUTCMonth(end_date.getUTCMonth() + 1);
        var dates = [];
        var date = start_date;
        while (true) {
            dates.push((0, util_1.copy_date)(date));
            date.setUTCMonth(date.getUTCMonth() + 1);
            if (date > end_date)
                break;
        }
        return dates;
    }
    var DaysTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DaysTicker, _super);
        function DaysTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        DaysTicker.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            var days = this.days;
            if (days.length > 1)
                this.interval = (days[1] - days[0]) * util_1.ONE_DAY;
            else
                this.interval = 31 * util_1.ONE_DAY;
        };
        DaysTicker.prototype.get_ticks_no_defaults = function (data_low, data_high, _cross_loc, _desired_n_ticks) {
            var month_dates = date_range_by_month(data_low, data_high);
            var days = this.days;
            var days_of_month = function (month_date, interval) {
                var e_1, _b;
                var current_month = month_date.getUTCMonth();
                var dates = [];
                try {
                    for (var days_1 = (0, tslib_1.__values)(days), days_1_1 = days_1.next(); !days_1_1.done; days_1_1 = days_1.next()) {
                        var day = days_1_1.value;
                        var day_date = (0, util_1.copy_date)(month_date);
                        day_date.setUTCDate(day);
                        // We can't use all of the values in this.days, because they may not
                        // fall within the current month.  In fact, if, e.g., our month is 28 days
                        // and we're marking every third day, we don't want day 28 to show up
                        // because it'll be right next to the 1st of the next month.  So we
                        // make sure we have a bit of room before we include a day.
                        // TODO (bev) The above description does not exactly work because JS Date
                        // is broken and will happily consider "Feb 28 + 3*ONE_DAY" to have month "2"
                        var future_date = new Date(day_date.getTime() + (interval / 2));
                        if (future_date.getUTCMonth() == current_month)
                            dates.push(day_date);
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (days_1_1 && !days_1_1.done && (_b = days_1.return))
                            _b.call(days_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
                return dates;
            };
            var interval = this.interval;
            var day_dates = (0, array_1.concat)(month_dates.map(function (date) { return days_of_month(date, interval); }));
            var all_ticks = day_dates.map(function (day_date) { return day_date.getTime(); });
            var ticks_in_range = all_ticks.filter(function (tick) { return data_low <= tick && tick <= data_high; });
            return {
                major: ticks_in_range,
                minor: [],
            };
        };
        return DaysTicker;
    }(single_interval_ticker_1.SingleIntervalTicker));
    exports.DaysTicker = DaysTicker;
    _a = DaysTicker;
    DaysTicker.__name__ = "DaysTicker";
    (function () {
        _a.define(function (_b) {
            var Int = _b.Int, Array = _b.Array;
            return ({
                days: [Array(Int), []],
            });
        });
        _a.override({
            num_minor_ticks: 0,
        });
    })();
},
/* models/tickers/single_interval_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var continuous_ticker_1 = require(264) /* ./continuous_ticker */;
    var SingleIntervalTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SingleIntervalTicker, _super);
        function SingleIntervalTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        SingleIntervalTicker.prototype.get_interval = function (_data_low, _data_high, _n_desired_ticks) {
            return this.interval;
        };
        SingleIntervalTicker.prototype.get_min_interval = function () {
            return this.interval;
        };
        SingleIntervalTicker.prototype.get_max_interval = function () {
            return this.interval;
        };
        return SingleIntervalTicker;
    }(continuous_ticker_1.ContinuousTicker));
    exports.SingleIntervalTicker = SingleIntervalTicker;
    _a = SingleIntervalTicker;
    SingleIntervalTicker.__name__ = "SingleIntervalTicker";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number;
            return ({
                interval: [Number],
            });
        });
    })();
},
/* models/tickers/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    // TODO Clear out debugging code, etc.
    // TODO Organize helper functions.
    // TODO The years ticker doesn't always use the roundest numbers; it should
    // probably use a special ticker.
    // TODO Add tests.
    // TODO There used to be a TODO: restore memoization.  So.... do that?
    // TODO Instead of a get_ticks() method, there used to be an auto_ticks()
    // function that took a lot of fancy arguments, but those arguments weren't
    // used anywhere.  Should we restore them?
    // Some time constants, in milliseconds.
    exports.ONE_MILLI = 1.0;
    exports.ONE_SECOND = 1000.0;
    exports.ONE_MINUTE = 60.0 * exports.ONE_SECOND;
    exports.ONE_HOUR = 60 * exports.ONE_MINUTE;
    exports.ONE_DAY = 24 * exports.ONE_HOUR;
    exports.ONE_MONTH = 30 * exports.ONE_DAY; // An approximation, obviously.
    exports.ONE_YEAR = 365 * exports.ONE_DAY;
    // ---------------------------------------------------------------------------
    // Date/time utility functions
    // ---------------------------------------------------------------------------
    // Makes a copy of a date object.
    function copy_date(date) {
        return new Date(date.getTime());
    }
    exports.copy_date = copy_date;
    // Rounds a date down to the month.
    function last_month_no_later_than(date) {
        var new_date = copy_date(date);
        new_date.setUTCDate(1);
        new_date.setUTCHours(0);
        new_date.setUTCMinutes(0);
        new_date.setUTCSeconds(0);
        new_date.setUTCMilliseconds(0);
        return new_date;
    }
    exports.last_month_no_later_than = last_month_no_later_than;
    // Rounds a date down to the year.
    function last_year_no_later_than(date) {
        var new_date = last_month_no_later_than(date);
        new_date.setUTCMonth(0);
        return new_date;
    }
    exports.last_year_no_later_than = last_year_no_later_than;
},
/* models/tickers/months_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var single_interval_ticker_1 = require(273) /* ./single_interval_ticker */;
    var util_1 = require(274) /* ./util */;
    var array_1 = require(126) /* ../../core/util/array */;
    // Given a start and end time in millis, returns the shortest array of
    // consecutive years (as Dates) that surrounds both times.
    function date_range_by_year(start_time, end_time) {
        var start_date = (0, util_1.last_year_no_later_than)(new Date(start_time));
        var end_date = (0, util_1.last_year_no_later_than)(new Date(end_time));
        end_date.setUTCFullYear(end_date.getUTCFullYear() + 1);
        var dates = [];
        var date = start_date;
        while (true) {
            dates.push((0, util_1.copy_date)(date));
            date.setUTCFullYear(date.getUTCFullYear() + 1);
            if (date > end_date)
                break;
        }
        return dates;
    }
    var MonthsTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MonthsTicker, _super);
        function MonthsTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        MonthsTicker.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            var months = this.months;
            if (months.length > 1)
                this.interval = (months[1] - months[0]) * util_1.ONE_MONTH;
            else
                this.interval = 12 * util_1.ONE_MONTH;
        };
        MonthsTicker.prototype.get_ticks_no_defaults = function (data_low, data_high, _cross_loc, _desired_n_ticks) {
            var year_dates = date_range_by_year(data_low, data_high);
            var months = this.months;
            var months_of_year = function (year_date) {
                return months.map(function (month) {
                    var month_date = (0, util_1.copy_date)(year_date);
                    month_date.setUTCMonth(month);
                    return month_date;
                });
            };
            var month_dates = (0, array_1.concat)(year_dates.map(months_of_year));
            var all_ticks = month_dates.map(function (month_date) { return month_date.getTime(); });
            var ticks_in_range = all_ticks.filter(function (tick) { return data_low <= tick && tick <= data_high; });
            return {
                major: ticks_in_range,
                minor: [],
            };
        };
        return MonthsTicker;
    }(single_interval_ticker_1.SingleIntervalTicker));
    exports.MonthsTicker = MonthsTicker;
    _a = MonthsTicker;
    MonthsTicker.__name__ = "MonthsTicker";
    (function () {
        _a.define(function (_b) {
            var Int = _b.Int, Array = _b.Array;
            return ({
                months: [Array(Int), []],
            });
        });
    })();
},
/* models/tickers/years_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var basic_ticker_1 = require(262) /* ./basic_ticker */;
    var single_interval_ticker_1 = require(273) /* ./single_interval_ticker */;
    var util_1 = require(274) /* ./util */;
    var YearsTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(YearsTicker, _super);
        function YearsTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        YearsTicker.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.interval = util_1.ONE_YEAR;
            this.basic_ticker = new basic_ticker_1.BasicTicker({ num_minor_ticks: 0 });
        };
        YearsTicker.prototype.get_ticks_no_defaults = function (data_low, data_high, cross_loc, desired_n_ticks) {
            var start_year = (0, util_1.last_year_no_later_than)(new Date(data_low)).getUTCFullYear();
            var end_year = (0, util_1.last_year_no_later_than)(new Date(data_high)).getUTCFullYear();
            var years = this.basic_ticker.get_ticks_no_defaults(start_year, end_year, cross_loc, desired_n_ticks).major;
            var all_ticks = years.map(function (year) { return Date.UTC(year, 0, 1); });
            var ticks_in_range = all_ticks.filter(function (tick) { return data_low <= tick && tick <= data_high; });
            return {
                major: ticks_in_range,
                minor: [],
            };
        };
        return YearsTicker;
    }(single_interval_ticker_1.SingleIntervalTicker));
    exports.YearsTicker = YearsTicker;
    YearsTicker.__name__ = "YearsTicker";
},
/* models/axes/log_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var continuous_axis_1 = require(258) /* ./continuous_axis */;
    var log_tick_formatter_1 = require(278) /* ../formatters/log_tick_formatter */;
    var log_ticker_1 = require(279) /* ../tickers/log_ticker */;
    var LogAxisView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LogAxisView, _super);
        function LogAxisView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LogAxisView;
    }(continuous_axis_1.ContinuousAxisView));
    exports.LogAxisView = LogAxisView;
    LogAxisView.__name__ = "LogAxisView";
    var LogAxis = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LogAxis, _super);
        function LogAxis(attrs) {
            return _super.call(this, attrs) || this;
        }
        return LogAxis;
    }(continuous_axis_1.ContinuousAxis));
    exports.LogAxis = LogAxis;
    _a = LogAxis;
    LogAxis.__name__ = "LogAxis";
    (function () {
        _a.prototype.default_view = LogAxisView;
        _a.override({
            ticker: function () { return new log_ticker_1.LogTicker(); },
            formatter: function () { return new log_tick_formatter_1.LogTickFormatter(); },
        });
    })();
},
/* models/formatters/log_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var tick_formatter_1 = require(246) /* ./tick_formatter */;
    var basic_tick_formatter_1 = require(261) /* ./basic_tick_formatter */;
    var log_ticker_1 = require(279) /* ../tickers/log_ticker */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var abs = Math.abs, log = Math.log, round = Math.round;
    var LogTickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LogTickFormatter, _super);
        function LogTickFormatter(attrs) {
            return _super.call(this, attrs) || this;
        }
        LogTickFormatter.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.basic_formatter = new basic_tick_formatter_1.BasicTickFormatter();
        };
        LogTickFormatter.prototype.format_graphics = function (ticks, opts) {
            var _this = this;
            var _b, _c;
            if (ticks.length == 0)
                return [];
            var base = (_c = (_b = this.ticker) === null || _b === void 0 ? void 0 : _b.base) !== null && _c !== void 0 ? _c : 10;
            var expos = this._exponents(ticks, base);
            if (expos == null)
                return this.basic_formatter.format_graphics(ticks, opts);
            else {
                return expos.map(function (expo) {
                    if (abs(expo) < _this.min_exponent) {
                        var b = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)("" + Math.pow(base, expo)) });
                        var e = new graphics_1.TextBox({ text: "" });
                        return new graphics_1.BaseExpo(b, e);
                    }
                    else {
                        var b = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)("" + base) });
                        var e = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)("" + expo) });
                        return new graphics_1.BaseExpo(b, e);
                    }
                });
            }
        };
        LogTickFormatter.prototype._exponents = function (ticks, base) {
            var e_1, _b;
            var last_exponent = null;
            var exponents = [];
            try {
                for (var ticks_1 = (0, tslib_1.__values)(ticks), ticks_1_1 = ticks_1.next(); !ticks_1_1.done; ticks_1_1 = ticks_1.next()) {
                    var tick = ticks_1_1.value;
                    var exponent = round(log(tick) / log(base));
                    if (last_exponent != exponent) {
                        last_exponent = exponent;
                        exponents.push(exponent);
                    }
                    else
                        return null;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (ticks_1_1 && !ticks_1_1.done && (_b = ticks_1.return))
                        _b.call(ticks_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return exponents;
        };
        LogTickFormatter.prototype.doFormat = function (ticks, opts) {
            var _this = this;
            var _b, _c;
            if (ticks.length == 0)
                return [];
            var base = (_c = (_b = this.ticker) === null || _b === void 0 ? void 0 : _b.base) !== null && _c !== void 0 ? _c : 10;
            var expos = this._exponents(ticks, base);
            if (expos == null)
                return this.basic_formatter.doFormat(ticks, opts);
            else
                return expos.map(function (expo) {
                    if (abs(expo) < _this.min_exponent)
                        return (0, basic_tick_formatter_1.unicode_replace)("" + Math.pow(base, expo));
                    else
                        return (0, basic_tick_formatter_1.unicode_replace)(base + "^" + expo);
                });
        };
        return LogTickFormatter;
    }(tick_formatter_1.TickFormatter));
    exports.LogTickFormatter = LogTickFormatter;
    _a = LogTickFormatter;
    LogTickFormatter.__name__ = "LogTickFormatter";
    (function () {
        _a.define(function (_b) {
            var Int = _b.Int, Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                ticker: [Nullable(Ref(log_ticker_1.LogTicker)), null],
                min_exponent: [Int, 0],
            });
        });
    })();
},
/* models/tickers/log_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var adaptive_ticker_1 = require(263) /* ./adaptive_ticker */;
    var array_1 = require(126) /* ../../core/util/array */;
    var LogTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LogTicker, _super);
        function LogTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        LogTicker.prototype.get_ticks_no_defaults = function (data_low, data_high, _cross_loc, desired_n_ticks) {
            var e_1, _b, e_2, _c, e_3, _d, e_4, _e, e_5, _f, e_6, _g;
            var num_minor_ticks = this.num_minor_ticks;
            var minor_ticks = [];
            var base = this.base;
            var log_low = Math.log(data_low) / Math.log(base);
            var log_high = Math.log(data_high) / Math.log(base);
            var log_interval = log_high - log_low;
            var ticks;
            if (!isFinite(log_interval)) {
                ticks = [];
            }
            else if (log_interval < 2) { // treat as linear ticker
                var interval_1 = this.get_interval(data_low, data_high, desired_n_ticks);
                var start_factor = Math.floor(data_low / interval_1);
                var end_factor = Math.ceil(data_high / interval_1);
                ticks = (0, array_1.range)(start_factor, end_factor + 1)
                    .filter(function (factor) { return factor != 0; })
                    .map(function (factor) { return factor * interval_1; })
                    .filter(function (tick) { return data_low <= tick && tick <= data_high; });
                if (num_minor_ticks > 0 && ticks.length > 0) {
                    var minor_interval_1 = interval_1 / num_minor_ticks;
                    var minor_offsets = (0, array_1.range)(0, num_minor_ticks).map(function (i) { return i * minor_interval_1; });
                    try {
                        for (var _h = (0, tslib_1.__values)(minor_offsets.slice(1)), _j = _h.next(); !_j.done; _j = _h.next()) {
                            var x = _j.value;
                            minor_ticks.push(ticks[0] - x);
                        }
                    }
                    catch (e_1_1) {
                        e_1 = { error: e_1_1 };
                    }
                    finally {
                        try {
                            if (_j && !_j.done && (_b = _h.return))
                                _b.call(_h);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                    }
                    try {
                        for (var ticks_1 = (0, tslib_1.__values)(ticks), ticks_1_1 = ticks_1.next(); !ticks_1_1.done; ticks_1_1 = ticks_1.next()) {
                            var tick = ticks_1_1.value;
                            try {
                                for (var minor_offsets_1 = (e_3 = void 0, (0, tslib_1.__values)(minor_offsets)), minor_offsets_1_1 = minor_offsets_1.next(); !minor_offsets_1_1.done; minor_offsets_1_1 = minor_offsets_1.next()) {
                                    var x = minor_offsets_1_1.value;
                                    minor_ticks.push(tick + x);
                                }
                            }
                            catch (e_3_1) {
                                e_3 = { error: e_3_1 };
                            }
                            finally {
                                try {
                                    if (minor_offsets_1_1 && !minor_offsets_1_1.done && (_d = minor_offsets_1.return))
                                        _d.call(minor_offsets_1);
                                }
                                finally {
                                    if (e_3)
                                        throw e_3.error;
                                }
                            }
                        }
                    }
                    catch (e_2_1) {
                        e_2 = { error: e_2_1 };
                    }
                    finally {
                        try {
                            if (ticks_1_1 && !ticks_1_1.done && (_c = ticks_1.return))
                                _c.call(ticks_1);
                        }
                        finally {
                            if (e_2)
                                throw e_2.error;
                        }
                    }
                }
            }
            else {
                var startlog = Math.ceil(log_low * 0.999999);
                var endlog = Math.floor(log_high * 1.000001);
                var interval = Math.ceil((endlog - startlog) / 9.0);
                ticks = (0, array_1.range)(startlog - 1, endlog + 1, interval)
                    .map(function (i) { return Math.pow(base, i); });
                if (num_minor_ticks > 0 && ticks.length > 0) {
                    var minor_interval_2 = Math.pow(base, interval) / num_minor_ticks;
                    var minor_offsets = (0, array_1.range)(1, num_minor_ticks + 1).map(function (i) { return i * minor_interval_2; });
                    try {
                        for (var minor_offsets_2 = (0, tslib_1.__values)(minor_offsets), minor_offsets_2_1 = minor_offsets_2.next(); !minor_offsets_2_1.done; minor_offsets_2_1 = minor_offsets_2.next()) {
                            var x = minor_offsets_2_1.value;
                            minor_ticks.push(ticks[0] / x);
                        }
                    }
                    catch (e_4_1) {
                        e_4 = { error: e_4_1 };
                    }
                    finally {
                        try {
                            if (minor_offsets_2_1 && !minor_offsets_2_1.done && (_e = minor_offsets_2.return))
                                _e.call(minor_offsets_2);
                        }
                        finally {
                            if (e_4)
                                throw e_4.error;
                        }
                    }
                    minor_ticks.push(ticks[0]);
                    try {
                        for (var ticks_2 = (0, tslib_1.__values)(ticks), ticks_2_1 = ticks_2.next(); !ticks_2_1.done; ticks_2_1 = ticks_2.next()) {
                            var tick = ticks_2_1.value;
                            try {
                                for (var minor_offsets_3 = (e_6 = void 0, (0, tslib_1.__values)(minor_offsets)), minor_offsets_3_1 = minor_offsets_3.next(); !minor_offsets_3_1.done; minor_offsets_3_1 = minor_offsets_3.next()) {
                                    var x = minor_offsets_3_1.value;
                                    minor_ticks.push(tick * x);
                                }
                            }
                            catch (e_6_1) {
                                e_6 = { error: e_6_1 };
                            }
                            finally {
                                try {
                                    if (minor_offsets_3_1 && !minor_offsets_3_1.done && (_g = minor_offsets_3.return))
                                        _g.call(minor_offsets_3);
                                }
                                finally {
                                    if (e_6)
                                        throw e_6.error;
                                }
                            }
                        }
                    }
                    catch (e_5_1) {
                        e_5 = { error: e_5_1 };
                    }
                    finally {
                        try {
                            if (ticks_2_1 && !ticks_2_1.done && (_f = ticks_2.return))
                                _f.call(ticks_2);
                        }
                        finally {
                            if (e_5)
                                throw e_5.error;
                        }
                    }
                }
            }
            return {
                major: ticks.filter(function (tick) { return data_low <= tick && tick <= data_high; }),
                minor: minor_ticks.filter(function (tick) { return data_low <= tick && tick <= data_high; }),
            };
        };
        return LogTicker;
    }(adaptive_ticker_1.AdaptiveTicker));
    exports.LogTicker = LogTicker;
    _a = LogTicker;
    LogTicker.__name__ = "LogTicker";
    (function () {
        _a.override({
            mantissas: [1, 5],
        });
    })();
},
/* models/axes/mercator_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var axis_1 = require(243) /* ./axis */;
    var linear_axis_1 = require(260) /* ./linear_axis */;
    var mercator_tick_formatter_1 = require(281) /* ../formatters/mercator_tick_formatter */;
    var mercator_ticker_1 = require(282) /* ../tickers/mercator_ticker */;
    var MercatorAxisView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MercatorAxisView, _super);
        function MercatorAxisView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return MercatorAxisView;
    }(axis_1.AxisView));
    exports.MercatorAxisView = MercatorAxisView;
    MercatorAxisView.__name__ = "MercatorAxisView";
    var MercatorAxis = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MercatorAxis, _super);
        function MercatorAxis(attrs) {
            return _super.call(this, attrs) || this;
        }
        return MercatorAxis;
    }(linear_axis_1.LinearAxis));
    exports.MercatorAxis = MercatorAxis;
    _a = MercatorAxis;
    MercatorAxis.__name__ = "MercatorAxis";
    (function () {
        _a.prototype.default_view = MercatorAxisView;
        _a.override({
            ticker: function () { return new mercator_ticker_1.MercatorTicker({ dimension: "lat" }); },
            formatter: function () { return new mercator_tick_formatter_1.MercatorTickFormatter({ dimension: "lat" }); },
        });
    })();
},
/* models/formatters/mercator_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var basic_tick_formatter_1 = require(261) /* ./basic_tick_formatter */;
    var enums_1 = require(135) /* ../../core/enums */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var MercatorTickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MercatorTickFormatter, _super);
        function MercatorTickFormatter(attrs) {
            return _super.call(this, attrs) || this;
        }
        MercatorTickFormatter.prototype.doFormat = function (ticks, opts) {
            if (this.dimension == null)
                throw new Error("MercatorTickFormatter.dimension not configured");
            if (ticks.length == 0)
                return [];
            var n = ticks.length;
            var proj_ticks = new Array(n);
            if (this.dimension == "lon") {
                for (var i = 0; i < n; i++) {
                    var _b = (0, tslib_1.__read)(projections_1.wgs84_mercator.invert(ticks[i], opts.loc), 1), lon = _b[0];
                    proj_ticks[i] = lon;
                }
            }
            else {
                for (var i = 0; i < n; i++) {
                    var _c = (0, tslib_1.__read)(projections_1.wgs84_mercator.invert(opts.loc, ticks[i]), 2), lat = _c[1];
                    proj_ticks[i] = lat;
                }
            }
            return _super.prototype.doFormat.call(this, proj_ticks, opts);
        };
        return MercatorTickFormatter;
    }(basic_tick_formatter_1.BasicTickFormatter));
    exports.MercatorTickFormatter = MercatorTickFormatter;
    _a = MercatorTickFormatter;
    MercatorTickFormatter.__name__ = "MercatorTickFormatter";
    (function () {
        _a.define(function (_b) {
            var Nullable = _b.Nullable;
            return ({
                dimension: [Nullable(enums_1.LatLon), null],
            });
        });
    })();
},
/* models/tickers/mercator_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var basic_ticker_1 = require(262) /* ./basic_ticker */;
    var enums_1 = require(135) /* ../../core/enums */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var MercatorTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MercatorTicker, _super);
        function MercatorTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        MercatorTicker.prototype.get_ticks_no_defaults = function (data_low, data_high, cross_loc, desired_n_ticks) {
            var _b;
            if (this.dimension == null) {
                throw new Error(this + ".dimension wasn't configured");
            }
            _b = (0, tslib_1.__read)((0, projections_1.clip_mercator)(data_low, data_high, this.dimension), 2), data_low = _b[0], data_high = _b[1];
            if (this.dimension == "lon")
                return this._get_ticks_lon(data_low, data_high, cross_loc, desired_n_ticks);
            else
                return this._get_ticks_lat(data_low, data_high, cross_loc, desired_n_ticks);
        };
        MercatorTicker.prototype._get_ticks_lon = function (data_low, data_high, cross_loc, desired_n_ticks) {
            var e_1, _b, e_2, _c;
            var _d = (0, tslib_1.__read)(projections_1.wgs84_mercator.invert(data_low, cross_loc), 1), proj_low = _d[0];
            var _e = (0, tslib_1.__read)(projections_1.wgs84_mercator.invert(data_high, cross_loc), 2), proj_high = _e[0], proj_cross_loc = _e[1];
            var proj_ticks = _super.prototype.get_ticks_no_defaults.call(this, proj_low, proj_high, cross_loc, desired_n_ticks);
            var major = [];
            try {
                for (var _f = (0, tslib_1.__values)(proj_ticks.major), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var tick = _g.value;
                    if ((0, projections_1.in_bounds)(tick, "lon")) {
                        var _h = (0, tslib_1.__read)(projections_1.wgs84_mercator.compute(tick, proj_cross_loc), 1), lon = _h[0];
                        major.push(lon);
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_b = _f.return))
                        _b.call(_f);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            var minor = [];
            try {
                for (var _j = (0, tslib_1.__values)(proj_ticks.minor), _k = _j.next(); !_k.done; _k = _j.next()) {
                    var tick = _k.value;
                    if ((0, projections_1.in_bounds)(tick, "lon")) {
                        var _l = (0, tslib_1.__read)(projections_1.wgs84_mercator.compute(tick, proj_cross_loc), 1), lon = _l[0];
                        minor.push(lon);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_k && !_k.done && (_c = _j.return))
                        _c.call(_j);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return { major: major, minor: minor };
        };
        MercatorTicker.prototype._get_ticks_lat = function (data_low, data_high, cross_loc, desired_n_ticks) {
            var e_3, _b, e_4, _c;
            var _d = (0, tslib_1.__read)(projections_1.wgs84_mercator.invert(cross_loc, data_low), 2), proj_low = _d[1];
            var _e = (0, tslib_1.__read)(projections_1.wgs84_mercator.invert(cross_loc, data_high), 2), proj_cross_loc = _e[0], proj_high = _e[1];
            var proj_ticks = _super.prototype.get_ticks_no_defaults.call(this, proj_low, proj_high, cross_loc, desired_n_ticks);
            var major = [];
            try {
                for (var _f = (0, tslib_1.__values)(proj_ticks.major), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var tick = _g.value;
                    if ((0, projections_1.in_bounds)(tick, "lat")) {
                        var _h = (0, tslib_1.__read)(projections_1.wgs84_mercator.compute(proj_cross_loc, tick), 2), lat = _h[1];
                        major.push(lat);
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_b = _f.return))
                        _b.call(_f);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            var minor = [];
            try {
                for (var _j = (0, tslib_1.__values)(proj_ticks.minor), _k = _j.next(); !_k.done; _k = _j.next()) {
                    var tick = _k.value;
                    if ((0, projections_1.in_bounds)(tick, "lat")) {
                        var _l = (0, tslib_1.__read)(projections_1.wgs84_mercator.compute(proj_cross_loc, tick), 2), lat = _l[1];
                        minor.push(lat);
                    }
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_k && !_k.done && (_c = _j.return))
                        _c.call(_j);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            return { major: major, minor: minor };
        };
        return MercatorTicker;
    }(basic_ticker_1.BasicTicker));
    exports.MercatorTicker = MercatorTicker;
    _a = MercatorTicker;
    MercatorTicker.__name__ = "MercatorTicker";
    (function () {
        _a.define(function (_b) {
            var Nullable = _b.Nullable;
            return ({
                dimension: [Nullable(enums_1.LatLon), null],
            });
        });
    })();
},
/* models/tickers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var adaptive_ticker_1 = require(263) /* ./adaptive_ticker */;
    __esExport("AdaptiveTicker", adaptive_ticker_1.AdaptiveTicker);
    var basic_ticker_1 = require(262) /* ./basic_ticker */;
    __esExport("BasicTicker", basic_ticker_1.BasicTicker);
    var categorical_ticker_1 = require(256) /* ./categorical_ticker */;
    __esExport("CategoricalTicker", categorical_ticker_1.CategoricalTicker);
    var composite_ticker_1 = require(271) /* ./composite_ticker */;
    __esExport("CompositeTicker", composite_ticker_1.CompositeTicker);
    var continuous_ticker_1 = require(264) /* ./continuous_ticker */;
    __esExport("ContinuousTicker", continuous_ticker_1.ContinuousTicker);
    var datetime_ticker_1 = require(270) /* ./datetime_ticker */;
    __esExport("DatetimeTicker", datetime_ticker_1.DatetimeTicker);
    var days_ticker_1 = require(272) /* ./days_ticker */;
    __esExport("DaysTicker", days_ticker_1.DaysTicker);
    var fixed_ticker_1 = require(284) /* ./fixed_ticker */;
    __esExport("FixedTicker", fixed_ticker_1.FixedTicker);
    var log_ticker_1 = require(279) /* ./log_ticker */;
    __esExport("LogTicker", log_ticker_1.LogTicker);
    var mercator_ticker_1 = require(282) /* ./mercator_ticker */;
    __esExport("MercatorTicker", mercator_ticker_1.MercatorTicker);
    var months_ticker_1 = require(275) /* ./months_ticker */;
    __esExport("MonthsTicker", months_ticker_1.MonthsTicker);
    var single_interval_ticker_1 = require(273) /* ./single_interval_ticker */;
    __esExport("SingleIntervalTicker", single_interval_ticker_1.SingleIntervalTicker);
    var ticker_1 = require(245) /* ./ticker */;
    __esExport("Ticker", ticker_1.Ticker);
    var years_ticker_1 = require(276) /* ./years_ticker */;
    __esExport("YearsTicker", years_ticker_1.YearsTicker);
    var binned_ticker_1 = require(285) /* ./binned_ticker */;
    __esExport("BinnedTicker", binned_ticker_1.BinnedTicker);
},
/* models/tickers/fixed_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var continuous_ticker_1 = require(264) /* ./continuous_ticker */;
    var FixedTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FixedTicker, _super);
        function FixedTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        FixedTicker.prototype.get_ticks_no_defaults = function (_data_low, _data_high, _cross_loc, _desired_n_ticks) {
            return {
                major: this.ticks,
                minor: this.minor_ticks,
            };
        };
        // XXX: whatever, because FixedTicker needs to fulfill the interface somehow
        FixedTicker.prototype.get_interval = function (_data_low, _data_high, _desired_n_ticks) {
            return 0;
        };
        FixedTicker.prototype.get_min_interval = function () {
            return 0;
        };
        FixedTicker.prototype.get_max_interval = function () {
            return 0;
        };
        return FixedTicker;
    }(continuous_ticker_1.ContinuousTicker));
    exports.FixedTicker = FixedTicker;
    _a = FixedTicker;
    FixedTicker.__name__ = "FixedTicker";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Array = _b.Array;
            return ({
                ticks: [Array(Number), []],
                minor_ticks: [Array(Number), []],
            });
        });
    })();
},
/* models/tickers/binned_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var ticker_1 = require(245) /* ./ticker */;
    var scanning_color_mapper_1 = require(286) /* ../mappers/scanning_color_mapper */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var BinnedTicker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BinnedTicker, _super);
        function BinnedTicker(attrs) {
            return _super.call(this, attrs) || this;
        }
        BinnedTicker.prototype.get_ticks = function (data_low, data_high, _range, _cross_loc) {
            var binning = this.mapper.metrics.binning;
            var k_low = Math.max(0, (0, arrayable_1.left_edge_index)(data_low, binning));
            var k_high = Math.min((0, arrayable_1.left_edge_index)(data_high, binning) + 1, binning.length - 1);
            var _major = [];
            for (var k = k_low; k <= k_high; k++) {
                _major.push(binning[k]);
            }
            var num_major_ticks = this.num_major_ticks;
            var major = [];
            var n = num_major_ticks == "auto" ? _major.length : num_major_ticks;
            var step = Math.max(1, Math.floor(_major.length / n));
            for (var i = 0; i < _major.length; i += step) {
                major.push(_major[i]);
            }
            return {
                major: major,
                minor: [],
            };
        };
        return BinnedTicker;
    }(ticker_1.Ticker));
    exports.BinnedTicker = BinnedTicker;
    _a = BinnedTicker;
    BinnedTicker.__name__ = "BinnedTicker";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Ref = _b.Ref, Or = _b.Or, Auto = _b.Auto;
            return ({
                mapper: [Ref(scanning_color_mapper_1.ScanningColorMapper)],
                num_major_ticks: [Or(Number, Auto), 8],
            });
        });
    })();
},
/* models/mappers/scanning_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var continuous_color_mapper_1 = require(287) /* ./continuous_color_mapper */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var ScanningColorMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ScanningColorMapper, _super);
        function ScanningColorMapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        ScanningColorMapper.prototype.cmap = function (d, palette, low_color, high_color, edges) {
            if (d < edges.binning[0])
                return low_color;
            if (d > edges.binning[edges.binning.length - 1])
                return high_color;
            var key = (0, arrayable_1.left_edge_index)(d, edges.binning);
            return palette[key];
        };
        return ScanningColorMapper;
    }(continuous_color_mapper_1.ContinuousColorMapper));
    exports.ScanningColorMapper = ScanningColorMapper;
    ScanningColorMapper.__name__ = "ScanningColorMapper";
},
/* models/mappers/continuous_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var color_mapper_1 = require(288) /* ./color_mapper */;
    var glyph_renderer_1 = require(290) /* ../renderers/glyph_renderer */;
    var array_1 = require(126) /* ../../core/util/array */;
    var types_1 = require(125) /* ../../core/util/types */;
    var ContinuousColorMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ContinuousColorMapper, _super);
        function ContinuousColorMapper(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this._scan_data = null;
            return _this;
        }
        ContinuousColorMapper.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var connect_renderers = function () {
                var e_1, _b;
                try {
                    // TODO: if already connected this will bail. However, it won't remove old connections.
                    for (var _c = (0, tslib_1.__values)(_this.domain), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var _e = (0, tslib_1.__read)(_d.value, 1), renderer = _e[0];
                        _this.connect(renderer.view.change, function () { return _this.update_data(); });
                        _this.connect(renderer.data_source.selected.change, function () { return _this.update_data(); });
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_b = _c.return))
                            _b.call(_c);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            };
            this.connect(this.properties.domain.change, function () { return connect_renderers(); });
            connect_renderers();
        };
        ContinuousColorMapper.prototype.update_data = function () {
            var _b = this, domain = _b.domain, palette = _b.palette;
            var all_data = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this._collect(domain)), false);
            this._scan_data = this.scan(all_data, palette.length);
            this.metrics_change.emit();
            this.change.emit();
        };
        Object.defineProperty(ContinuousColorMapper.prototype, "metrics", {
            get: function () {
                if (this._scan_data == null) {
                    this.update_data();
                }
                return this._scan_data;
            },
            enumerable: false,
            configurable: true
        });
        ContinuousColorMapper.prototype._collect = function (domain) {
            var domain_1, domain_1_1, _b, renderer, fields, _loop_1, _c, _d, field, e_2_1, e_3_1;
            var e_3, _e, e_2, _f;
            return (0, tslib_1.__generator)(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        _g.trys.push([0, 11, 12, 13]);
                        domain_1 = (0, tslib_1.__values)(domain), domain_1_1 = domain_1.next();
                        _g.label = 1;
                    case 1:
                        if (!!domain_1_1.done)
                            return [3 /*break*/, 10];
                        _b = (0, tslib_1.__read)(domain_1_1.value, 2), renderer = _b[0], fields = _b[1];
                        _loop_1 = function (field) {
                            var array, masked, selected, subset, array_2, array_2_1, subarray, e_4_1;
                            var e_4, _h;
                            return (0, tslib_1.__generator)(this, function (_j) {
                                switch (_j.label) {
                                    case 0:
                                        array = renderer.data_source.get_column(field);
                                        array = renderer.view.indices.select(array);
                                        masked = renderer.view.masked;
                                        selected = renderer.data_source.selected.indices;
                                        subset = void 0;
                                        if (masked != null && selected.length > 0)
                                            subset = (0, array_1.intersection)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(masked), false), selected);
                                        else if (masked != null)
                                            subset = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(masked), false);
                                        else if (selected.length > 0)
                                            subset = selected;
                                        if (subset != null) {
                                            array = (0, array_1.map)(subset, function (i) { return array[i]; });
                                        }
                                        if (!(array.length > 0 && !(0, types_1.isNumber)(array[0])))
                                            return [3 /*break*/, 9];
                                        _j.label = 1;
                                    case 1:
                                        _j.trys.push([1, 6, 7, 8]);
                                        array_2 = (e_4 = void 0, (0, tslib_1.__values)(array)), array_2_1 = array_2.next();
                                        _j.label = 2;
                                    case 2:
                                        if (!!array_2_1.done)
                                            return [3 /*break*/, 5];
                                        subarray = array_2_1.value;
                                        return [5 /*yield**/, (0, tslib_1.__values)(subarray)];
                                    case 3:
                                        _j.sent();
                                        _j.label = 4;
                                    case 4:
                                        array_2_1 = array_2.next();
                                        return [3 /*break*/, 2];
                                    case 5: return [3 /*break*/, 8];
                                    case 6:
                                        e_4_1 = _j.sent();
                                        e_4 = { error: e_4_1 };
                                        return [3 /*break*/, 8];
                                    case 7:
                                        try {
                                            if (array_2_1 && !array_2_1.done && (_h = array_2.return))
                                                _h.call(array_2);
                                        }
                                        finally {
                                            if (e_4)
                                                throw e_4.error;
                                        }
                                        return [7 /*endfinally*/];
                                    case 8: return [3 /*break*/, 11];
                                    case 9: return [5 /*yield**/, (0, tslib_1.__values)(array)];
                                    case 10:
                                        _j.sent();
                                        _j.label = 11;
                                    case 11: return [2 /*return*/];
                                }
                            });
                        };
                        _g.label = 2;
                    case 2:
                        _g.trys.push([2, 7, 8, 9]);
                        _c = (e_2 = void 0, (0, tslib_1.__values)((0, types_1.isArray)(fields) ? fields : [fields])), _d = _c.next();
                        _g.label = 3;
                    case 3:
                        if (!!_d.done)
                            return [3 /*break*/, 6];
                        field = _d.value;
                        return [5 /*yield**/, _loop_1(field)];
                    case 4:
                        _g.sent();
                        _g.label = 5;
                    case 5:
                        _d = _c.next();
                        return [3 /*break*/, 3];
                    case 6: return [3 /*break*/, 9];
                    case 7:
                        e_2_1 = _g.sent();
                        e_2 = { error: e_2_1 };
                        return [3 /*break*/, 9];
                    case 8:
                        try {
                            if (_d && !_d.done && (_f = _c.return))
                                _f.call(_c);
                        }
                        finally {
                            if (e_2)
                                throw e_2.error;
                        }
                        return [7 /*endfinally*/];
                    case 9:
                        domain_1_1 = domain_1.next();
                        return [3 /*break*/, 1];
                    case 10: return [3 /*break*/, 13];
                    case 11:
                        e_3_1 = _g.sent();
                        e_3 = { error: e_3_1 };
                        return [3 /*break*/, 13];
                    case 12:
                        try {
                            if (domain_1_1 && !domain_1_1.done && (_e = domain_1.return))
                                _e.call(domain_1);
                        }
                        finally {
                            if (e_3)
                                throw e_3.error;
                        }
                        return [7 /*endfinally*/];
                    case 13: return [2 /*return*/];
                }
            });
        };
        ContinuousColorMapper.prototype._v_compute = function (data, values, palette, colors) {
            var nan_color = colors.nan_color;
            var low_color = colors.low_color, high_color = colors.high_color;
            if (low_color == null)
                low_color = palette[0];
            if (high_color == null)
                high_color = palette[palette.length - 1];
            var domain = this.domain;
            var all_data = !(0, array_1.is_empty)(domain) ? (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this._collect(domain)), false) : data;
            this._scan_data = this.scan(all_data, palette.length);
            this.metrics_change.emit();
            for (var i = 0, end = data.length; i < end; i++) {
                var d = data[i];
                if (isNaN(d))
                    values[i] = nan_color;
                else
                    values[i] = this.cmap(d, palette, low_color, high_color, this._scan_data);
            }
        };
        ContinuousColorMapper.prototype._colors = function (conv) {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._colors.call(this, conv)), { low_color: this.low_color != null ? conv(this.low_color) : undefined, high_color: this.high_color != null ? conv(this.high_color) : undefined });
        };
        return ContinuousColorMapper;
    }(color_mapper_1.ColorMapper));
    exports.ContinuousColorMapper = ContinuousColorMapper;
    _a = ContinuousColorMapper;
    ContinuousColorMapper.__name__ = "ContinuousColorMapper";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, String = _b.String, Ref = _b.Ref, Color = _b.Color, Or = _b.Or, Tuple = _b.Tuple, Array = _b.Array, Nullable = _b.Nullable;
            return {
                high: [Nullable(Number), null],
                low: [Nullable(Number), null],
                high_color: [Nullable(Color), null],
                low_color: [Nullable(Color), null],
                domain: [Array(Tuple(Ref(glyph_renderer_1.GlyphRenderer), Or(String, Array(String)))), []],
            };
        });
    })();
},
/* models/mappers/color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var mapper_1 = require(289) /* ./mapper */;
    var signaling_1 = require(130) /* ../../core/signaling */;
    var types_1 = require(139) /* ../../core/types */;
    var color_1 = require(137) /* ../../core/util/color */;
    var platform_1 = require(142) /* ../../core/util/platform */;
    // export for testing
    function _convert_color(color) {
        return (0, color_1.encode_rgba)((0, color_1.color2rgba)(color));
    }
    exports._convert_color = _convert_color;
    // export for testing
    function _convert_palette(palette) {
        var new_palette = new Uint32Array(palette.length);
        for (var i = 0, end = palette.length; i < end; i++)
            new_palette[i] = _convert_color(palette[i]);
        return new_palette;
    }
    exports._convert_palette = _convert_palette;
    var ColorMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColorMapper, _super);
        function ColorMapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        ColorMapper.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.metrics_change = new signaling_1.Signal0(this, "metrics_change");
        };
        ColorMapper.prototype.v_compute = function (xs) {
            var values = new Array(xs.length);
            this._v_compute(xs, values, this.palette, this._colors(function (c) { return c; }));
            return values;
        };
        Object.defineProperty(ColorMapper.prototype, "rgba_mapper", {
            get: function () {
                var self = this;
                var palette = _convert_palette(this.palette);
                var colors = this._colors(_convert_color);
                return {
                    v_compute: function (xs) {
                        var values = new types_1.ColorArray(xs.length);
                        self._v_compute(xs, values, palette, colors);
                        return new Uint8ClampedArray((0, platform_1.to_big_endian)(values).buffer);
                    },
                };
            },
            enumerable: false,
            configurable: true
        });
        ColorMapper.prototype._colors = function (conv) {
            return { nan_color: conv(this.nan_color) };
        };
        return ColorMapper;
    }(mapper_1.Mapper));
    exports.ColorMapper = ColorMapper;
    _a = ColorMapper;
    ColorMapper.__name__ = "ColorMapper";
    (function () {
        _a.define(function (_b) {
            var Color = _b.Color, Array = _b.Array;
            return ({
                palette: [Array(Color)],
                nan_color: [Color, "gray"],
            });
        });
    })();
},
/* models/mappers/mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var transform_1 = require(171) /* ../transforms/transform */;
    var Mapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Mapper, _super);
        function Mapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        Mapper.prototype.compute = function (_x) {
            // If it's just a single value, then a mapper doesn't really make sense.
            throw new Error("mapping single values is not supported");
        };
        return Mapper;
    }(transform_1.Transform));
    exports.Mapper = Mapper;
    Mapper.__name__ = "Mapper";
},
/* models/renderers/glyph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var data_renderer_1 = require(291) /* ./data_renderer */;
    var line_1 = require(292) /* ../glyphs/line */;
    var patch_1 = require(301) /* ../glyphs/patch */;
    var harea_1 = require(302) /* ../glyphs/harea */;
    var varea_1 = require(304) /* ../glyphs/varea */;
    var glyph_1 = require(294) /* ../glyphs/glyph */;
    var columnar_data_source_1 = require(185) /* ../sources/columnar_data_source */;
    var cds_view_1 = require(305) /* ../sources/cds_view */;
    var types_1 = require(139) /* ../../core/types */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var object_1 = require(128) /* ../../core/util/object */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var selection_defaults = {
        fill: {},
        line: {},
    };
    var decimated_defaults = {
        fill: { fill_alpha: 0.3, fill_color: "grey" },
        line: { line_alpha: 0.3, line_color: "grey" },
    };
    var nonselection_defaults = {
        fill: { fill_alpha: 0.2 },
        line: {},
    };
    var hover_defaults = {
        fill: {},
        line: {},
    };
    var muted_defaults = {
        fill: { fill_alpha: 0.2 },
        line: {},
    };
    var GlyphRendererView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GlyphRendererView, _super);
        function GlyphRendererView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(GlyphRendererView.prototype, "glyph_view", {
            get: function () {
                return this.glyph;
            },
            enumerable: false,
            configurable: true
        });
        GlyphRendererView.prototype.lazy_initialize = function () {
            var _b;
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                function mk_glyph(defaults) {
                    var attrs = (0, object_1.clone)(glyph_attrs);
                    if (has_fill)
                        (0, object_1.extend)(attrs, defaults.fill);
                    if (has_line)
                        (0, object_1.extend)(attrs, defaults.line);
                    return new base_glyph.constructor(attrs);
                }
                function glyph_from_mode(defaults, glyph) {
                    if (glyph instanceof glyph_1.Glyph) {
                        return glyph;
                    }
                    else if (glyph == "auto") {
                        return mk_glyph(defaults);
                    }
                    return mk_glyph({ fill: {}, line: {} });
                }
                var base_glyph, _c, has_fill, has_line, glyph_attrs, _d, selection_glyph, nonselection_glyph, hover_glyph, muted_glyph, _e, _f, _g, _h, decimated_glyph, _j;
                return (0, tslib_1.__generator)(this, function (_k) {
                    switch (_k.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _k.sent();
                            base_glyph = this.model.glyph;
                            _c = this;
                            return [4 /*yield*/, this.build_glyph_view(base_glyph)];
                        case 2:
                            _c.glyph = _k.sent();
                            has_fill = "fill" in this.glyph.visuals;
                            has_line = "line" in this.glyph.visuals;
                            glyph_attrs = (0, tslib_1.__assign)({}, base_glyph.attributes);
                            delete glyph_attrs.id;
                            _d = this.model, selection_glyph = _d.selection_glyph, nonselection_glyph = _d.nonselection_glyph, hover_glyph = _d.hover_glyph, muted_glyph = _d.muted_glyph;
                            selection_glyph = glyph_from_mode(selection_defaults, selection_glyph);
                            _e = this;
                            return [4 /*yield*/, this.build_glyph_view(selection_glyph)];
                        case 3:
                            _e.selection_glyph = _k.sent();
                            nonselection_glyph = glyph_from_mode(nonselection_defaults, nonselection_glyph);
                            _f = this;
                            return [4 /*yield*/, this.build_glyph_view(nonselection_glyph)];
                        case 4:
                            _f.nonselection_glyph = _k.sent();
                            hover_glyph = glyph_from_mode(hover_defaults, hover_glyph);
                            _g = this;
                            return [4 /*yield*/, this.build_glyph_view(hover_glyph)];
                        case 5:
                            _g.hover_glyph = _k.sent();
                            muted_glyph = glyph_from_mode(muted_defaults, muted_glyph);
                            _h = this;
                            return [4 /*yield*/, this.build_glyph_view(muted_glyph)];
                        case 6:
                            _h.muted_glyph = _k.sent();
                            decimated_glyph = glyph_from_mode(decimated_defaults, "auto");
                            _j = this;
                            return [4 /*yield*/, this.build_glyph_view(decimated_glyph)];
                        case 7:
                            _j.decimated_glyph = _k.sent();
                            this.selection_glyph.set_base(this.glyph);
                            this.nonselection_glyph.set_base(this.glyph);
                            (_b = this.hover_glyph) === null || _b === void 0 ? void 0 : _b.set_base(this.glyph);
                            this.muted_glyph.set_base(this.glyph);
                            this.decimated_glyph.set_base(this.glyph);
                            this.set_data();
                            return [2 /*return*/];
                    }
                });
            });
        };
        GlyphRendererView.prototype.build_glyph_view = function (glyph) {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_b) {
                    return [2 /*return*/, (0, build_views_1.build_view)(glyph, { parent: this })];
                });
            });
        };
        GlyphRendererView.prototype.remove = function () {
            var _b;
            this.glyph.remove();
            this.selection_glyph.remove();
            this.nonselection_glyph.remove();
            (_b = this.hover_glyph) === null || _b === void 0 ? void 0 : _b.remove();
            this.muted_glyph.remove();
            this.decimated_glyph.remove();
            _super.prototype.remove.call(this);
        };
        GlyphRendererView.prototype.connect_signals = function () {
            var e_1, _b, e_2, _c;
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var render = function () { return _this.request_render(); };
            var update = function () { return _this.update_data(); };
            this.connect(this.model.change, render);
            this.connect(this.glyph.model.change, update);
            this.connect(this.selection_glyph.model.change, update);
            this.connect(this.nonselection_glyph.model.change, update);
            if (this.hover_glyph != null)
                this.connect(this.hover_glyph.model.change, update);
            this.connect(this.muted_glyph.model.change, update);
            this.connect(this.decimated_glyph.model.change, update);
            this.connect(this.model.data_source.change, update);
            this.connect(this.model.data_source.streaming, update);
            this.connect(this.model.data_source.patching, function (indices) { return _this.update_data(indices); });
            this.connect(this.model.data_source.selected.change, render);
            this.connect(this.model.data_source._select, render);
            if (this.hover_glyph != null)
                this.connect(this.model.data_source.inspect, render);
            this.connect(this.model.properties.view.change, update);
            this.connect(this.model.view.properties.indices.change, update);
            this.connect(this.model.view.properties.masked.change, function () { return _this.set_visuals(); });
            this.connect(this.model.properties.visible.change, function () { return _this.plot_view.invalidate_dataranges = true; });
            var _d = this.plot_view.frame, x_ranges = _d.x_ranges, y_ranges = _d.y_ranges;
            try {
                for (var x_ranges_1 = (0, tslib_1.__values)(x_ranges), x_ranges_1_1 = x_ranges_1.next(); !x_ranges_1_1.done; x_ranges_1_1 = x_ranges_1.next()) {
                    var _e = (0, tslib_1.__read)(x_ranges_1_1.value, 2), range = _e[1];
                    if (range instanceof factor_range_1.FactorRange)
                        this.connect(range.change, update);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (x_ranges_1_1 && !x_ranges_1_1.done && (_b = x_ranges_1.return))
                        _b.call(x_ranges_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            try {
                for (var y_ranges_1 = (0, tslib_1.__values)(y_ranges), y_ranges_1_1 = y_ranges_1.next(); !y_ranges_1_1.done; y_ranges_1_1 = y_ranges_1.next()) {
                    var _f = (0, tslib_1.__read)(y_ranges_1_1.value, 2), range = _f[1];
                    if (range instanceof factor_range_1.FactorRange)
                        this.connect(range.change, update);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (y_ranges_1_1 && !y_ranges_1_1.done && (_c = y_ranges_1.return))
                        _c.call(y_ranges_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            var _g = this.model.glyph, transformchange = _g.transformchange, exprchange = _g.exprchange;
            this.connect(transformchange, update);
            this.connect(exprchange, update);
        };
        GlyphRendererView.prototype._update_masked_indices = function () {
            var masked = this.glyph.mask_data();
            this.model.view.masked = masked;
            return masked;
        };
        GlyphRendererView.prototype.update_data = function (indices) {
            this.set_data(indices);
            this.request_render();
        };
        // in case of partial updates like patching, the list of indices that actually
        // changed may be passed as the "indices" parameter to afford any optional optimizations
        GlyphRendererView.prototype.set_data = function (indices) {
            var source = this.model.data_source;
            this.all_indices = this.model.view.indices;
            var all_indices = this.all_indices;
            this.glyph.set_data(source, all_indices, indices);
            this.set_visuals();
            this._update_masked_indices();
            var lod_factor = this.plot_model.lod_factor;
            var n = this.all_indices.count;
            this.decimated = new types_1.Indices(n);
            for (var i = 0; i < n; i += lod_factor) {
                this.decimated.set(i);
            }
            this.plot_view.invalidate_dataranges = true;
        };
        GlyphRendererView.prototype.set_visuals = function () {
            var _b, _c, _d, _e;
            var source = this.model.data_source;
            var all_indices = this.all_indices;
            this.glyph.set_visuals(source, all_indices);
            this.decimated_glyph.set_visuals(source, all_indices);
            (_b = this.selection_glyph) === null || _b === void 0 ? void 0 : _b.set_visuals(source, all_indices);
            (_c = this.nonselection_glyph) === null || _c === void 0 ? void 0 : _c.set_visuals(source, all_indices);
            (_d = this.hover_glyph) === null || _d === void 0 ? void 0 : _d.set_visuals(source, all_indices);
            (_e = this.muted_glyph) === null || _e === void 0 ? void 0 : _e.set_visuals(source, all_indices);
        };
        Object.defineProperty(GlyphRendererView.prototype, "has_webgl", {
            get: function () {
                return this.glyph.has_webgl;
            },
            enumerable: false,
            configurable: true
        });
        GlyphRendererView.prototype._render = function () {
            var e_3, _b, e_4, _c, e_5, _d, e_6, _e, e_7, _f;
            var _this = this;
            var glsupport = this.has_webgl;
            this.glyph.map_data();
            // all_indices is in full data space, indices is converted to subset space by mask_data (that may use the spatial index)
            var all_indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.all_indices), false);
            var indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this._update_masked_indices()), false);
            var ctx = this.layer.ctx;
            ctx.save();
            // selected is in full set space
            var selected = this.model.data_source.selected;
            var selected_full_indices;
            if (!selected || selected.is_empty())
                selected_full_indices = [];
            else {
                if (this.glyph instanceof line_1.LineView && selected.selected_glyph === this.glyph.model)
                    selected_full_indices = this.model.view.convert_indices_from_subset(indices);
                else
                    selected_full_indices = selected.indices;
            }
            // inspected is in full set space
            var inspected = this.model.data_source.inspected;
            var inspected_full_indices = new Set((function () {
                if (!inspected || inspected.is_empty())
                    return [];
                else {
                    if (inspected.selected_glyph)
                        return _this.model.view.convert_indices_from_subset(indices);
                    else if (inspected.indices.length > 0)
                        return inspected.indices;
                    else {
                        // TODO: return inspected.multiline_indices.keys()
                        return Object.keys(inspected.multiline_indices).map(function (i) { return parseInt(i); });
                    }
                }
            })());
            // inspected is transformed to subset space
            var inspected_subset_indices = (0, arrayable_1.filter)(indices, function (i) { return inspected_full_indices.has(all_indices[i]); });
            var lod_threshold = this.plot_model.lod_threshold;
            var glyph;
            var nonselection_glyph;
            var selection_glyph;
            if ((this.model.document != null ? this.model.document.interactive_duration() > 0 : false)
                && !glsupport && lod_threshold != null && all_indices.length > lod_threshold) {
                // Render decimated during interaction if too many elements and not using GL
                indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.decimated), false);
                glyph = this.decimated_glyph;
                nonselection_glyph = this.decimated_glyph;
                selection_glyph = this.selection_glyph;
            }
            else {
                glyph = this.model.muted && this.muted_glyph != null ? this.muted_glyph : this.glyph;
                nonselection_glyph = this.nonselection_glyph;
                selection_glyph = this.selection_glyph;
            }
            if (this.hover_glyph != null && inspected_subset_indices.length) {
                // TODO: keep working on Indices instead of converting back and forth
                var set = new Set(indices);
                try {
                    for (var inspected_subset_indices_1 = (0, tslib_1.__values)(inspected_subset_indices), inspected_subset_indices_1_1 = inspected_subset_indices_1.next(); !inspected_subset_indices_1_1.done; inspected_subset_indices_1_1 = inspected_subset_indices_1.next()) {
                        var i = inspected_subset_indices_1_1.value;
                        set.delete(i);
                    }
                }
                catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                }
                finally {
                    try {
                        if (inspected_subset_indices_1_1 && !inspected_subset_indices_1_1.done && (_b = inspected_subset_indices_1.return))
                            _b.call(inspected_subset_indices_1);
                    }
                    finally {
                        if (e_3)
                            throw e_3.error;
                    }
                }
                indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(set), false);
            }
            // Render with no selection
            if (!selected_full_indices.length) {
                if (this.glyph instanceof line_1.LineView) {
                    if (this.hover_glyph && inspected_subset_indices.length)
                        this.hover_glyph.render(ctx, this.model.view.convert_indices_from_subset(inspected_subset_indices));
                    else
                        glyph.render(ctx, all_indices);
                }
                else if (this.glyph instanceof patch_1.PatchView || this.glyph instanceof harea_1.HAreaView || this.glyph instanceof varea_1.VAreaView) {
                    if (inspected.selected_glyphs.length == 0 || this.hover_glyph == null) {
                        glyph.render(ctx, all_indices);
                    }
                    else {
                        try {
                            for (var _g = (0, tslib_1.__values)(inspected.selected_glyphs), _h = _g.next(); !_h.done; _h = _g.next()) {
                                var sglyph = _h.value;
                                if (sglyph == this.glyph.model)
                                    this.hover_glyph.render(ctx, all_indices);
                            }
                        }
                        catch (e_4_1) {
                            e_4 = { error: e_4_1 };
                        }
                        finally {
                            try {
                                if (_h && !_h.done && (_c = _g.return))
                                    _c.call(_g);
                            }
                            finally {
                                if (e_4)
                                    throw e_4.error;
                            }
                        }
                    }
                }
                else {
                    glyph.render(ctx, indices);
                    if (this.hover_glyph && inspected_subset_indices.length)
                        this.hover_glyph.render(ctx, inspected_subset_indices);
                }
                // Render with selection
            }
            else {
                // reset the selection mask
                var selected_mask = {};
                try {
                    for (var selected_full_indices_1 = (0, tslib_1.__values)(selected_full_indices), selected_full_indices_1_1 = selected_full_indices_1.next(); !selected_full_indices_1_1.done; selected_full_indices_1_1 = selected_full_indices_1.next()) {
                        var i = selected_full_indices_1_1.value;
                        selected_mask[i] = true;
                    }
                }
                catch (e_5_1) {
                    e_5 = { error: e_5_1 };
                }
                finally {
                    try {
                        if (selected_full_indices_1_1 && !selected_full_indices_1_1.done && (_d = selected_full_indices_1.return))
                            _d.call(selected_full_indices_1);
                    }
                    finally {
                        if (e_5)
                            throw e_5.error;
                    }
                }
                // intersect/different selection with render mask
                var selected_subset_indices = new Array();
                var nonselected_subset_indices = new Array();
                // now, selected is changed to subset space, except for Line glyph
                if (this.glyph instanceof line_1.LineView) {
                    try {
                        for (var all_indices_1 = (0, tslib_1.__values)(all_indices), all_indices_1_1 = all_indices_1.next(); !all_indices_1_1.done; all_indices_1_1 = all_indices_1.next()) {
                            var i = all_indices_1_1.value;
                            if (selected_mask[i] != null)
                                selected_subset_indices.push(i);
                            else
                                nonselected_subset_indices.push(i);
                        }
                    }
                    catch (e_6_1) {
                        e_6 = { error: e_6_1 };
                    }
                    finally {
                        try {
                            if (all_indices_1_1 && !all_indices_1_1.done && (_e = all_indices_1.return))
                                _e.call(all_indices_1);
                        }
                        finally {
                            if (e_6)
                                throw e_6.error;
                        }
                    }
                }
                else {
                    try {
                        for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                            var i = indices_1_1.value;
                            if (selected_mask[all_indices[i]] != null)
                                selected_subset_indices.push(i);
                            else
                                nonselected_subset_indices.push(i);
                        }
                    }
                    catch (e_7_1) {
                        e_7 = { error: e_7_1 };
                    }
                    finally {
                        try {
                            if (indices_1_1 && !indices_1_1.done && (_f = indices_1.return))
                                _f.call(indices_1);
                        }
                        finally {
                            if (e_7)
                                throw e_7.error;
                        }
                    }
                }
                nonselection_glyph.render(ctx, nonselected_subset_indices);
                selection_glyph.render(ctx, selected_subset_indices);
                if (this.hover_glyph != null) {
                    if (this.glyph instanceof line_1.LineView)
                        this.hover_glyph.render(ctx, this.model.view.convert_indices_from_subset(inspected_subset_indices));
                    else
                        this.hover_glyph.render(ctx, inspected_subset_indices);
                }
            }
            ctx.restore();
        };
        GlyphRendererView.prototype.draw_legend = function (ctx, x0, x1, y0, y1, field, label, index) {
            if (this.glyph.data_size == 0)
                return;
            if (index == null)
                index = this.model.get_reference_point(field, label);
            this.glyph.draw_legend_for_index(ctx, { x0: x0, x1: x1, y0: y0, y1: y1 }, index);
        };
        GlyphRendererView.prototype.hit_test = function (geometry) {
            if (!this.model.visible)
                return null;
            var hit_test_result = this.glyph.hit_test(geometry);
            // glyphs that don't have hit-testing implemented will return null
            if (hit_test_result == null)
                return null;
            return this.model.view.convert_selection_from_subset(hit_test_result);
        };
        return GlyphRendererView;
    }(data_renderer_1.DataRendererView));
    exports.GlyphRendererView = GlyphRendererView;
    GlyphRendererView.__name__ = "GlyphRendererView";
    var GlyphRenderer = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GlyphRenderer, _super);
        function GlyphRenderer(attrs) {
            return _super.call(this, attrs) || this;
        }
        GlyphRenderer.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            if (this.view.source != this.data_source) {
                this.view.source = this.data_source;
                this.view.compute_indices();
            }
        };
        GlyphRenderer.prototype.get_reference_point = function (field, value) {
            var e_8, _b;
            if (field != null) {
                var data = this.data_source.get_column(field);
                if (data != null) {
                    try {
                        for (var _c = (0, tslib_1.__values)(Object.entries(this.view.indices_map)), _d = _c.next(); !_d.done; _d = _c.next()) {
                            var _e = (0, tslib_1.__read)(_d.value, 2), key = _e[0], index = _e[1];
                            if (data[parseInt(key)] == value)
                                return index;
                        }
                    }
                    catch (e_8_1) {
                        e_8 = { error: e_8_1 };
                    }
                    finally {
                        try {
                            if (_d && !_d.done && (_b = _c.return))
                                _b.call(_c);
                        }
                        finally {
                            if (e_8)
                                throw e_8.error;
                        }
                    }
                }
            }
            return 0;
        };
        GlyphRenderer.prototype.get_selection_manager = function () {
            return this.data_source.selection_manager;
        };
        return GlyphRenderer;
    }(data_renderer_1.DataRenderer));
    exports.GlyphRenderer = GlyphRenderer;
    _a = GlyphRenderer;
    GlyphRenderer.__name__ = "GlyphRenderer";
    (function () {
        _a.prototype.default_view = GlyphRendererView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Auto = _b.Auto, Or = _b.Or, Ref = _b.Ref, Null = _b.Null, Nullable = _b.Nullable;
            return ({
                data_source: [Ref(columnar_data_source_1.ColumnarDataSource)],
                view: [Ref(cds_view_1.CDSView), function (self) { return new cds_view_1.CDSView({ source: self.data_source }); }],
                glyph: [Ref(glyph_1.Glyph)],
                hover_glyph: [Nullable(Ref(glyph_1.Glyph)), null],
                nonselection_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
                selection_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
                muted_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
                muted: [Boolean, false],
            });
        });
    })();
},
/* models/renderers/data_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var renderer_1 = require(156) /* ./renderer */;
    var DataRendererView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DataRendererView, _super);
        function DataRendererView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(DataRendererView.prototype, "xscale", {
            get: function () {
                return this.coordinates.x_scale;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(DataRendererView.prototype, "yscale", {
            get: function () {
                return this.coordinates.y_scale;
            },
            enumerable: false,
            configurable: true
        });
        return DataRendererView;
    }(renderer_1.RendererView));
    exports.DataRendererView = DataRendererView;
    DataRendererView.__name__ = "DataRendererView";
    var DataRenderer = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DataRenderer, _super);
        function DataRenderer(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(DataRenderer.prototype, "selection_manager", {
            get: function () {
                return this.get_selection_manager();
            },
            enumerable: false,
            configurable: true
        });
        return DataRenderer;
    }(renderer_1.Renderer));
    exports.DataRenderer = DataRenderer;
    _a = DataRenderer;
    DataRenderer.__name__ = "DataRenderer";
    (function () {
        _a.override({
            level: "glyph",
        });
    })();
},
/* models/glyphs/line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var utils_1 = require(299) /* ./utils */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var selection_1 = require(187) /* ../selections/selection */;
    var LineView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineView, _super);
        function LineView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LineView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var webgl, LineGL;
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _b.sent();
                            webgl = this.renderer.plot_view.canvas_view.webgl;
                            if (!(webgl === null || webgl === void 0 ? void 0 : webgl.regl_wrapper.has_webgl))
                                return [3 /*break*/, 3];
                            return [4 /*yield*/, Promise.resolve().then(function () { return (0, tslib_1.__importStar)(require(536) /* ./webgl/line_gl */); })];
                        case 2:
                            LineGL = (_b.sent()).LineGL;
                            this.glglyph = new LineGL(webgl.regl_wrapper, this);
                            _b.label = 3;
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        LineView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy;
            var last_i = null;
            var gap = function (i) { return last_i != null && i - last_i != 1; };
            var move = true;
            ctx.beginPath();
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    if (!isFinite(sx_i + sy_i))
                        move = true;
                    else {
                        if (move || gap(i)) {
                            ctx.moveTo(sx_i, sy_i);
                            move = false;
                        }
                        else
                            ctx.lineTo(sx_i, sy_i);
                    }
                    last_i = i;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            this.visuals.line.set_value(ctx);
            ctx.stroke();
        };
        LineView.prototype._hit_point = function (geometry) {
            /* Check if the point geometry hits this line glyph and return an object
            that describes the hit result:
              Args:
                * geometry (object): object with the following keys
                  * sx (float): screen x coordinate of the point
                  * sy (float): screen y coordinate of the point
                  * type (str): type of geometry (in this case it's a point)
            */
            var result = new selection_1.Selection();
            var point = { x: geometry.sx, y: geometry.sy };
            var shortest = 9999;
            var threshold = Math.max(2, this.line_width.value / 2);
            for (var i = 0, end = this.sx.length - 1; i < end; i++) {
                var p0 = { x: this.sx[i], y: this.sy[i] };
                var p1 = { x: this.sx[i + 1], y: this.sy[i + 1] };
                var dist = hittest.dist_to_segment(point, p0, p1);
                if (dist < threshold && dist < shortest) {
                    shortest = dist;
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                }
            }
            return result;
        };
        LineView.prototype._hit_span = function (geometry) {
            var sx = geometry.sx, sy = geometry.sy;
            var result = new selection_1.Selection();
            var val;
            var values;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                values = this._y;
            }
            else {
                val = this.renderer.xscale.invert(sx);
                values = this._x;
            }
            for (var i = 0, end = values.length - 1; i < end; i++) {
                if ((values[i] <= val && val <= values[i + 1]) || (values[i + 1] <= val && val <= values[i])) {
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices.push(i);
                }
            }
            return result;
        };
        LineView.prototype.get_interpolation_hit = function (i, geometry) {
            var _b = (0, tslib_1.__read)([this._x[i], this._y[i], this._x[i + 1], this._y[i + 1]], 4), x2 = _b[0], y2 = _b[1], x3 = _b[2], y3 = _b[3];
            return (0, utils_1.line_interpolation)(this.renderer, geometry, x2, y2, x3, y3);
        };
        LineView.prototype.draw_legend_for_index = function (ctx, bbox, _index) {
            (0, utils_1.generic_line_scalar_legend)(this.visuals, ctx, bbox);
        };
        return LineView;
    }(xy_glyph_1.XYGlyphView));
    exports.LineView = LineView;
    LineView.__name__ = "LineView";
    var Line = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Line, _super);
        function Line(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Line;
    }(xy_glyph_1.XYGlyph));
    exports.Line = Line;
    _a = Line;
    Line.__name__ = "Line";
    (function () {
        _a.prototype.default_view = LineView;
        _a.mixins(mixins.LineScalar);
    })();
},
/* models/glyphs/xy_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var glyph_1 = require(294) /* ./glyph */;
    var XYGlyphView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(XYGlyphView, _super);
        function XYGlyphView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        XYGlyphView.prototype._project_data = function () {
            projections_1.inplace.project_xy(this._x, this._y);
        };
        XYGlyphView.prototype._index_data = function (index) {
            var _b = this, _x = _b._x, _y = _b._y, data_size = _b.data_size;
            for (var i = 0; i < data_size; i++) {
                var x = _x[i];
                var y = _y[i];
                index.add_point(x, y);
            }
        };
        XYGlyphView.prototype.scenterxy = function (i) {
            return [this.sx[i], this.sy[i]];
        };
        return XYGlyphView;
    }(glyph_1.GlyphView));
    exports.XYGlyphView = XYGlyphView;
    XYGlyphView.__name__ = "XYGlyphView";
    var XYGlyph = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(XYGlyph, _super);
        function XYGlyph(attrs) {
            return _super.call(this, attrs) || this;
        }
        return XYGlyph;
    }(glyph_1.Glyph));
    exports.XYGlyph = XYGlyph;
    _a = XYGlyph;
    XYGlyph.__name__ = "XYGlyph";
    (function () {
        _a.define(function (_b) {
            return ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y: [p.YCoordinateSpec, { field: "y" }],
            });
        });
    })();
},
/* models/glyphs/glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var bbox = (0, tslib_1.__importStar)(require(180) /* ../../core/util/bbox */);
    var visuals = (0, tslib_1.__importStar)(require(160) /* ../../core/visuals */);
    var view_1 = require(157) /* ../../core/view */;
    var model_1 = require(168) /* ../../model */;
    var logging_1 = require(134) /* ../../core/logging */;
    var types_1 = require(139) /* ../../core/types */;
    var types_2 = require(125) /* ../../core/util/types */;
    var ragged_array_1 = require(295) /* ../../core/util/ragged_array */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var eq_1 = require(141) /* ../../core/util/eq */;
    var spatial_1 = require(296) /* ../../core/util/spatial */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var selection_1 = require(187) /* ../selections/selection */;
    var abs = Math.abs, ceil = Math.ceil;
    var GlyphView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GlyphView, _super);
        function GlyphView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._index = null;
            _this._data_size = null;
            _this._nohit_warned = new Set();
            return _this;
        }
        Object.defineProperty(GlyphView.prototype, "renderer", {
            get: function () {
                return this.parent;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(GlyphView.prototype, "has_webgl", {
            get: function () {
                return this.glglyph != null;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(GlyphView.prototype, "index", {
            get: function () {
                var _index = this._index;
                if (_index != null)
                    return _index;
                else
                    throw new Error(this + ".index_data() wasn't called");
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(GlyphView.prototype, "data_size", {
            get: function () {
                var _data_size = this._data_size;
                if (_data_size != null)
                    return _data_size;
                else
                    throw new Error(this + ".set_data() wasn't called");
            },
            enumerable: false,
            configurable: true
        });
        GlyphView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.visuals = new visuals.Visuals(this);
        };
        GlyphView.prototype.request_render = function () {
            this.parent.request_render();
        };
        Object.defineProperty(GlyphView.prototype, "canvas", {
            get: function () {
                return this.renderer.parent.canvas_view;
            },
            enumerable: false,
            configurable: true
        });
        GlyphView.prototype.render = function (ctx, indices, data) {
            var _a;
            if (this.glglyph != null) {
                this.renderer.needs_webgl_blit = this.glglyph.render(ctx, indices, (_a = this.base) !== null && _a !== void 0 ? _a : this);
                if (this.renderer.needs_webgl_blit)
                    return;
            }
            this._render(ctx, indices, data !== null && data !== void 0 ? data : this.base);
        };
        GlyphView.prototype.has_finished = function () {
            return true;
        };
        GlyphView.prototype.notify_finished = function () {
            this.renderer.notify_finished();
        };
        GlyphView.prototype._bounds = function (bounds) {
            return bounds;
        };
        GlyphView.prototype.bounds = function () {
            return this._bounds(this.index.bbox);
        };
        GlyphView.prototype.log_bounds = function () {
            var _a = this.index.bounds(bbox.positive_x()), x0 = _a.x0, x1 = _a.x1;
            var _b = this.index.bounds(bbox.positive_y()), y0 = _b.y0, y1 = _b.y1;
            return this._bounds({ x0: x0, y0: y0, x1: x1, y1: y1 });
        };
        GlyphView.prototype.get_anchor_point = function (anchor, i, _a) {
            var _b = (0, tslib_1.__read)(_a, 2), sx = _b[0], sy = _b[1];
            switch (anchor) {
                case "center":
                case "center_center": {
                    var _c = (0, tslib_1.__read)(this.scenterxy(i, sx, sy), 2), x = _c[0], y = _c[1];
                    return { x: x, y: y };
                }
                default:
                    return null;
            }
        };
        /** @deprecated */
        GlyphView.prototype.scenterx = function (i, sx, sy) {
            return this.scenterxy(i, sx, sy)[0];
        };
        /** @deprecated */
        GlyphView.prototype.scentery = function (i, sx, sy) {
            return this.scenterxy(i, sx, sy)[1];
        };
        GlyphView.prototype.sdist = function (scale, pts, spans, pts_location, dilate) {
            if (pts_location === void 0) {
                pts_location = "edge";
            }
            if (dilate === void 0) {
                dilate = false;
            }
            var n = pts.length;
            var sdist = new types_1.ScreenArray(n);
            var compute = scale.s_compute;
            if (pts_location == "center") {
                for (var i = 0; i < n; i++) {
                    var pts_i = pts[i];
                    var halfspan_i = spans.get(i) / 2;
                    var spt0 = compute(pts_i - halfspan_i);
                    var spt1 = compute(pts_i + halfspan_i);
                    sdist[i] = abs(spt1 - spt0);
                }
            }
            else {
                for (var i = 0; i < n; i++) {
                    var pts_i = pts[i];
                    var spt0 = compute(pts_i);
                    var spt1 = compute(pts_i + spans.get(i));
                    sdist[i] = abs(spt1 - spt0);
                }
            }
            if (dilate)
                (0, arrayable_1.inplace_map)(sdist, function (sd) { return ceil(sd); });
            return sdist;
        };
        GlyphView.prototype.draw_legend_for_index = function (_ctx, _bbox, _index) { };
        GlyphView.prototype.hit_test = function (geometry) {
            switch (geometry.type) {
                case "point":
                    if (this._hit_point != null)
                        return this._hit_point(geometry);
                    break;
                case "span":
                    if (this._hit_span != null)
                        return this._hit_span(geometry);
                    break;
                case "rect":
                    if (this._hit_rect != null)
                        return this._hit_rect(geometry);
                    break;
                case "poly":
                    if (this._hit_poly != null)
                        return this._hit_poly(geometry);
                    break;
            }
            if (!this._nohit_warned.has(geometry.type)) {
                logging_1.logger.debug("'" + geometry.type + "' selection not available for " + this.model.type);
                this._nohit_warned.add(geometry.type);
            }
            return null;
        };
        GlyphView.prototype._hit_rect_against_index = function (geometry) {
            var sx0 = geometry.sx0, sx1 = geometry.sx1, sy0 = geometry.sy0, sy1 = geometry.sy1;
            var _a = (0, tslib_1.__read)(this.renderer.coordinates.x_scale.r_invert(sx0, sx1), 2), x0 = _a[0], x1 = _a[1];
            var _b = (0, tslib_1.__read)(this.renderer.coordinates.y_scale.r_invert(sy0, sy1), 2), y0 = _b[0], y1 = _b[1];
            var indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), false);
            return new selection_1.Selection({ indices: indices });
        };
        GlyphView.prototype._project_data = function () { };
        GlyphView.prototype._iter_visuals = function () {
            var _a, _b, visual, visual_1, visual_1_1, prop, e_1_1, e_2_1;
            var e_2, _c, e_1, _d;
            return (0, tslib_1.__generator)(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        _e.trys.push([0, 11, 12, 13]);
                        _a = (0, tslib_1.__values)(this.visuals), _b = _a.next();
                        _e.label = 1;
                    case 1:
                        if (!!_b.done)
                            return [3 /*break*/, 10];
                        visual = _b.value;
                        _e.label = 2;
                    case 2:
                        _e.trys.push([2, 7, 8, 9]);
                        visual_1 = (e_1 = void 0, (0, tslib_1.__values)(visual)), visual_1_1 = visual_1.next();
                        _e.label = 3;
                    case 3:
                        if (!!visual_1_1.done)
                            return [3 /*break*/, 6];
                        prop = visual_1_1.value;
                        if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                            return [3 /*break*/, 5];
                        return [4 /*yield*/, prop];
                    case 4:
                        _e.sent();
                        _e.label = 5;
                    case 5:
                        visual_1_1 = visual_1.next();
                        return [3 /*break*/, 3];
                    case 6: return [3 /*break*/, 9];
                    case 7:
                        e_1_1 = _e.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 9];
                    case 8:
                        try {
                            if (visual_1_1 && !visual_1_1.done && (_d = visual_1.return))
                                _d.call(visual_1);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                        return [7 /*endfinally*/];
                    case 9:
                        _b = _a.next();
                        return [3 /*break*/, 1];
                    case 10: return [3 /*break*/, 13];
                    case 11:
                        e_2_1 = _e.sent();
                        e_2 = { error: e_2_1 };
                        return [3 /*break*/, 13];
                    case 12:
                        try {
                            if (_b && !_b.done && (_c = _a.return))
                                _c.call(_a);
                        }
                        finally {
                            if (e_2)
                                throw e_2.error;
                        }
                        return [7 /*endfinally*/];
                    case 13: return [2 /*return*/];
                }
            });
        };
        GlyphView.prototype.set_base = function (base) {
            if (base != this && base instanceof this.constructor)
                this.base = base;
        };
        GlyphView.prototype._configure = function (prop, descriptor) {
            Object.defineProperty(this, (0, types_2.isString)(prop) ? prop : prop.attr, (0, tslib_1.__assign)({ configurable: true, enumerable: true }, descriptor));
        };
        GlyphView.prototype.set_visuals = function (source, indices) {
            var e_3, _a, e_4, _b;
            var _c;
            var _loop_1 = function (prop) {
                var base = this_1.base;
                if (base != null) {
                    var base_prop = base.model.properties[prop.attr];
                    if (base_prop != null && (0, eq_1.is_equal)(prop.get_value(), base_prop.get_value())) {
                        this_1._configure(prop, {
                            get: function () { return base["" + prop.attr]; },
                        });
                        return "continue";
                    }
                }
                var uniform = prop.uniform(source).select(indices);
                this_1._configure(prop, { value: uniform });
            };
            var this_1 = this;
            try {
                for (var _d = (0, tslib_1.__values)(this._iter_visuals()), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var prop = _e.value;
                    _loop_1(prop);
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_a = _d.return))
                        _a.call(_d);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            try {
                for (var _f = (0, tslib_1.__values)(this.visuals), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var visual = _g.value;
                    visual.update();
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_b = _f.return))
                        _b.call(_f);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            this._set_visuals();
            (_c = this.glglyph) === null || _c === void 0 ? void 0 : _c.set_visuals_changed();
        };
        GlyphView.prototype._set_visuals = function () { };
        GlyphView.prototype.set_data = function (source, indices, indices_to_update) {
            var e_5, _a;
            var _b;
            var _c = this.renderer.coordinates, x_source = _c.x_source, y_source = _c.y_source;
            var visual_props = new Set(this._iter_visuals());
            this._data_size = indices.count;
            try {
                for (var _d = (0, tslib_1.__values)(this.model), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var prop = _e.value;
                    if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                        continue;
                    if (visual_props.has(prop)) // let set_visuals() do the work, at least for now
                        continue;
                    if (prop instanceof p.BaseCoordinateSpec) {
                        var base_array = prop.array(source);
                        var array = indices.select(base_array);
                        var range = prop.dimension == "x" ? x_source : y_source;
                        if (range instanceof factor_range_1.FactorRange) {
                            if (prop instanceof p.CoordinateSpec) {
                                array = range.v_synthetic(array);
                            }
                            else if (prop instanceof p.CoordinateSeqSpec) {
                                for (var i = 0; i < array.length; i++) {
                                    array[i] = range.v_synthetic(array[i]);
                                }
                            }
                        }
                        var final_array = void 0;
                        if (prop instanceof p.CoordinateSeqSpec) {
                            // TODO: infer precision
                            final_array = ragged_array_1.RaggedArray.from(array, Float64Array);
                        }
                        else
                            final_array = array;
                        this._configure("_" + prop.attr, { value: final_array });
                    }
                    else {
                        var uniform = prop.uniform(source).select(indices);
                        this._configure(prop, { value: uniform });
                        if (prop instanceof p.DistanceSpec) {
                            var max_value = uniform.is_Scalar() ? uniform.value : (0, arrayable_1.max)(uniform.array);
                            this._configure("max_" + prop.attr, { value: max_value });
                        }
                    }
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_a = _d.return))
                        _a.call(_d);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            if (this.renderer.plot_view.model.use_map) {
                this._project_data();
            }
            this._set_data(indices_to_update !== null && indices_to_update !== void 0 ? indices_to_update : null); // TODO doesn't take subset indices into account
            (_b = this.glglyph) === null || _b === void 0 ? void 0 : _b.set_data_changed();
            this.index_data();
        };
        GlyphView.prototype._set_data = function (_indices) { };
        Object.defineProperty(GlyphView.prototype, "_index_size", {
            get: function () {
                return this.data_size;
            },
            enumerable: false,
            configurable: true
        });
        GlyphView.prototype.index_data = function () {
            var index = new spatial_1.SpatialIndex(this._index_size);
            this._index_data(index);
            index.finish();
            this._index = index;
        };
        GlyphView.prototype.mask_data = function () {
            /** Returns subset indices in the viewport. */
            if (this._mask_data == null)
                return types_1.Indices.all_set(this.data_size);
            else
                return this._mask_data();
        };
        GlyphView.prototype.map_data = function () {
            var e_6, _a;
            var _b;
            var self = this;
            var _c = this.renderer.coordinates, x_scale = _c.x_scale, y_scale = _c.y_scale;
            try {
                for (var _d = (0, tslib_1.__values)(this.model), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var prop = _e.value;
                    if (prop instanceof p.BaseCoordinateSpec) {
                        var scale = prop.dimension == "x" ? x_scale : y_scale;
                        var array = self["_" + prop.attr];
                        if (array instanceof ragged_array_1.RaggedArray) {
                            var screen = scale.v_compute(array.array);
                            array = new ragged_array_1.RaggedArray(array.offsets, screen);
                        }
                        else {
                            array = scale.v_compute(array);
                        }
                        this["s" + prop.attr] = array;
                    }
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_a = _d.return))
                        _a.call(_d);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            this._map_data();
            (_b = this.glglyph) === null || _b === void 0 ? void 0 : _b.set_data_changed();
        };
        // This is where specs not included in coords are computed, e.g. radius.
        GlyphView.prototype._map_data = function () { };
        return GlyphView;
    }(view_1.View));
    exports.GlyphView = GlyphView;
    GlyphView.__name__ = "GlyphView";
    var Glyph = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Glyph, _super);
        function Glyph(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Glyph;
    }(model_1.Model));
    exports.Glyph = Glyph;
    Glyph.__name__ = "Glyph";
},
/* core/util/ragged_array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var eq_1 = require(141) /* ./eq */;
    var assert_1 = require(127) /* ./assert */;
    var RaggedArray = /** @class */ (function () {
        function RaggedArray(offsets, array) {
            this.offsets = offsets;
            this.array = array;
        }
        RaggedArray.prototype[(_a = Symbol.toStringTag, eq_1.equals)] = function (that, cmp) {
            return cmp.arrays(this.offsets, that.offsets) && cmp.arrays(this.array, that.array);
        };
        Object.defineProperty(RaggedArray.prototype, "length", {
            get: function () {
                return this.offsets.length;
            },
            enumerable: false,
            configurable: true
        });
        RaggedArray.prototype.clone = function () {
            return new RaggedArray(this.offsets.slice(), this.array.slice());
        };
        RaggedArray.from = function (items, ctor) {
            var n = items.length;
            var offset = 0;
            var offsets = (function () {
                var offsets = new Uint32Array(n);
                for (var i = 0; i < n; i++) {
                    var length = items[i].length;
                    offsets[i] = offset;
                    offset += length;
                }
                if (offset < 256)
                    return new Uint8Array(offsets);
                else if (offset < 65536)
                    return new Uint16Array(offsets);
                else
                    return offsets;
            })();
            var array = new ctor(offset);
            for (var i = 0; i < n; i++) {
                array.set(items[i], offsets[i]);
            }
            return new RaggedArray(offsets, array);
        };
        RaggedArray.prototype[Symbol.iterator] = function () {
            var _b, offsets, length, i;
            return (0, tslib_1.__generator)(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _b = this, offsets = _b.offsets, length = _b.length;
                        i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(i < length))
                            return [3 /*break*/, 4];
                        return [4 /*yield*/, this.array.subarray(offsets[i], offsets[i + 1])];
                    case 2:
                        _c.sent();
                        _c.label = 3;
                    case 3:
                        i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        };
        RaggedArray.prototype._check_bounds = function (i) {
            (0, assert_1.assert)(0 <= i && i < this.length, "Out of bounds: 0 <= " + i + " < " + this.length);
        };
        RaggedArray.prototype.get = function (i) {
            this._check_bounds(i);
            var offsets = this.offsets;
            return this.array.subarray(offsets[i], offsets[i + 1]);
        };
        RaggedArray.prototype.set = function (i, array) {
            this._check_bounds(i);
            this.array.set(array, this.offsets[i]);
        };
        return RaggedArray;
    }());
    exports.RaggedArray = RaggedArray;
    RaggedArray.__name__ = "RaggedArray";
    RaggedArray[_a] = "RaggedArray";
},
/* core/util/spatial.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var flatbush_1 = (0, tslib_1.__importDefault)(require(297) /* flatbush */);
    var types_1 = require(139) /* ../types */;
    var bbox_1 = require(180) /* ./bbox */;
    function upperBound(value, arr) {
        var i = 0;
        var j = arr.length - 1;
        while (i < j) {
            var m = (i + j) >> 1;
            if (arr[m] > value) {
                j = m;
            }
            else {
                i = m + 1;
            }
        }
        return arr[i];
    }
    var _FlatBush = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(_FlatBush, _super);
        function _FlatBush() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(_FlatBush.prototype, "boxes", {
            get: function () {
                return this._boxes;
            },
            enumerable: false,
            configurable: true
        });
        _FlatBush.prototype.search_indices = function (minX, minY, maxX, maxY) {
            if (this._pos !== this._boxes.length) {
                throw new Error("Data not yet indexed - call index.finish().");
            }
            var nodeIndex = this._boxes.length - 4;
            var queue = [];
            var results = new types_1.Indices(this.numItems);
            while (nodeIndex !== undefined) {
                // find the end index of the node
                var end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // search through child nodes
                for (var pos = nodeIndex; pos < end; pos += 4) {
                    var index = this._indices[pos >> 2] | 0;
                    // check if node bbox intersects with query bbox
                    var nodeMinX = this._boxes[pos + 0];
                    var nodeMinY = this._boxes[pos + 1];
                    var nodeMaxX = this._boxes[pos + 2];
                    var nodeMaxY = this._boxes[pos + 3];
                    if (maxX < nodeMinX)
                        continue;
                    if (maxY < nodeMinY)
                        continue;
                    if (minX > nodeMaxX)
                        continue;
                    if (minY > nodeMaxY)
                        continue;
                    if (nodeIndex < this.numItems * 4) {
                        results.set(index); // leaf item
                    }
                    else {
                        queue.push(index); // node; add it to the search queue
                    }
                }
                nodeIndex = queue.pop();
            }
            return results;
        };
        return _FlatBush;
    }(flatbush_1.default));
    _FlatBush.__name__ = "_FlatBush";
    var SpatialIndex = /** @class */ (function () {
        function SpatialIndex(size) {
            this.index = null;
            if (size > 0) {
                this.index = new _FlatBush(size);
            }
        }
        SpatialIndex.prototype.add_rect = function (x0, y0, x1, y1) {
            var _a;
            if (!isFinite(x0 + y0 + x1 + y1))
                this.add_empty();
            else
                (_a = this.index) === null || _a === void 0 ? void 0 : _a.add(x0, y0, x1, y1);
        };
        SpatialIndex.prototype.add_point = function (x, y) {
            var _a;
            if (!isFinite(x + y))
                this.add_empty();
            else
                (_a = this.index) === null || _a === void 0 ? void 0 : _a.add(x, y, x, y);
        };
        SpatialIndex.prototype.add_empty = function () {
            var _a;
            (_a = this.index) === null || _a === void 0 ? void 0 : _a.add(Infinity, Infinity, -Infinity, -Infinity);
        };
        SpatialIndex.prototype.finish = function () {
            var _a;
            (_a = this.index) === null || _a === void 0 ? void 0 : _a.finish();
        };
        SpatialIndex.prototype._normalize = function (rect) {
            var _a, _b;
            var x0 = rect.x0, y0 = rect.y0, x1 = rect.x1, y1 = rect.y1;
            if (x0 > x1)
                _a = (0, tslib_1.__read)([x1, x0], 2), x0 = _a[0], x1 = _a[1];
            if (y0 > y1)
                _b = (0, tslib_1.__read)([y1, y0], 2), y0 = _b[0], y1 = _b[1];
            return { x0: x0, y0: y0, x1: x1, y1: y1 };
        };
        Object.defineProperty(SpatialIndex.prototype, "bbox", {
            get: function () {
                if (this.index == null)
                    return (0, bbox_1.empty)();
                else {
                    var _a = this.index, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY;
                    return { x0: minX, y0: minY, x1: maxX, y1: maxY };
                }
            },
            enumerable: false,
            configurable: true
        });
        SpatialIndex.prototype.indices = function (rect) {
            if (this.index == null)
                return new types_1.Indices(0);
            else {
                var _a = this._normalize(rect), x0 = _a.x0, y0 = _a.y0, x1 = _a.x1, y1 = _a.y1;
                return this.index.search_indices(x0, y0, x1, y1);
            }
        };
        SpatialIndex.prototype.bounds = function (rect) {
            var e_1, _a;
            var bounds = (0, bbox_1.empty)();
            if (this.index == null)
                return bounds;
            var boxes = this.index.boxes;
            try {
                for (var _b = (0, tslib_1.__values)(this.indices(rect)), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var i = _c.value;
                    var x0 = boxes[4 * i + 0];
                    var y0 = boxes[4 * i + 1];
                    var x1 = boxes[4 * i + 2];
                    var y1 = boxes[4 * i + 3];
                    if (x0 >= rect.x0 && x0 < bounds.x0)
                        bounds.x0 = x0;
                    if (x1 <= rect.x1 && x1 > bounds.x1)
                        bounds.x1 = x1;
                    if (y0 >= rect.y0 && y0 < bounds.y0)
                        bounds.y0 = y0;
                    if (y1 <= rect.y1 && y1 > bounds.y1)
                        bounds.y1 = y1;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return bounds;
        };
        return SpatialIndex;
    }());
    exports.SpatialIndex = SpatialIndex;
    SpatialIndex.__name__ = "SpatialIndex";
},
/* flatbush/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var flatqueue_1 = (0, tslib_1.__importDefault)(require(298) /* flatqueue */);
    var ARRAY_TYPES = [
        Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
        Int32Array, Uint32Array, Float32Array, Float64Array
    ];
    var VERSION = 3; // serialized format version
    var Flatbush = /** @class */ (function () {
        function Flatbush(numItems, nodeSize, ArrayType, data) {
            if (nodeSize === void 0) {
                nodeSize = 16;
            }
            if (ArrayType === void 0) {
                ArrayType = Float64Array;
            }
            if (numItems === undefined)
                throw new Error('Missing required argument: numItems.');
            if (isNaN(numItems) || numItems <= 0)
                throw new Error("Unpexpected numItems value: " + numItems + ".");
            this.numItems = +numItems;
            this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
            // calculate the total number of nodes in the R-tree to allocate space for
            // and the index of each tree level (used in search later)
            var n = numItems;
            var numNodes = n;
            this._levelBounds = [n * 4];
            do {
                n = Math.ceil(n / this.nodeSize);
                numNodes += n;
                this._levelBounds.push(numNodes * 4);
            } while (n !== 1);
            this.ArrayType = ArrayType || Float64Array;
            this.IndexArrayType = numNodes < 16384 ? Uint16Array : Uint32Array;
            var arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
            var nodesByteSize = numNodes * 4 * this.ArrayType.BYTES_PER_ELEMENT;
            if (arrayTypeIndex < 0) {
                throw new Error("Unexpected typed array class: " + ArrayType + ".");
            }
            if (data && (data instanceof ArrayBuffer)) {
                this.data = data;
                this._boxes = new this.ArrayType(this.data, 8, numNodes * 4);
                this._indices = new this.IndexArrayType(this.data, 8 + nodesByteSize, numNodes);
                this._pos = numNodes * 4;
                this.minX = this._boxes[this._pos - 4];
                this.minY = this._boxes[this._pos - 3];
                this.maxX = this._boxes[this._pos - 2];
                this.maxY = this._boxes[this._pos - 1];
            }
            else {
                this.data = new ArrayBuffer(8 + nodesByteSize + numNodes * this.IndexArrayType.BYTES_PER_ELEMENT);
                this._boxes = new this.ArrayType(this.data, 8, numNodes * 4);
                this._indices = new this.IndexArrayType(this.data, 8 + nodesByteSize, numNodes);
                this._pos = 0;
                this.minX = Infinity;
                this.minY = Infinity;
                this.maxX = -Infinity;
                this.maxY = -Infinity;
                new Uint8Array(this.data, 0, 2).set([0xfb, (VERSION << 4) + arrayTypeIndex]);
                new Uint16Array(this.data, 2, 1)[0] = nodeSize;
                new Uint32Array(this.data, 4, 1)[0] = numItems;
            }
            // a priority queue for k-nearest-neighbors queries
            this._queue = new flatqueue_1.default();
        }
        Flatbush.from = function (data) {
            if (!(data instanceof ArrayBuffer)) {
                throw new Error('Data must be an instance of ArrayBuffer.');
            }
            var _a = (0, tslib_1.__read)(new Uint8Array(data, 0, 2), 2), magic = _a[0], versionAndType = _a[1];
            if (magic !== 0xfb) {
                throw new Error('Data does not appear to be in a Flatbush format.');
            }
            if (versionAndType >> 4 !== VERSION) {
                throw new Error("Got v" + (versionAndType >> 4) + " data when expected v" + VERSION + ".");
            }
            var _b = (0, tslib_1.__read)(new Uint16Array(data, 2, 1), 1), nodeSize = _b[0];
            var _c = (0, tslib_1.__read)(new Uint32Array(data, 4, 1), 1), numItems = _c[0];
            return new Flatbush(numItems, nodeSize, ARRAY_TYPES[versionAndType & 0x0f], data);
        };
        Flatbush.prototype.add = function (minX, minY, maxX, maxY) {
            var index = this._pos >> 2;
            this._indices[index] = index;
            this._boxes[this._pos++] = minX;
            this._boxes[this._pos++] = minY;
            this._boxes[this._pos++] = maxX;
            this._boxes[this._pos++] = maxY;
            if (minX < this.minX)
                this.minX = minX;
            if (minY < this.minY)
                this.minY = minY;
            if (maxX > this.maxX)
                this.maxX = maxX;
            if (maxY > this.maxY)
                this.maxY = maxY;
            return index;
        };
        Flatbush.prototype.finish = function () {
            if (this._pos >> 2 !== this.numItems) {
                throw new Error("Added " + (this._pos >> 2) + " items when expected " + this.numItems + ".");
            }
            if (this.numItems <= this.nodeSize) {
                // only one node, skip sorting and just fill the root box
                this._boxes[this._pos++] = this.minX;
                this._boxes[this._pos++] = this.minY;
                this._boxes[this._pos++] = this.maxX;
                this._boxes[this._pos++] = this.maxY;
                return;
            }
            var width = this.maxX - this.minX;
            var height = this.maxY - this.minY;
            var hilbertValues = new Uint32Array(this.numItems);
            var hilbertMax = (1 << 16) - 1;
            // map item centers into Hilbert coordinate space and calculate Hilbert values
            for (var i = 0; i < this.numItems; i++) {
                var pos = 4 * i;
                var minX = this._boxes[pos++];
                var minY = this._boxes[pos++];
                var maxX = this._boxes[pos++];
                var maxY = this._boxes[pos++];
                var x = Math.floor(hilbertMax * ((minX + maxX) / 2 - this.minX) / width);
                var y = Math.floor(hilbertMax * ((minY + maxY) / 2 - this.minY) / height);
                hilbertValues[i] = hilbert(x, y);
            }
            // sort items by their Hilbert value (for packing later)
            sort(hilbertValues, this._boxes, this._indices, 0, this.numItems - 1, this.nodeSize);
            // generate nodes at each tree level, bottom-up
            for (var i = 0, pos = 0; i < this._levelBounds.length - 1; i++) {
                var end = this._levelBounds[i];
                // generate a parent node for each block of consecutive <nodeSize> nodes
                while (pos < end) {
                    var nodeIndex = pos;
                    // calculate bbox for the new node
                    var nodeMinX = Infinity;
                    var nodeMinY = Infinity;
                    var nodeMaxX = -Infinity;
                    var nodeMaxY = -Infinity;
                    for (var i_1 = 0; i_1 < this.nodeSize && pos < end; i_1++) {
                        nodeMinX = Math.min(nodeMinX, this._boxes[pos++]);
                        nodeMinY = Math.min(nodeMinY, this._boxes[pos++]);
                        nodeMaxX = Math.max(nodeMaxX, this._boxes[pos++]);
                        nodeMaxY = Math.max(nodeMaxY, this._boxes[pos++]);
                    }
                    // add the new node to the tree data
                    this._indices[this._pos >> 2] = nodeIndex;
                    this._boxes[this._pos++] = nodeMinX;
                    this._boxes[this._pos++] = nodeMinY;
                    this._boxes[this._pos++] = nodeMaxX;
                    this._boxes[this._pos++] = nodeMaxY;
                }
            }
        };
        Flatbush.prototype.search = function (minX, minY, maxX, maxY, filterFn) {
            if (this._pos !== this._boxes.length) {
                throw new Error('Data not yet indexed - call index.finish().');
            }
            var nodeIndex = this._boxes.length - 4;
            var queue = [];
            var results = [];
            while (nodeIndex !== undefined) {
                // find the end index of the node
                var end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // search through child nodes
                for (var pos = nodeIndex; pos < end; pos += 4) {
                    var index = this._indices[pos >> 2] | 0;
                    // check if node bbox intersects with query bbox
                    if (maxX < this._boxes[pos])
                        continue; // maxX < nodeMinX
                    if (maxY < this._boxes[pos + 1])
                        continue; // maxY < nodeMinY
                    if (minX > this._boxes[pos + 2])
                        continue; // minX > nodeMaxX
                    if (minY > this._boxes[pos + 3])
                        continue; // minY > nodeMaxY
                    if (nodeIndex < this.numItems * 4) {
                        if (filterFn === undefined || filterFn(index)) {
                            results.push(index); // leaf item
                        }
                    }
                    else {
                        queue.push(index); // node; add it to the search queue
                    }
                }
                nodeIndex = queue.pop();
            }
            return results;
        };
        Flatbush.prototype.neighbors = function (x, y, maxResults, maxDistance, filterFn) {
            if (maxResults === void 0) {
                maxResults = Infinity;
            }
            if (maxDistance === void 0) {
                maxDistance = Infinity;
            }
            if (this._pos !== this._boxes.length) {
                throw new Error('Data not yet indexed - call index.finish().');
            }
            var nodeIndex = this._boxes.length - 4;
            var q = this._queue;
            var results = [];
            var maxDistSquared = maxDistance * maxDistance;
            while (nodeIndex !== undefined) {
                // find the end index of the node
                var end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // add child nodes to the queue
                for (var pos = nodeIndex; pos < end; pos += 4) {
                    var index = this._indices[pos >> 2] | 0;
                    var dx = axisDist(x, this._boxes[pos], this._boxes[pos + 2]);
                    var dy = axisDist(y, this._boxes[pos + 1], this._boxes[pos + 3]);
                    var dist = dx * dx + dy * dy;
                    if (nodeIndex < this.numItems * 4) { // leaf node
                        if (filterFn === undefined || filterFn(index)) {
                            // put a negative index if it's an item rather than a node, to recognize later
                            q.push(-index - 1, dist);
                        }
                    }
                    else {
                        q.push(index, dist);
                    }
                }
                // pop items from the queue
                while (q.length && q.peek() < 0) {
                    var dist = q.peekValue();
                    if (dist > maxDistSquared) {
                        q.clear();
                        return results;
                    }
                    results.push(-q.pop() - 1);
                    if (results.length === maxResults) {
                        q.clear();
                        return results;
                    }
                }
                nodeIndex = q.pop();
            }
            q.clear();
            return results;
        };
        return Flatbush;
    }());
    exports.default = Flatbush;
    function axisDist(k, min, max) {
        return k < min ? min - k : k <= max ? 0 : k - max;
    }
    // binary search for the first value in the array bigger than the given
    function upperBound(value, arr) {
        var i = 0;
        var j = arr.length - 1;
        while (i < j) {
            var m = (i + j) >> 1;
            if (arr[m] > value) {
                j = m;
            }
            else {
                i = m + 1;
            }
        }
        return arr[i];
    }
    // custom quicksort that partially sorts bbox data alongside the hilbert values
    function sort(values, boxes, indices, left, right, nodeSize) {
        if (Math.floor(left / nodeSize) >= Math.floor(right / nodeSize))
            return;
        var pivot = values[(left + right) >> 1];
        var i = left - 1;
        var j = right + 1;
        while (true) {
            do
                i++;
            while (values[i] < pivot);
            do
                j--;
            while (values[j] > pivot);
            if (i >= j)
                break;
            swap(values, boxes, indices, i, j);
        }
        sort(values, boxes, indices, left, j, nodeSize);
        sort(values, boxes, indices, j + 1, right, nodeSize);
    }
    // swap two values and two corresponding boxes
    function swap(values, boxes, indices, i, j) {
        var temp = values[i];
        values[i] = values[j];
        values[j] = temp;
        var k = 4 * i;
        var m = 4 * j;
        var a = boxes[k];
        var b = boxes[k + 1];
        var c = boxes[k + 2];
        var d = boxes[k + 3];
        boxes[k] = boxes[m];
        boxes[k + 1] = boxes[m + 1];
        boxes[k + 2] = boxes[m + 2];
        boxes[k + 3] = boxes[m + 3];
        boxes[m] = a;
        boxes[m + 1] = b;
        boxes[m + 2] = c;
        boxes[m + 3] = d;
        var e = indices[i];
        indices[i] = indices[j];
        indices[j] = e;
    }
    // Fast Hilbert curve algorithm by http://threadlocalmutex.com/
    // Ported from C++ https://github.com/rawrunprotected/hilbert_curves (public domain)
    function hilbert(x, y) {
        var a = x ^ y;
        var b = 0xFFFF ^ a;
        var c = 0xFFFF ^ (x | y);
        var d = x & (y ^ 0xFFFF);
        var A = a | (b >> 1);
        var B = (a >> 1) ^ a;
        var C = ((c >> 1) ^ (b & (d >> 1))) ^ c;
        var D = ((a & (c >> 1)) ^ (d >> 1)) ^ d;
        a = A;
        b = B;
        c = C;
        d = D;
        A = ((a & (a >> 2)) ^ (b & (b >> 2)));
        B = ((a & (b >> 2)) ^ (b & ((a ^ b) >> 2)));
        C ^= ((a & (c >> 2)) ^ (b & (d >> 2)));
        D ^= ((b & (c >> 2)) ^ ((a ^ b) & (d >> 2)));
        a = A;
        b = B;
        c = C;
        d = D;
        A = ((a & (a >> 4)) ^ (b & (b >> 4)));
        B = ((a & (b >> 4)) ^ (b & ((a ^ b) >> 4)));
        C ^= ((a & (c >> 4)) ^ (b & (d >> 4)));
        D ^= ((b & (c >> 4)) ^ ((a ^ b) & (d >> 4)));
        a = A;
        b = B;
        c = C;
        d = D;
        C ^= ((a & (c >> 8)) ^ (b & (d >> 8)));
        D ^= ((b & (c >> 8)) ^ ((a ^ b) & (d >> 8)));
        a = C ^ (C >> 1);
        b = D ^ (D >> 1);
        var i0 = x ^ y;
        var i1 = b | (0xFFFF ^ (i0 | a));
        i0 = (i0 | (i0 << 8)) & 0x00FF00FF;
        i0 = (i0 | (i0 << 4)) & 0x0F0F0F0F;
        i0 = (i0 | (i0 << 2)) & 0x33333333;
        i0 = (i0 | (i0 << 1)) & 0x55555555;
        i1 = (i1 | (i1 << 8)) & 0x00FF00FF;
        i1 = (i1 | (i1 << 4)) & 0x0F0F0F0F;
        i1 = (i1 | (i1 << 2)) & 0x33333333;
        i1 = (i1 | (i1 << 1)) & 0x55555555;
        return ((i1 << 1) | i0) >>> 0;
    }
},
/* flatqueue/index.mjs */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var FlatQueue = /** @class */ (function () {
        function FlatQueue() {
            this.ids = [];
            this.values = [];
            this.length = 0;
        }
        FlatQueue.prototype.clear = function () {
            this.length = 0;
        };
        FlatQueue.prototype.push = function (id, value) {
            var pos = this.length++;
            this.ids[pos] = id;
            this.values[pos] = value;
            while (pos > 0) {
                var parent = (pos - 1) >> 1;
                var parentValue = this.values[parent];
                if (value >= parentValue)
                    break;
                this.ids[pos] = this.ids[parent];
                this.values[pos] = parentValue;
                pos = parent;
            }
            this.ids[pos] = id;
            this.values[pos] = value;
        };
        FlatQueue.prototype.pop = function () {
            if (this.length === 0)
                return undefined;
            var top = this.ids[0];
            this.length--;
            if (this.length > 0) {
                var id = this.ids[0] = this.ids[this.length];
                var value = this.values[0] = this.values[this.length];
                var halfLength = this.length >> 1;
                var pos = 0;
                while (pos < halfLength) {
                    var left = (pos << 1) + 1;
                    var right = left + 1;
                    var bestIndex = this.ids[left];
                    var bestValue = this.values[left];
                    var rightValue = this.values[right];
                    if (right < this.length && rightValue < bestValue) {
                        left = right;
                        bestIndex = this.ids[right];
                        bestValue = rightValue;
                    }
                    if (bestValue >= value)
                        break;
                    this.ids[pos] = bestIndex;
                    this.values[pos] = bestValue;
                    pos = left;
                }
                this.ids[pos] = id;
                this.values[pos] = value;
            }
            return top;
        };
        FlatQueue.prototype.peek = function () {
            if (this.length === 0)
                return undefined;
            return this.ids[0];
        };
        FlatQueue.prototype.peekValue = function () {
            if (this.length === 0)
                return undefined;
            return this.values[0];
        };
        return FlatQueue;
    }());
    exports.default = FlatQueue;
},
/* models/glyphs/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    function generic_line_scalar_legend(visuals, ctx, _a) {
        var x0 = _a.x0, x1 = _a.x1, y0 = _a.y0, y1 = _a.y1;
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x0, (y0 + y1) / 2);
        ctx.lineTo(x1, (y0 + y1) / 2);
        visuals.line.apply(ctx);
        ctx.restore();
    }
    exports.generic_line_scalar_legend = generic_line_scalar_legend;
    function generic_line_vector_legend(visuals, ctx, _a, i) {
        var x0 = _a.x0, x1 = _a.x1, y0 = _a.y0, y1 = _a.y1;
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x0, (y0 + y1) / 2);
        ctx.lineTo(x1, (y0 + y1) / 2);
        visuals.line.apply(ctx, i);
        ctx.restore();
    }
    exports.generic_line_vector_legend = generic_line_vector_legend;
    exports.generic_line_legend = generic_line_vector_legend;
    function generic_area_scalar_legend(visuals, ctx, _a) {
        var _b, _c;
        var x0 = _a.x0, x1 = _a.x1, y0 = _a.y0, y1 = _a.y1;
        var w = Math.abs(x1 - x0);
        var dw = w * 0.1;
        var h = Math.abs(y1 - y0);
        var dh = h * 0.1;
        var sx0 = x0 + dw;
        var sx1 = x1 - dw;
        var sy0 = y0 + dh;
        var sy1 = y1 - dh;
        ctx.beginPath();
        ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        visuals.fill.apply(ctx);
        (_b = visuals.hatch) === null || _b === void 0 ? void 0 : _b.apply(ctx);
        (_c = visuals.line) === null || _c === void 0 ? void 0 : _c.apply(ctx);
    }
    exports.generic_area_scalar_legend = generic_area_scalar_legend;
    function generic_area_vector_legend(visuals, ctx, _a, i) {
        var _b, _c;
        var x0 = _a.x0, x1 = _a.x1, y0 = _a.y0, y1 = _a.y1;
        var w = Math.abs(x1 - x0);
        var dw = w * 0.1;
        var h = Math.abs(y1 - y0);
        var dh = h * 0.1;
        var sx0 = x0 + dw;
        var sx1 = x1 - dw;
        var sy0 = y0 + dh;
        var sy1 = y1 - dh;
        ctx.beginPath();
        ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        visuals.fill.apply(ctx, i);
        (_b = visuals.hatch) === null || _b === void 0 ? void 0 : _b.apply(ctx, i);
        (_c = visuals.line) === null || _c === void 0 ? void 0 : _c.apply(ctx, i);
    }
    exports.generic_area_vector_legend = generic_area_vector_legend;
    exports.generic_area_legend = generic_area_vector_legend;
    function line_interpolation(renderer, geometry, x2, y2, x3, y3) {
        var _a, _b, _c, _d, _e, _f;
        var sx = geometry.sx, sy = geometry.sy;
        var x0, x1;
        var y0, y1;
        if (geometry.type == "point") {
            // The +/- adjustments here are to dilate the hit point into a virtual "segment" to use below
            _a = (0, tslib_1.__read)(renderer.yscale.r_invert(sy - 1, sy + 1), 2), y0 = _a[0], y1 = _a[1];
            _b = (0, tslib_1.__read)(renderer.xscale.r_invert(sx - 1, sx + 1), 2), x0 = _b[0], x1 = _b[1];
        }
        else {
            // The +/- adjustments here are to handle cases such as purely horizontal or vertical lines
            if (geometry.direction == "v") {
                _c = (0, tslib_1.__read)(renderer.yscale.r_invert(sy, sy), 2), y0 = _c[0], y1 = _c[1];
                _d = (0, tslib_1.__read)([Math.min(x2 - 1, x3 - 1), Math.max(x2 + 1, x3 + 1)], 2), x0 = _d[0], x1 = _d[1];
            }
            else {
                _e = (0, tslib_1.__read)(renderer.xscale.r_invert(sx, sx), 2), x0 = _e[0], x1 = _e[1];
                _f = (0, tslib_1.__read)([Math.min(y2 - 1, y3 - 1), Math.max(y2 + 1, y3 + 1)], 2), y0 = _f[0], y1 = _f[1];
            }
        }
        var _g = hittest.check_2_segments_intersect(x0, y0, x1, y1, x2, y2, x3, y3), x = _g.x, y = _g.y;
        return [x, y]; // XXX: null is not handled at use sites
    }
    exports.line_interpolation = line_interpolation;
},
/* core/hittest.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function point_in_poly(x, y, px, py) {
        var inside = false;
        var x1 = px[px.length - 1];
        var y1 = py[py.length - 1];
        for (var i = 0; i < px.length; i++) {
            var x2 = px[i];
            var y2 = py[i];
            if ((y1 < y) != (y2 < y)) {
                if ((x1 + (y - y1) / (y2 - y1) * (x2 - x1)) < x)
                    inside = !inside;
            }
            x1 = x2;
            y1 = y2;
        }
        return inside;
    }
    exports.point_in_poly = point_in_poly;
    function point_in_ellipse(x, y, angle, b, a, x0, y0) {
        var A = (Math.pow((Math.cos(angle) / a), 2) + Math.pow((Math.sin(angle) / b), 2));
        var B = 2 * Math.cos(angle) * Math.sin(angle) * (Math.pow((1 / a), 2) - Math.pow((1 / b), 2));
        var C = (Math.pow((Math.cos(angle) / b), 2) + Math.pow((Math.sin(angle) / a), 2));
        var eqn = A * Math.pow((x - x0), 2) + B * (x - x0) * (y - y0) + C * Math.pow((y - y0), 2);
        var inside = eqn <= 1;
        return inside;
    }
    exports.point_in_ellipse = point_in_ellipse;
    function dist_2_pts(p0, p1) {
        return Math.pow((p0.x - p1.x), 2) + Math.pow((p0.y - p1.y), 2);
    }
    exports.dist_2_pts = dist_2_pts;
    function dist_to_segment_squared(p, v, w) {
        var l2 = dist_2_pts(v, w);
        if (l2 == 0)
            return dist_2_pts(p, v);
        var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
        if (t < 0)
            return dist_2_pts(p, v);
        if (t > 1)
            return dist_2_pts(p, w);
        var q = { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) };
        return dist_2_pts(p, q);
    }
    exports.dist_to_segment_squared = dist_to_segment_squared;
    function dist_to_segment(p, v, w) {
        return Math.sqrt(dist_to_segment_squared(p, v, w));
    }
    exports.dist_to_segment = dist_to_segment;
    function check_2_segments_intersect(l0_x0, l0_y0, l0_x1, l0_y1, l1_x0, l1_y0, l1_x1, l1_y1) {
        /*
         *  Check if 2 segments (l0 and l1) intersect. Returns a structure with
         *  the following attributes:
         *   * hit (boolean): whether the 2 segments intersect
         *   * x (float): x coordinate of the intersection point
         *   * y (float): y coordinate of the intersection point
         */
        var den = ((l1_y1 - l1_y0) * (l0_x1 - l0_x0)) - ((l1_x1 - l1_x0) * (l0_y1 - l0_y0));
        if (den == 0) {
            return { hit: false, x: null, y: null };
        }
        else {
            var a = l0_y0 - l1_y0;
            var b = l0_x0 - l1_x0;
            var num1 = ((l1_x1 - l1_x0) * a) - ((l1_y1 - l1_y0) * b);
            var num2 = ((l0_x1 - l0_x0) * a) - ((l0_y1 - l0_y0) * b);
            a = num1 / den;
            b = num2 / den;
            var x = l0_x0 + (a * (l0_x1 - l0_x0));
            var y = l0_y0 + (a * (l0_y1 - l0_y0));
            return { hit: (a > 0 && a < 1) && (b > 0 && b < 1), x: x, y: y };
        }
    }
    exports.check_2_segments_intersect = check_2_segments_intersect;
},
/* models/glyphs/patch.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var utils_1 = require(299) /* ./utils */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var selection_1 = require(187) /* ../selections/selection */;
    var PatchView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PatchView, _super);
        function PatchView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PatchView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy;
            var move = true;
            ctx.beginPath();
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    if (!isFinite(sx_i + sy_i)) {
                        ctx.closePath();
                        move = true;
                    }
                    else {
                        if (move) {
                            ctx.moveTo(sx_i, sy_i);
                            move = false;
                        }
                        else
                            ctx.lineTo(sx_i, sy_i);
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
            this.visuals.line.apply(ctx);
        };
        PatchView.prototype.draw_legend_for_index = function (ctx, bbox, _index) {
            (0, utils_1.generic_area_scalar_legend)(this.visuals, ctx, bbox);
        };
        PatchView.prototype._hit_point = function (geometry) {
            var result = new selection_1.Selection();
            if (hittest.point_in_poly(geometry.sx, geometry.sy, this.sx, this.sy)) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
            }
            return result;
        };
        return PatchView;
    }(xy_glyph_1.XYGlyphView));
    exports.PatchView = PatchView;
    PatchView.__name__ = "PatchView";
    var Patch = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Patch, _super);
        function Patch(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Patch;
    }(xy_glyph_1.XYGlyph));
    exports.Patch = Patch;
    _a = Patch;
    Patch.__name__ = "Patch";
    (function () {
        _a.prototype.default_view = PatchView;
        _a.mixins([mixins.LineScalar, mixins.FillScalar, mixins.HatchScalar]);
    })();
},
/* models/glyphs/harea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var types_1 = require(139) /* ../../core/types */;
    var area_1 = require(303) /* ./area */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var selection_1 = require(187) /* ../selections/selection */;
    var HAreaView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HAreaView, _super);
        function HAreaView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        HAreaView.prototype._index_data = function (index) {
            var min = Math.min, max = Math.max;
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                var x1 = this._x1[i];
                var x2 = this._x2[i];
                var y = this._y[i];
                index.add_rect(min(x1, x2), y, max(x1, x2), y);
            }
        };
        HAreaView.prototype._render = function (ctx, _indices, data) {
            var _b = data !== null && data !== void 0 ? data : this, sx1 = _b.sx1, sx2 = _b.sx2, sy = _b.sy;
            ctx.beginPath();
            for (var i = 0, end = sx1.length; i < end; i++) {
                ctx.lineTo(sx1[i], sy[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (var i = sx2.length - 1; i >= 0; i--) {
                ctx.lineTo(sx2[i], sy[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        };
        HAreaView.prototype._hit_point = function (geometry) {
            var L = this.sy.length;
            var sx = new types_1.ScreenArray(2 * L);
            var sy = new types_1.ScreenArray(2 * L);
            for (var i = 0, end = L; i < end; i++) {
                sx[i] = this.sx1[i];
                sy[i] = this.sy[i];
                sx[L + i] = this.sx2[L - i - 1];
                sy[L + i] = this.sy[L - i - 1];
            }
            var result = new selection_1.Selection();
            if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
            }
            return result;
        };
        HAreaView.prototype.scenterxy = function (i) {
            var scx = (this.sx1[i] + this.sx2[i]) / 2;
            var scy = this.sy[i];
            return [scx, scy];
        };
        HAreaView.prototype._map_data = function () {
            this.sx1 = this.renderer.xscale.v_compute(this._x1);
            this.sx2 = this.renderer.xscale.v_compute(this._x2);
            this.sy = this.renderer.yscale.v_compute(this._y);
        };
        return HAreaView;
    }(area_1.AreaView));
    exports.HAreaView = HAreaView;
    HAreaView.__name__ = "HAreaView";
    var HArea = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HArea, _super);
        function HArea(attrs) {
            return _super.call(this, attrs) || this;
        }
        return HArea;
    }(area_1.Area));
    exports.HArea = HArea;
    _a = HArea;
    HArea.__name__ = "HArea";
    (function () {
        _a.prototype.default_view = HAreaView;
        _a.define(function (_b) {
            return ({
                x1: [p.XCoordinateSpec, { field: "x1" }],
                x2: [p.XCoordinateSpec, { field: "x2" }],
                y: [p.YCoordinateSpec, { field: "y" }],
            });
        });
    })();
},
/* models/glyphs/area.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var glyph_1 = require(294) /* ./glyph */;
    var utils_1 = require(299) /* ./utils */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var AreaView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AreaView, _super);
        function AreaView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AreaView.prototype.draw_legend_for_index = function (ctx, bbox, _index) {
            (0, utils_1.generic_area_scalar_legend)(this.visuals, ctx, bbox);
        };
        return AreaView;
    }(glyph_1.GlyphView));
    exports.AreaView = AreaView;
    AreaView.__name__ = "AreaView";
    var Area = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Area, _super);
        function Area(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Area;
    }(glyph_1.Glyph));
    exports.Area = Area;
    _a = Area;
    Area.__name__ = "Area";
    (function () {
        _a.mixins([mixins.FillScalar, mixins.HatchScalar]);
    })();
},
/* models/glyphs/varea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var types_1 = require(139) /* ../../core/types */;
    var area_1 = require(303) /* ./area */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var selection_1 = require(187) /* ../selections/selection */;
    var VAreaView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VAreaView, _super);
        function VAreaView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        VAreaView.prototype._index_data = function (index) {
            var min = Math.min, max = Math.max;
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                var x = this._x[i];
                var y1 = this._y1[i];
                var y2 = this._y2[i];
                index.add_rect(x, min(y1, y2), x, max(y1, y2));
            }
        };
        VAreaView.prototype._render = function (ctx, _indices, data) {
            var _b = data !== null && data !== void 0 ? data : this, sx = _b.sx, sy1 = _b.sy1, sy2 = _b.sy2;
            ctx.beginPath();
            for (var i = 0, end = sy1.length; i < end; i++) {
                ctx.lineTo(sx[i], sy1[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (var i = sy2.length - 1; i >= 0; i--) {
                ctx.lineTo(sx[i], sy2[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        };
        VAreaView.prototype.scenterxy = function (i) {
            var scx = this.sx[i];
            var scy = (this.sy1[i] + this.sy2[i]) / 2;
            return [scx, scy];
        };
        VAreaView.prototype._hit_point = function (geometry) {
            var L = this.sx.length;
            var sx = new types_1.ScreenArray(2 * L);
            var sy = new types_1.ScreenArray(2 * L);
            for (var i = 0, end = L; i < end; i++) {
                sx[i] = this.sx[i];
                sy[i] = this.sy1[i];
                sx[L + i] = this.sx[L - i - 1];
                sy[L + i] = this.sy2[L - i - 1];
            }
            var result = new selection_1.Selection();
            if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
            }
            return result;
        };
        VAreaView.prototype._map_data = function () {
            this.sx = this.renderer.xscale.v_compute(this._x);
            this.sy1 = this.renderer.yscale.v_compute(this._y1);
            this.sy2 = this.renderer.yscale.v_compute(this._y2);
        };
        return VAreaView;
    }(area_1.AreaView));
    exports.VAreaView = VAreaView;
    VAreaView.__name__ = "VAreaView";
    var VArea = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VArea, _super);
        function VArea(attrs) {
            return _super.call(this, attrs) || this;
        }
        return VArea;
    }(area_1.Area));
    exports.VArea = VArea;
    _a = VArea;
    VArea.__name__ = "VArea";
    (function () {
        _a.prototype.default_view = VAreaView;
        _a.define(function (_b) {
            return ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
                y2: [p.YCoordinateSpec, { field: "y2" }],
            });
        });
    })();
},
/* models/sources/cds_view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var types_1 = require(139) /* ../../core/types */;
    var filter_1 = require(306) /* ../filters/filter */;
    var columnar_data_source_1 = require(185) /* ./columnar_data_source */;
    var CDSView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CDSView, _super);
        function CDSView(attrs) {
            return _super.call(this, attrs) || this;
        }
        CDSView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.compute_indices();
        };
        CDSView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.properties.filters.change, function () { return _this.compute_indices(); });
            var connect_listeners = function () {
                var fn = function () { return _this.compute_indices(); };
                if (_this.source != null) {
                    _this.connect(_this.source.change, fn);
                    if (_this.source instanceof columnar_data_source_1.ColumnarDataSource) {
                        _this.connect(_this.source.streaming, fn);
                        _this.connect(_this.source.patching, fn);
                    }
                }
            };
            var initialized = this.source != null;
            if (initialized)
                connect_listeners();
            else {
                this.connect(this.properties.source.change, function () {
                    if (!initialized) {
                        connect_listeners();
                        initialized = true;
                    }
                });
            }
        };
        CDSView.prototype.compute_indices = function () {
            var e_1, _b;
            var _c;
            var source = this.source;
            if (source == null)
                return;
            // XXX: if the data source is empty, there still may be one
            // index originating from glyph's scalar values.
            var size = (_c = source.get_length()) !== null && _c !== void 0 ? _c : 1;
            var indices = types_1.Indices.all_set(size);
            try {
                for (var _d = (0, tslib_1.__values)(this.filters), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var filter = _e.value;
                    indices.intersect(filter.compute_indices(source));
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            this.indices = indices;
            this._indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(indices), false);
            this.indices_map_to_subset();
        };
        CDSView.prototype.indices_map_to_subset = function () {
            this.indices_map = {};
            for (var i = 0; i < this._indices.length; i++) {
                this.indices_map[this._indices[i]] = i;
            }
        };
        CDSView.prototype.convert_selection_from_subset = function (selection_subset) {
            var _this = this;
            return selection_subset.map(function (i) { return _this._indices[i]; });
        };
        CDSView.prototype.convert_selection_to_subset = function (selection_full) {
            var _this = this;
            return selection_full.map(function (i) { return _this.indices_map[i]; });
        };
        CDSView.prototype.convert_indices_from_subset = function (indices) {
            var _this = this;
            return indices.map(function (i) { return _this._indices[i]; });
        };
        return CDSView;
    }(model_1.Model));
    exports.CDSView = CDSView;
    _a = CDSView;
    CDSView.__name__ = "CDSView";
    (function () {
        _a.define(function (_b) {
            var Array = _b.Array, Ref = _b.Ref;
            return ({
                filters: [Array(Ref(filter_1.Filter)), []],
                source: [Ref(columnar_data_source_1.ColumnarDataSource)],
            });
        });
        _a.internal(function (_b) {
            var Int = _b.Int, Dict = _b.Dict, Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                indices: [Ref(types_1.Indices)],
                indices_map: [Dict(Int), {}],
                masked: [Nullable(Ref(types_1.Indices)), null],
            });
        });
    })();
},
/* models/filters/filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../../model */;
    var Filter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Filter, _super);
        function Filter(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Filter;
    }(model_1.Model));
    exports.Filter = Filter;
    Filter.__name__ = "Filter";
},
/* models/formatters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var basic_tick_formatter_1 = require(261) /* ./basic_tick_formatter */;
    __esExport("BasicTickFormatter", basic_tick_formatter_1.BasicTickFormatter);
    var categorical_tick_formatter_1 = require(257) /* ./categorical_tick_formatter */;
    __esExport("CategoricalTickFormatter", categorical_tick_formatter_1.CategoricalTickFormatter);
    var datetime_tick_formatter_1 = require(265) /* ./datetime_tick_formatter */;
    __esExport("DatetimeTickFormatter", datetime_tick_formatter_1.DatetimeTickFormatter);
    var func_tick_formatter_1 = require(308) /* ./func_tick_formatter */;
    __esExport("FuncTickFormatter", func_tick_formatter_1.FuncTickFormatter);
    var log_tick_formatter_1 = require(278) /* ./log_tick_formatter */;
    __esExport("LogTickFormatter", log_tick_formatter_1.LogTickFormatter);
    var mercator_tick_formatter_1 = require(281) /* ./mercator_tick_formatter */;
    __esExport("MercatorTickFormatter", mercator_tick_formatter_1.MercatorTickFormatter);
    var numeral_tick_formatter_1 = require(309) /* ./numeral_tick_formatter */;
    __esExport("NumeralTickFormatter", numeral_tick_formatter_1.NumeralTickFormatter);
    var printf_tick_formatter_1 = require(310) /* ./printf_tick_formatter */;
    __esExport("PrintfTickFormatter", printf_tick_formatter_1.PrintfTickFormatter);
    var tick_formatter_1 = require(246) /* ./tick_formatter */;
    __esExport("TickFormatter", tick_formatter_1.TickFormatter);
},
/* models/formatters/func_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var tick_formatter_1 = require(246) /* ./tick_formatter */;
    var object_1 = require(128) /* ../../core/util/object */;
    var string_1 = require(149) /* ../../core/util/string */;
    var FuncTickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FuncTickFormatter, _super);
        function FuncTickFormatter(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(FuncTickFormatter.prototype, "names", {
            get: function () {
                return (0, object_1.keys)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(FuncTickFormatter.prototype, "values", {
            get: function () {
                return (0, object_1.values)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        /*protected*/ FuncTickFormatter.prototype._make_func = function () {
            var code = (0, string_1.use_strict)(this.code);
            return new (Function.bind.apply(Function, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([void 0, "tick", "index", "ticks"], (0, tslib_1.__read)(this.names), false), [code], false)))();
        };
        FuncTickFormatter.prototype.doFormat = function (ticks, _opts) {
            var _this = this;
            var cache = {};
            var func = this._make_func().bind(cache);
            return ticks.map(function (tick, index, ticks) { return "" + func.apply(void 0, (0, tslib_1.__spreadArray)([tick, index, ticks], (0, tslib_1.__read)(_this.values), false)); });
        };
        return FuncTickFormatter;
    }(tick_formatter_1.TickFormatter));
    exports.FuncTickFormatter = FuncTickFormatter;
    _a = FuncTickFormatter;
    FuncTickFormatter.__name__ = "FuncTickFormatter";
    (function () {
        _a.define(function (_b) {
            var Unknown = _b.Unknown, String = _b.String, Dict = _b.Dict;
            return ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            });
        });
    })();
},
/* models/formatters/numeral_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var Numbro = (0, tslib_1.__importStar)(require(268) /* @bokeh/numbro */);
    var tick_formatter_1 = require(246) /* ./tick_formatter */;
    var enums_1 = require(135) /* ../../core/enums */;
    var NumeralTickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NumeralTickFormatter, _super);
        function NumeralTickFormatter(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(NumeralTickFormatter.prototype, "_rounding_fn", {
            get: function () {
                switch (this.rounding) {
                    case "round":
                    case "nearest":
                        return Math.round;
                    case "floor":
                    case "rounddown":
                        return Math.floor;
                    case "ceil":
                    case "roundup":
                        return Math.ceil;
                }
            },
            enumerable: false,
            configurable: true
        });
        NumeralTickFormatter.prototype.doFormat = function (ticks, _opts) {
            var _b = this, format = _b.format, language = _b.language, _rounding_fn = _b._rounding_fn;
            return ticks.map(function (tick) { return Numbro.format(tick, format, language, _rounding_fn); });
        };
        return NumeralTickFormatter;
    }(tick_formatter_1.TickFormatter));
    exports.NumeralTickFormatter = NumeralTickFormatter;
    _a = NumeralTickFormatter;
    NumeralTickFormatter.__name__ = "NumeralTickFormatter";
    (function () {
        _a.define(function (_b) {
            var String = _b.String;
            return ({
                // TODO (bev) all of these could be tightened up
                format: [String, "0,0"],
                language: [String, "en"],
                rounding: [enums_1.RoundingFunction, "round"],
            });
        });
    })();
},
/* models/formatters/printf_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var tick_formatter_1 = require(246) /* ./tick_formatter */;
    var templating_1 = require(267) /* ../../core/util/templating */;
    var PrintfTickFormatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PrintfTickFormatter, _super);
        function PrintfTickFormatter(attrs) {
            return _super.call(this, attrs) || this;
        }
        PrintfTickFormatter.prototype.doFormat = function (ticks, _opts) {
            var _this = this;
            return ticks.map(function (tick) { return (0, templating_1.sprintf)(_this.format, tick); });
        };
        return PrintfTickFormatter;
    }(tick_formatter_1.TickFormatter));
    exports.PrintfTickFormatter = PrintfTickFormatter;
    _a = PrintfTickFormatter;
    PrintfTickFormatter.__name__ = "PrintfTickFormatter";
    (function () {
        _a.define(function (_b) {
            var String = _b.String;
            return ({
                format: [String, "%s"],
            });
        });
    })();
},
/* models/mappers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_color_mapper_1 = require(312) /* ./categorical_color_mapper */;
    __esExport("CategoricalColorMapper", categorical_color_mapper_1.CategoricalColorMapper);
    var categorical_marker_mapper_1 = require(314) /* ./categorical_marker_mapper */;
    __esExport("CategoricalMarkerMapper", categorical_marker_mapper_1.CategoricalMarkerMapper);
    var categorical_pattern_mapper_1 = require(315) /* ./categorical_pattern_mapper */;
    __esExport("CategoricalPatternMapper", categorical_pattern_mapper_1.CategoricalPatternMapper);
    var continuous_color_mapper_1 = require(287) /* ./continuous_color_mapper */;
    __esExport("ContinuousColorMapper", continuous_color_mapper_1.ContinuousColorMapper);
    var color_mapper_1 = require(288) /* ./color_mapper */;
    __esExport("ColorMapper", color_mapper_1.ColorMapper);
    var linear_color_mapper_1 = require(316) /* ./linear_color_mapper */;
    __esExport("LinearColorMapper", linear_color_mapper_1.LinearColorMapper);
    var log_color_mapper_1 = require(317) /* ./log_color_mapper */;
    __esExport("LogColorMapper", log_color_mapper_1.LogColorMapper);
    var scanning_color_mapper_1 = require(286) /* ./scanning_color_mapper */;
    __esExport("ScanningColorMapper", scanning_color_mapper_1.ScanningColorMapper);
    var eqhist_color_mapper_1 = require(318) /* ./eqhist_color_mapper */;
    __esExport("EqHistColorMapper", eqhist_color_mapper_1.EqHistColorMapper);
},
/* models/mappers/categorical_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var categorical_mapper_1 = require(313) /* ./categorical_mapper */;
    var color_mapper_1 = require(288) /* ./color_mapper */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var CategoricalColorMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CategoricalColorMapper, _super);
        function CategoricalColorMapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        CategoricalColorMapper.prototype._v_compute = function (data, values, palette, _b) {
            var nan_color = _b.nan_color;
            (0, categorical_mapper_1.cat_v_compute)(data, this.factors, palette, values, this.start, this.end, nan_color);
        };
        return CategoricalColorMapper;
    }(color_mapper_1.ColorMapper));
    exports.CategoricalColorMapper = CategoricalColorMapper;
    _a = CategoricalColorMapper;
    CategoricalColorMapper.__name__ = "CategoricalColorMapper";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Nullable = _b.Nullable;
            return ({
                factors: [factor_range_1.FactorSeq],
                start: [Number, 0],
                end: [Nullable(Number), null],
            });
        });
    })();
},
/* models/mappers/categorical_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var types_1 = require(125) /* ../../core/util/types */;
    function _cat_equals(a, b) {
        if (a.length != b.length)
            return false;
        for (var i = 0, end = a.length; i < end; i++) {
            if (a[i] !== b[i])
                return false;
        }
        return true;
    }
    exports._cat_equals = _cat_equals;
    function cat_v_compute(data, factors, targets, values, start, end, extra_value) {
        var N = data.length;
        var _loop_1 = function (i) {
            var d = data[i];
            var key = void 0;
            if ((0, types_1.isString)(d))
                key = (0, arrayable_1.index_of)(factors, d);
            else {
                if (start != null) {
                    if (end != null)
                        d = d.slice(start, end);
                    else
                        d = d.slice(start);
                }
                else if (end != null)
                    d = d.slice(0, end);
                if (d.length == 1)
                    key = (0, arrayable_1.index_of)(factors, d[0]);
                else
                    key = (0, arrayable_1.find_index)(factors, function (x) { return _cat_equals(x, d); });
            }
            var value = void 0;
            if (key < 0 || key >= targets.length)
                value = extra_value;
            else
                value = targets[key];
            values[i] = value;
        };
        for (var i = 0; i < N; i++) {
            _loop_1(i);
        }
    }
    exports.cat_v_compute = cat_v_compute;
},
/* models/mappers/categorical_marker_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var categorical_mapper_1 = require(313) /* ./categorical_mapper */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var mapper_1 = require(289) /* ./mapper */;
    var enums_1 = require(135) /* ../../core/enums */;
    var CategoricalMarkerMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CategoricalMarkerMapper, _super);
        function CategoricalMarkerMapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        CategoricalMarkerMapper.prototype.v_compute = function (xs) {
            var values = new Array(xs.length);
            (0, categorical_mapper_1.cat_v_compute)(xs, this.factors, this.markers, values, this.start, this.end, this.default_value);
            return values;
        };
        return CategoricalMarkerMapper;
    }(mapper_1.Mapper));
    exports.CategoricalMarkerMapper = CategoricalMarkerMapper;
    _a = CategoricalMarkerMapper;
    CategoricalMarkerMapper.__name__ = "CategoricalMarkerMapper";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Array = _b.Array, Nullable = _b.Nullable;
            return ({
                factors: [factor_range_1.FactorSeq],
                markers: [Array(enums_1.MarkerType)],
                start: [Number, 0],
                end: [Nullable(Number), null],
                default_value: [enums_1.MarkerType, "circle"],
            });
        });
    })();
},
/* models/mappers/categorical_pattern_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var categorical_mapper_1 = require(313) /* ./categorical_mapper */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var mapper_1 = require(289) /* ./mapper */;
    var enums_1 = require(135) /* ../../core/enums */;
    var CategoricalPatternMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CategoricalPatternMapper, _super);
        function CategoricalPatternMapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        CategoricalPatternMapper.prototype.v_compute = function (xs) {
            var values = new Array(xs.length);
            (0, categorical_mapper_1.cat_v_compute)(xs, this.factors, this.patterns, values, this.start, this.end, this.default_value);
            return values;
        };
        return CategoricalPatternMapper;
    }(mapper_1.Mapper));
    exports.CategoricalPatternMapper = CategoricalPatternMapper;
    _a = CategoricalPatternMapper;
    CategoricalPatternMapper.__name__ = "CategoricalPatternMapper";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Array = _b.Array, Nullable = _b.Nullable;
            return ({
                factors: [factor_range_1.FactorSeq],
                patterns: [Array(enums_1.HatchPatternType)],
                start: [Number, 0],
                end: [Nullable(Number), null],
                default_value: [enums_1.HatchPatternType, " "],
            });
        });
    })();
},
/* models/mappers/linear_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var continuous_color_mapper_1 = require(287) /* ./continuous_color_mapper */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var LinearColorMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LinearColorMapper, _super);
        function LinearColorMapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        LinearColorMapper.prototype.scan = function (data, n) {
            var low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            var high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            var norm_factor = 1 / (high - low);
            var normed_interval = 1 / n;
            return { max: high, min: low, norm_factor: norm_factor, normed_interval: normed_interval };
        };
        LinearColorMapper.prototype.cmap = function (d, palette, low_color, high_color, scan_data) {
            // This handles the edge case where d == high, since the code below maps
            // values exactly equal to high to palette.length, which is greater than
            // max_key
            var max_key = palette.length - 1;
            if (d == scan_data.max) {
                return palette[max_key];
            }
            var normed_d = (d - scan_data.min) * scan_data.norm_factor;
            var key = Math.floor(normed_d / scan_data.normed_interval);
            if (key < 0)
                return low_color;
            else if (key > max_key)
                return high_color;
            else
                return palette[key];
        };
        return LinearColorMapper;
    }(continuous_color_mapper_1.ContinuousColorMapper));
    exports.LinearColorMapper = LinearColorMapper;
    LinearColorMapper.__name__ = "LinearColorMapper";
},
/* models/mappers/log_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var continuous_color_mapper_1 = require(287) /* ./continuous_color_mapper */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var LogColorMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LogColorMapper, _super);
        function LogColorMapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        LogColorMapper.prototype.scan = function (data, n) {
            var low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            var high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            var scale = n / (Math.log(high) - Math.log(low)); // subtract the low offset
            return { max: high, min: low, scale: scale };
        };
        LogColorMapper.prototype.cmap = function (d, palette, low_color, high_color, scan_data) {
            var max_key = palette.length - 1;
            if (d > scan_data.max) {
                return high_color;
            }
            // This handles the edge case where d == high, since the code below maps
            // values exactly equal to high to palette.length, which is greater than
            // max_key
            if (d == scan_data.max)
                return palette[max_key];
            else if (d < scan_data.min)
                return low_color;
            // Get the key
            var log = Math.log(d) - Math.log(scan_data.min); // subtract the low offset
            var key = Math.floor(log * scan_data.scale);
            // Deal with upper bound
            if (key > max_key) {
                key = max_key;
            }
            return palette[key];
        };
        return LogColorMapper;
    }(continuous_color_mapper_1.ContinuousColorMapper));
    exports.LogColorMapper = LogColorMapper;
    LogColorMapper.__name__ = "LogColorMapper";
},
/* models/mappers/eqhist_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var scanning_color_mapper_1 = require(286) /* ./scanning_color_mapper */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var array_1 = require(126) /* ../../core/util/array */;
    var logging_1 = require(134) /* ../../core/logging */;
    var EqHistColorMapper = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EqHistColorMapper, _super);
        function EqHistColorMapper(attrs) {
            return _super.call(this, attrs) || this;
        }
        EqHistColorMapper.prototype.scan = function (data, n) {
            var low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            var high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            var nbins = this.bins;
            var eq_bin_edges = (0, array_1.linspace)(low, high, nbins + 1);
            var hist = (0, arrayable_1.bin_counts)(data, eq_bin_edges);
            var eq_bin_centers = new Array(nbins);
            for (var i = 0, length = eq_bin_edges.length; i < length - 1; i++) {
                var left = eq_bin_edges[i];
                var right = eq_bin_edges[i + 1];
                eq_bin_centers[i] = (left + right) / 2;
            }
            // CDFs
            var cdf = (0, array_1.cumsum)(hist);
            var cdf_max = cdf[cdf.length - 1];
            var norm_cdf = (0, arrayable_1.map)(cdf, function (x) { return x / cdf_max; });
            // Iteratively find as many finite bins as there are colors
            var finite_bins = n - 1;
            var binning = [];
            var iterations = 0;
            var guess = n * 2;
            while ((finite_bins != n) && (iterations < 4) && (finite_bins != 0)) {
                var ratio = guess / finite_bins;
                if (ratio > 1000) {
                    // Abort if distribution is extremely skewed
                    break;
                }
                guess = Math.round(Math.max(n * ratio, n));
                // Interpolate
                var palette_edges = (0, array_1.range)(0, guess);
                var palette_cdf = (0, arrayable_1.map)(norm_cdf, function (x) { return x * (guess - 1); });
                binning = (0, arrayable_1.interpolate)(palette_edges, palette_cdf, eq_bin_centers);
                // Evaluate binning
                var uniq_bins = (0, array_1.uniq)(binning);
                finite_bins = uniq_bins.length - 1;
                iterations++;
            }
            if (finite_bins == 0) {
                binning = [low, high];
                for (var j = 0; j < n - 1; j++)
                    binning.push(high);
            }
            else {
                binning = binning.slice(binning.length - n - 1);
                if (finite_bins != n)
                    logging_1.logger.warn("EqHistColorMapper warning: Histogram equalization did not converge.");
            }
            // XXX: should this be guaranteed by the above algorithm?
            binning[0] = low;
            binning[binning.length - 1] = high;
            return { min: low, max: high, binning: binning };
        };
        return EqHistColorMapper;
    }(scanning_color_mapper_1.ScanningColorMapper));
    exports.EqHistColorMapper = EqHistColorMapper;
    _a = EqHistColorMapper;
    EqHistColorMapper.__name__ = "EqHistColorMapper";
    (function () {
        _a.define(function (_b) {
            var Int = _b.Int;
            return ({
                bins: [Int, 256 * 256],
            });
        });
    })();
},
/* models/scales/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_scale_1 = require(177) /* ./categorical_scale */;
    __esExport("CategoricalScale", categorical_scale_1.CategoricalScale);
    var continuous_scale_1 = require(175) /* ./continuous_scale */;
    __esExport("ContinuousScale", continuous_scale_1.ContinuousScale);
    var linear_scale_1 = require(174) /* ./linear_scale */;
    __esExport("LinearScale", linear_scale_1.LinearScale);
    var linear_interpolation_scale_1 = require(320) /* ./linear_interpolation_scale */;
    __esExport("LinearInterpolationScale", linear_interpolation_scale_1.LinearInterpolationScale);
    var log_scale_1 = require(176) /* ./log_scale */;
    __esExport("LogScale", log_scale_1.LogScale);
    var scale_1 = require(170) /* ./scale */;
    __esExport("Scale", scale_1.Scale);
},
/* models/scales/linear_interpolation_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var scale_1 = require(170) /* ./scale */;
    var linear_scale_1 = require(174) /* ./linear_scale */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var LinearInterpolationScale = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LinearInterpolationScale, _super);
        function LinearInterpolationScale(attrs) {
            return _super.call(this, attrs) || this;
        }
        LinearInterpolationScale.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var _b = this.properties, source_range = _b.source_range, target_range = _b.target_range;
            this.on_change([source_range, target_range], function () {
                _this.linear_scale = new linear_scale_1.LinearScale({
                    source_range: _this.source_range,
                    target_range: _this.target_range,
                });
            });
        };
        Object.defineProperty(LinearInterpolationScale.prototype, "s_compute", {
            get: function () {
                throw new Error("not implemented");
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LinearInterpolationScale.prototype, "s_invert", {
            get: function () {
                throw new Error("not implemented");
            },
            enumerable: false,
            configurable: true
        });
        LinearInterpolationScale.prototype.compute = function (x) {
            return x;
        };
        LinearInterpolationScale.prototype.v_compute = function (vs) {
            var binning = this.binning;
            var _b = this.source_range, start = _b.start, end = _b.end;
            var min_val = start;
            var max_val = end;
            var n = binning.length;
            var step = (end - start) / (n - 1);
            var mapping = new Float64Array(n);
            for (var i = 0; i < n; i++) {
                mapping[i] = start + i * step;
            }
            var vvs = (0, arrayable_1.map)(vs, function (v) {
                if (v < min_val)
                    return min_val;
                if (v > max_val)
                    return max_val;
                var k = (0, arrayable_1.left_edge_index)(v, binning);
                if (k == -1)
                    return min_val;
                if (k >= n - 1)
                    return max_val;
                var b0 = binning[k];
                var b1 = binning[k + 1];
                var c = (v - b0) / (b1 - b0);
                var m0 = mapping[k];
                var m1 = mapping[k + 1];
                return m0 + c * (m1 - m0);
            });
            return this.linear_scale.v_compute(vvs);
        };
        LinearInterpolationScale.prototype.invert = function (xprime) {
            return xprime;
        };
        LinearInterpolationScale.prototype.v_invert = function (xprimes) {
            return new Float64Array(xprimes);
        };
        return LinearInterpolationScale;
    }(scale_1.Scale));
    exports.LinearInterpolationScale = LinearInterpolationScale;
    _a = LinearInterpolationScale;
    LinearInterpolationScale.__name__ = "LinearInterpolationScale";
    (function () {
        _a.internal(function (_b) {
            var Arrayable = _b.Arrayable, Ref = _b.Ref;
            return ({
                binning: [Arrayable],
                linear_scale: [
                    Ref(linear_scale_1.LinearScale),
                    function (self) {
                        return new linear_scale_1.LinearScale({
                            source_range: self.source_range,
                            target_range: self.target_range,
                        });
                    },
                ],
            });
        });
    })();
},
/* models/ranges/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var data_range_1 = require(179) /* ./data_range */;
    __esExport("DataRange", data_range_1.DataRange);
    var data_range1d_1 = require(178) /* ./data_range1d */;
    __esExport("DataRange1d", data_range1d_1.DataRange1d);
    var factor_range_1 = require(182) /* ./factor_range */;
    __esExport("FactorRange", factor_range_1.FactorRange);
    var range_1 = require(172) /* ./range */;
    __esExport("Range", range_1.Range);
    var range1d_1 = require(173) /* ./range1d */;
    __esExport("Range1d", range1d_1.Range1d);
},
/* core/layout/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(239) /* ./types */;
    __esExport("Sizeable", types_1.Sizeable);
    __esExport("SizingPolicy", types_1.SizingPolicy);
    var layoutable_1 = require(240) /* ./layoutable */;
    __esExport("Layoutable", layoutable_1.Layoutable);
    __esExport("LayoutItem", layoutable_1.LayoutItem);
    var alignments_1 = require(323) /* ./alignments */;
    __esExport("HStack", alignments_1.HStack);
    __esExport("VStack", alignments_1.VStack);
    var grid_1 = require(324) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
    __esExport("Row", grid_1.Row);
    __esExport("Column", grid_1.Column);
    var html_1 = require(325) /* ./html */;
    __esExport("ContentBox", html_1.ContentBox);
    __esExport("VariadicBox", html_1.VariadicBox);
},
/* core/layout/alignments.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var layoutable_1 = require(240) /* ./layoutable */;
    var bbox_1 = require(180) /* ../util/bbox */;
    var Stack = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Stack, _super);
        function Stack() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.children = [];
            return _this;
        }
        Stack.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [5 /*yield**/, (0, tslib_1.__values)(this.children)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        };
        return Stack;
    }(layoutable_1.Layoutable));
    exports.Stack = Stack;
    Stack.__name__ = "Stack";
    var HStack = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HStack, _super);
        function HStack() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        HStack.prototype._measure = function (_viewport) {
            var e_1, _a;
            var width = 0;
            var height = 0;
            try {
                for (var _b = (0, tslib_1.__values)(this.children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var child = _c.value;
                    var size_hint = child.measure({ width: 0, height: 0 });
                    width += size_hint.width;
                    height = Math.max(height, size_hint.height);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return { width: width, height: height };
        };
        HStack.prototype._set_geometry = function (outer, inner) {
            var e_2, _a;
            _super.prototype._set_geometry.call(this, outer, inner);
            var top = this.absolute ? outer.top : 0;
            var left = this.absolute ? outer.left : 0;
            var height = outer.height;
            try {
                for (var _b = (0, tslib_1.__values)(this.children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var child = _c.value;
                    var width = child.measure({ width: 0, height: 0 }).width;
                    child.set_geometry(new bbox_1.BBox({ left: left, width: width, top: top, height: height }));
                    left += width;
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        };
        return HStack;
    }(Stack));
    exports.HStack = HStack;
    HStack.__name__ = "HStack";
    var VStack = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VStack, _super);
        function VStack() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        VStack.prototype._measure = function (_viewport) {
            var e_3, _a;
            var width = 0;
            var height = 0;
            try {
                for (var _b = (0, tslib_1.__values)(this.children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var child = _c.value;
                    var size_hint = child.measure({ width: 0, height: 0 });
                    width = Math.max(width, size_hint.width);
                    height += size_hint.height;
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return { width: width, height: height };
        };
        VStack.prototype._set_geometry = function (outer, inner) {
            var e_4, _a;
            _super.prototype._set_geometry.call(this, outer, inner);
            var left = this.absolute ? outer.left : 0;
            var top = this.absolute ? outer.top : 0;
            var width = outer.width;
            try {
                for (var _b = (0, tslib_1.__values)(this.children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var child = _c.value;
                    var height = child.measure({ width: 0, height: 0 }).height;
                    child.set_geometry(new bbox_1.BBox({ top: top, height: height, left: left, width: width }));
                    top += height;
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
        };
        return VStack;
    }(Stack));
    exports.VStack = VStack;
    VStack.__name__ = "VStack";
    var NodeLayout = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NodeLayout, _super);
        function NodeLayout() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.children = [];
            return _this;
        }
        NodeLayout.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [5 /*yield**/, (0, tslib_1.__values)(this.children)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        };
        NodeLayout.prototype._measure = function (viewport) {
            var e_5, _a;
            var _this = this;
            var _b = this.sizing, width_policy = _b.width_policy, height_policy = _b.height_policy;
            var min = Math.min, max = Math.max;
            var max_width = 0;
            var max_height = 0;
            try {
                for (var _c = (0, tslib_1.__values)(this.children), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var layout = _d.value;
                    var _e = layout.measure(viewport), width_1 = _e.width, height_1 = _e.height;
                    max_width = max(max_width, width_1);
                    max_height = max(max_height, height_1);
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return))
                        _a.call(_c);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            var width = (function () {
                var width = _this.sizing.width;
                if (viewport.width == Infinity) {
                    return width_policy == "fixed" ? width !== null && width !== void 0 ? width : max_width : max_width;
                }
                else {
                    switch (width_policy) {
                        case "fixed": return width !== null && width !== void 0 ? width : max_width;
                        case "min": return /*width != null ? min(viewport.width, width) :*/ max_width;
                        case "fit": return width != null ? min(viewport.width, width) : viewport.width;
                        case "max": return width != null ? max(viewport.width, width) : viewport.width;
                    }
                }
            })();
            var height = (function () {
                var height = _this.sizing.height;
                if (viewport.height == Infinity) {
                    return height_policy == "fixed" ? height !== null && height !== void 0 ? height : max_height : max_height;
                }
                else {
                    switch (height_policy) {
                        case "fixed": return height !== null && height !== void 0 ? height : max_height;
                        case "min": return /*height != null ? min(viewport.height, height) :*/ max_height;
                        case "fit": return height != null ? min(viewport.height, height) : viewport.height;
                        case "max": return height != null ? max(viewport.height, height) : viewport.height;
                    }
                }
            })();
            return { width: width, height: height };
        };
        NodeLayout.prototype._set_geometry = function (outer, inner) {
            var e_6, _a;
            _super.prototype._set_geometry.call(this, outer, inner);
            var bbox = this.absolute ? outer : outer.relative();
            var left = bbox.left, right = bbox.right, top = bbox.top, bottom = bbox.bottom;
            var vcenter = Math.round(bbox.vcenter);
            var hcenter = Math.round(bbox.hcenter);
            var _loop_1 = function (layout) {
                var _d = layout.sizing, margin = _d.margin, halign = _d.halign, valign = _d.valign;
                var _e = layout.measure(outer), width = _e.width, height = _e.height, inner_1 = _e.inner;
                var bbox_2 = (function () {
                    var anchor = valign + "_" + halign;
                    switch (anchor) {
                        case "start_start": // "top_left"
                            return new bbox_1.BBox({ left: left + margin.left, top: top + margin.top, width: width, height: height });
                        case "start_center": // "top_center"
                            return new bbox_1.BBox({ hcenter: hcenter, top: top + margin.top, width: width, height: height });
                        case "start_end": // "top_right"
                            return new bbox_1.BBox({ right: right - margin.right, top: top + margin.top, width: width, height: height });
                        case "center_start": // "center_left"
                            return new bbox_1.BBox({ left: left + margin.left, vcenter: vcenter, width: width, height: height });
                        case "center_center": // "center"
                            return new bbox_1.BBox({ hcenter: hcenter, vcenter: vcenter, width: width, height: height });
                        case "center_end": // "center_right"
                            return new bbox_1.BBox({ right: right - margin.right, vcenter: vcenter, width: width, height: height });
                        case "end_start": // "bottom_left"
                            return new bbox_1.BBox({ left: left + margin.left, bottom: bottom - margin.bottom, width: width, height: height });
                        case "end_center": // "bottom_center"
                            return new bbox_1.BBox({ hcenter: hcenter, bottom: bottom - margin.bottom, width: width, height: height });
                        case "end_end": // "bottom_right"
                            return new bbox_1.BBox({ right: right - margin.right, bottom: bottom - margin.bottom, width: width, height: height });
                    }
                })();
                var inner_bbox = inner_1 == null ? bbox_2 : new bbox_1.BBox({
                    left: bbox_2.left + inner_1.left,
                    top: bbox_2.top + inner_1.top,
                    right: bbox_2.right - inner_1.right,
                    bottom: bbox_2.bottom - inner_1.bottom,
                });
                layout.set_geometry(bbox_2, inner_bbox);
            };
            try {
                for (var _b = (0, tslib_1.__values)(this.children), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var layout = _c.value;
                    _loop_1(layout);
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
        };
        return NodeLayout;
    }(layoutable_1.Layoutable));
    exports.NodeLayout = NodeLayout;
    NodeLayout.__name__ = "NodeLayout";
},
/* core/layout/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var types_1 = require(239) /* ./types */;
    var layoutable_1 = require(240) /* ./layoutable */;
    var types_2 = require(125) /* ../util/types */;
    var bbox_1 = require(180) /* ../util/bbox */;
    var array_1 = require(126) /* ../util/array */;
    var max = Math.max, round = Math.round;
    var DefaultMap = /** @class */ (function () {
        function DefaultMap(def) {
            this.def = def;
            this._map = new Map();
        }
        DefaultMap.prototype.get = function (key) {
            var value = this._map.get(key);
            if (value === undefined) {
                value = this.def();
                this._map.set(key, value);
            }
            return value;
        };
        DefaultMap.prototype.apply = function (key, fn) {
            var value = this.get(key);
            this._map.set(key, fn(value));
        };
        return DefaultMap;
    }());
    DefaultMap.__name__ = "DefaultMap";
    var Container = /** @class */ (function () {
        function Container() {
            this._items = [];
            this._nrows = 0;
            this._ncols = 0;
        }
        Object.defineProperty(Container.prototype, "nrows", {
            get: function () {
                return this._nrows;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Container.prototype, "ncols", {
            get: function () {
                return this._ncols;
            },
            enumerable: false,
            configurable: true
        });
        Container.prototype.add = function (span, data) {
            var r1 = span.r1, c1 = span.c1;
            this._nrows = max(this._nrows, r1 + 1);
            this._ncols = max(this._ncols, c1 + 1);
            this._items.push({ span: span, data: data });
        };
        Container.prototype.at = function (r, c) {
            var selected = this._items.filter(function (_a) {
                var span = _a.span;
                return span.r0 <= r && r <= span.r1 &&
                    span.c0 <= c && c <= span.c1;
            });
            return selected.map(function (_a) {
                var data = _a.data;
                return data;
            });
        };
        Container.prototype.row = function (r) {
            var selected = this._items.filter(function (_a) {
                var span = _a.span;
                return span.r0 <= r && r <= span.r1;
            });
            return selected.map(function (_a) {
                var data = _a.data;
                return data;
            });
        };
        Container.prototype.col = function (c) {
            var selected = this._items.filter(function (_a) {
                var span = _a.span;
                return span.c0 <= c && c <= span.c1;
            });
            return selected.map(function (_a) {
                var data = _a.data;
                return data;
            });
        };
        Container.prototype.foreach = function (fn) {
            var e_1, _a;
            try {
                for (var _b = (0, tslib_1.__values)(this._items), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var _d = _c.value, span = _d.span, data = _d.data;
                    fn(span, data);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        Container.prototype.map = function (fn) {
            var e_2, _a;
            var result = new Container();
            try {
                for (var _b = (0, tslib_1.__values)(this._items), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var _d = _c.value, span = _d.span, data = _d.data;
                    result.add(span, fn(span, data));
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return result;
        };
        return Container;
    }());
    Container.__name__ = "Container";
    var Grid = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Grid, _super);
        function Grid(items) {
            if (items === void 0) {
                items = [];
            }
            var _this = _super.call(this) || this;
            _this.items = items;
            _this.rows = "auto";
            _this.cols = "auto";
            _this.spacing = 0;
            return _this;
        }
        Grid.prototype[Symbol.iterator] = function () {
            var _a, _b, layout, e_3_1;
            var e_3, _c;
            return (0, tslib_1.__generator)(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 5, 6, 7]);
                        _a = (0, tslib_1.__values)(this.items), _b = _a.next();
                        _d.label = 1;
                    case 1:
                        if (!!_b.done)
                            return [3 /*break*/, 4];
                        layout = _b.value.layout;
                        return [4 /*yield*/, layout];
                    case 2:
                        _d.sent();
                        _d.label = 3;
                    case 3:
                        _b = _a.next();
                        return [3 /*break*/, 1];
                    case 4: return [3 /*break*/, 7];
                    case 5:
                        e_3_1 = _d.sent();
                        e_3 = { error: e_3_1 };
                        return [3 /*break*/, 7];
                    case 6:
                        try {
                            if (_b && !_b.done && (_c = _a.return))
                                _c.call(_a);
                        }
                        finally {
                            if (e_3)
                                throw e_3.error;
                        }
                        return [7 /*endfinally*/];
                    case 7: return [2 /*return*/];
                }
            });
        };
        Grid.prototype.is_width_expanding = function () {
            if (_super.prototype.is_width_expanding.call(this))
                return true;
            if (this.sizing.width_policy == "fixed")
                return false;
            var cols = this._state.cols;
            return (0, array_1.some)(cols, function (col) { return col.policy == "max"; });
        };
        Grid.prototype.is_height_expanding = function () {
            if (_super.prototype.is_height_expanding.call(this))
                return true;
            if (this.sizing.height_policy == "fixed")
                return false;
            var rows = this._state.rows;
            return (0, array_1.some)(rows, function (row) { return row.policy == "max"; });
        };
        Grid.prototype._init = function () {
            var e_4, _a;
            var _this = this;
            var _b, _c, _d, _e;
            _super.prototype._init.call(this);
            var items = new Container();
            try {
                for (var _f = (0, tslib_1.__values)(this.items), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var _h = _g.value, layout = _h.layout, row = _h.row, col = _h.col, row_span = _h.row_span, col_span = _h.col_span;
                    if (layout.sizing.visible) {
                        var r0 = row;
                        var c0 = col;
                        var r1 = row + (row_span != null ? row_span : 1) - 1;
                        var c1 = col + (col_span != null ? col_span : 1) - 1;
                        items.add({ r0: r0, c0: c0, r1: r1, c1: c1 }, layout);
                    }
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_a = _f.return))
                        _a.call(_f);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            var nrows = items.nrows, ncols = items.ncols;
            var rows = new Array(nrows);
            var _loop_1 = function (y) {
                var row = (function () {
                    var _a;
                    var sizing = (0, types_2.isPlainObject)(_this.rows) ? (_a = _this.rows[y]) !== null && _a !== void 0 ? _a : _this.rows["*"] : _this.rows;
                    if (sizing == null)
                        return { policy: "auto" };
                    else if ((0, types_2.isNumber)(sizing))
                        return { policy: "fixed", height: sizing };
                    else if ((0, types_2.isString)(sizing))
                        return { policy: sizing };
                    else
                        return sizing;
                })();
                var align = (_b = row.align) !== null && _b !== void 0 ? _b : "auto";
                if (row.policy == "fixed")
                    rows[y] = { policy: "fixed", height: row.height, align: align };
                else if (row.policy == "min")
                    rows[y] = { policy: "min", align: align };
                else if (row.policy == "fit" || row.policy == "max")
                    rows[y] = { policy: row.policy, flex: (_c = row.flex) !== null && _c !== void 0 ? _c : 1, align: align };
                else if (row.policy == "auto") {
                    if ((0, array_1.some)(items.row(y), function (layout) { return layout.is_height_expanding(); }))
                        rows[y] = { policy: "max", flex: 1, align: align };
                    else
                        rows[y] = { policy: "min", align: align };
                }
                else
                    throw new Error("unrechable");
            };
            for (var y = 0; y < nrows; y++) {
                _loop_1(y);
            }
            var cols = new Array(ncols);
            var _loop_2 = function (x) {
                var col = (function () {
                    var _a;
                    var sizing = (0, types_2.isPlainObject)(_this.cols) ? (_a = _this.cols[x]) !== null && _a !== void 0 ? _a : _this.cols["*"] : _this.cols;
                    if (sizing == null)
                        return { policy: "auto" };
                    else if ((0, types_2.isNumber)(sizing))
                        return { policy: "fixed", width: sizing };
                    else if ((0, types_2.isString)(sizing))
                        return { policy: sizing };
                    else
                        return sizing;
                })();
                var align = (_d = col.align) !== null && _d !== void 0 ? _d : "auto";
                if (col.policy == "fixed")
                    cols[x] = { policy: "fixed", width: col.width, align: align };
                else if (col.policy == "min")
                    cols[x] = { policy: "min", align: align };
                else if (col.policy == "fit" || col.policy == "max")
                    cols[x] = { policy: col.policy, flex: (_e = col.flex) !== null && _e !== void 0 ? _e : 1, align: align };
                else if (col.policy == "auto") {
                    if ((0, array_1.some)(items.col(x), function (layout) { return layout.is_width_expanding(); }))
                        cols[x] = { policy: "max", flex: 1, align: align };
                    else
                        cols[x] = { policy: "min", align: align };
                }
                else
                    throw new Error("unrechable");
            };
            for (var x = 0; x < ncols; x++) {
                _loop_2(x);
            }
            var _j = (0, tslib_1.__read)((0, types_2.isNumber)(this.spacing) ? [this.spacing, this.spacing] : this.spacing, 2), rspacing = _j[0], cspacing = _j[1];
            this._state = { items: items, nrows: nrows, ncols: ncols, rows: rows, cols: cols, rspacing: rspacing, cspacing: cspacing };
        };
        Grid.prototype._measure_totals = function (row_heights, col_widths) {
            var _a = this._state, nrows = _a.nrows, ncols = _a.ncols, rspacing = _a.rspacing, cspacing = _a.cspacing;
            return {
                height: (0, array_1.sum)(row_heights) + (nrows - 1) * rspacing,
                width: (0, array_1.sum)(col_widths) + (ncols - 1) * cspacing,
            };
        };
        Grid.prototype._measure_cells = function (cell_viewport) {
            var _a = this._state, items = _a.items, nrows = _a.nrows, ncols = _a.ncols, rows = _a.rows, cols = _a.cols, rspacing = _a.rspacing, cspacing = _a.cspacing;
            var row_heights = new Array(nrows);
            for (var r = 0; r < nrows; r++) {
                var row = rows[r];
                row_heights[r] = row.policy == "fixed" ? row.height : 0;
            }
            var col_widths = new Array(ncols);
            for (var c = 0; c < ncols; c++) {
                var col = cols[c];
                col_widths[c] = col.policy == "fixed" ? col.width : 0;
            }
            var size_hints = new Container();
            items.foreach(function (span, layout) {
                var e_5, _a, e_6, _b;
                var r0 = span.r0, c0 = span.c0, r1 = span.r1, c1 = span.c1;
                var rspace = (r1 - r0) * rspacing;
                var cspace = (c1 - c0) * cspacing;
                var height = 0;
                for (var r = r0; r <= r1; r++) {
                    height += cell_viewport(r, c0).height;
                }
                height += rspace;
                var width = 0;
                for (var c = c0; c <= c1; c++) {
                    width += cell_viewport(r0, c).width;
                }
                width += cspace;
                var size_hint = layout.measure({ width: width, height: height });
                size_hints.add(span, { layout: layout, size_hint: size_hint });
                var size = new types_1.Sizeable(size_hint).grow_by(layout.sizing.margin);
                size.height -= rspace;
                size.width -= cspace;
                var radjustable = [];
                for (var r = r0; r <= r1; r++) {
                    var row = rows[r];
                    if (row.policy == "fixed")
                        size.height -= row.height;
                    else
                        radjustable.push(r);
                }
                if (size.height > 0) {
                    var rheight = round(size.height / radjustable.length);
                    try {
                        for (var radjustable_1 = (0, tslib_1.__values)(radjustable), radjustable_1_1 = radjustable_1.next(); !radjustable_1_1.done; radjustable_1_1 = radjustable_1.next()) {
                            var r = radjustable_1_1.value;
                            row_heights[r] = max(row_heights[r], rheight);
                        }
                    }
                    catch (e_5_1) {
                        e_5 = { error: e_5_1 };
                    }
                    finally {
                        try {
                            if (radjustable_1_1 && !radjustable_1_1.done && (_a = radjustable_1.return))
                                _a.call(radjustable_1);
                        }
                        finally {
                            if (e_5)
                                throw e_5.error;
                        }
                    }
                }
                var cadjustable = [];
                for (var c = c0; c <= c1; c++) {
                    var col = cols[c];
                    if (col.policy == "fixed")
                        size.width -= col.width;
                    else
                        cadjustable.push(c);
                }
                if (size.width > 0) {
                    var cwidth = round(size.width / cadjustable.length);
                    try {
                        for (var cadjustable_1 = (0, tslib_1.__values)(cadjustable), cadjustable_1_1 = cadjustable_1.next(); !cadjustable_1_1.done; cadjustable_1_1 = cadjustable_1.next()) {
                            var c = cadjustable_1_1.value;
                            col_widths[c] = max(col_widths[c], cwidth);
                        }
                    }
                    catch (e_6_1) {
                        e_6 = { error: e_6_1 };
                    }
                    finally {
                        try {
                            if (cadjustable_1_1 && !cadjustable_1_1.done && (_b = cadjustable_1.return))
                                _b.call(cadjustable_1);
                        }
                        finally {
                            if (e_6)
                                throw e_6.error;
                        }
                    }
                }
            });
            var size = this._measure_totals(row_heights, col_widths);
            return { size: size, row_heights: row_heights, col_widths: col_widths, size_hints: size_hints };
        };
        Grid.prototype._measure_grid = function (viewport) {
            var _a = this._state, nrows = _a.nrows, ncols = _a.ncols, rows = _a.rows, cols = _a.cols, rspacing = _a.rspacing, cspacing = _a.cspacing;
            var preferred = this._measure_cells(function (y, x) {
                var row = rows[y];
                var col = cols[x];
                return {
                    width: col.policy == "fixed" ? col.width : Infinity,
                    height: row.policy == "fixed" ? row.height : Infinity,
                };
            });
            var available_height;
            if (this.sizing.height_policy == "fixed" && this.sizing.height != null)
                available_height = this.sizing.height;
            else if (viewport.height != Infinity && this.is_height_expanding())
                available_height = viewport.height;
            else
                available_height = preferred.size.height;
            var height_flex = 0;
            for (var y = 0; y < nrows; y++) {
                var row = rows[y];
                if (row.policy == "fit" || row.policy == "max")
                    height_flex += row.flex;
                else
                    available_height -= preferred.row_heights[y];
            }
            available_height -= (nrows - 1) * rspacing;
            if (height_flex != 0 && available_height > 0) {
                for (var y = 0; y < nrows; y++) {
                    var row = rows[y];
                    if (row.policy == "fit" || row.policy == "max") {
                        var height = round(available_height * (row.flex / height_flex));
                        available_height -= height;
                        preferred.row_heights[y] = height;
                        height_flex -= row.flex;
                    }
                }
            }
            else if (available_height < 0) {
                var nadjustable = 0;
                for (var y = 0; y < nrows; y++) {
                    var row = rows[y];
                    if (row.policy != "fixed")
                        nadjustable++;
                }
                var overflow_height = -available_height;
                for (var y = 0; y < nrows; y++) {
                    var row = rows[y];
                    if (row.policy != "fixed") {
                        var height = preferred.row_heights[y];
                        var cutoff = round(overflow_height / nadjustable);
                        preferred.row_heights[y] = max(height - cutoff, 0);
                        overflow_height -= cutoff > height ? height : cutoff;
                        nadjustable--;
                    }
                }
            }
            var available_width;
            if (this.sizing.width_policy == "fixed" && this.sizing.width != null)
                available_width = this.sizing.width;
            else if (viewport.width != Infinity && this.is_width_expanding())
                available_width = viewport.width;
            else
                available_width = preferred.size.width;
            var width_flex = 0;
            for (var x = 0; x < ncols; x++) {
                var col = cols[x];
                if (col.policy == "fit" || col.policy == "max")
                    width_flex += col.flex;
                else
                    available_width -= preferred.col_widths[x];
            }
            available_width -= (ncols - 1) * cspacing;
            if (width_flex != 0 && available_width > 0) {
                for (var x = 0; x < ncols; x++) {
                    var col = cols[x];
                    if (col.policy == "fit" || col.policy == "max") {
                        var width = round(available_width * (col.flex / width_flex));
                        available_width -= width;
                        preferred.col_widths[x] = width;
                        width_flex -= col.flex;
                    }
                }
            }
            else if (available_width < 0) {
                var nadjustable = 0;
                for (var x = 0; x < ncols; x++) {
                    var col = cols[x];
                    if (col.policy != "fixed")
                        nadjustable++;
                }
                var overflow_width = -available_width;
                for (var x = 0; x < ncols; x++) {
                    var col = cols[x];
                    if (col.policy != "fixed") {
                        var width = preferred.col_widths[x];
                        var cutoff = round(overflow_width / nadjustable);
                        preferred.col_widths[x] = max(width - cutoff, 0);
                        overflow_width -= cutoff > width ? width : cutoff;
                        nadjustable--;
                    }
                }
            }
            var _b = this._measure_cells(function (y, x) {
                return {
                    width: preferred.col_widths[x],
                    height: preferred.row_heights[y],
                };
            }), row_heights = _b.row_heights, col_widths = _b.col_widths, size_hints = _b.size_hints;
            var size = this._measure_totals(row_heights, col_widths);
            return { size: size, row_heights: row_heights, col_widths: col_widths, size_hints: size_hints };
        };
        Grid.prototype._measure = function (viewport) {
            var size = this._measure_grid(viewport).size;
            return size;
        };
        Grid.prototype._set_geometry = function (outer, inner) {
            var _this = this;
            _super.prototype._set_geometry.call(this, outer, inner);
            var _a = this._state, nrows = _a.nrows, ncols = _a.ncols, rspacing = _a.rspacing, cspacing = _a.cspacing;
            var _b = this._measure_grid(outer), row_heights = _b.row_heights, col_widths = _b.col_widths, size_hints = _b.size_hints;
            var rows = this._state.rows.map(function (row, r) {
                return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, row), { top: 0, height: row_heights[r], get bottom() { return this.top + this.height; } });
            });
            var cols = this._state.cols.map(function (col, c) {
                return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, col), { left: 0, width: col_widths[c], get right() { return this.left + this.width; } });
            });
            var items = size_hints.map(function (_, item) {
                return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, item), { outer: new bbox_1.BBox(), inner: new bbox_1.BBox() });
            });
            for (var r = 0, top = !this.absolute ? 0 : outer.top; r < nrows; r++) {
                var row = rows[r];
                row.top = top;
                top += row.height + rspacing;
            }
            for (var c = 0, left = !this.absolute ? 0 : outer.left; c < ncols; c++) {
                var col = cols[c];
                col.left = left;
                left += col.width + cspacing;
            }
            function span_width(c0, c1) {
                var width = (c1 - c0) * cspacing;
                for (var c = c0; c <= c1; c++) {
                    width += cols[c].width;
                }
                return width;
            }
            function span_height(r0, r1) {
                var height = (r1 - r0) * rspacing;
                for (var r = r0; r <= r1; r++) {
                    height += rows[r].height;
                }
                return height;
            }
            items.foreach(function (_a, item) {
                var r0 = _a.r0, c0 = _a.c0, r1 = _a.r1, c1 = _a.c1;
                var layout = item.layout, size_hint = item.size_hint;
                var sizing = layout.sizing;
                var width = size_hint.width, height = size_hint.height;
                var span = {
                    width: span_width(c0, c1),
                    height: span_height(r0, r1),
                };
                var halign = c0 == c1 && cols[c0].align != "auto" ? cols[c0].align : sizing.halign;
                var valign = r0 == r1 && rows[r0].align != "auto" ? rows[r0].align : sizing.valign;
                var left = cols[c0].left;
                if (halign == "start")
                    left += sizing.margin.left;
                else if (halign == "center")
                    left += round((span.width - width) / 2);
                else if (halign == "end")
                    left += span.width - sizing.margin.right - width;
                var top = rows[r0].top;
                if (valign == "start")
                    top += sizing.margin.top;
                else if (valign == "center")
                    top += round((span.height - height) / 2);
                else if (valign == "end")
                    top += span.height - sizing.margin.bottom - height;
                item.outer = new bbox_1.BBox({ left: left, top: top, width: width, height: height });
            });
            var row_aligns = rows.map(function () {
                return {
                    start: new DefaultMap(function () { return 0; }),
                    end: new DefaultMap(function () { return 0; }),
                };
            });
            var col_aligns = cols.map(function () {
                return {
                    start: new DefaultMap(function () { return 0; }),
                    end: new DefaultMap(function () { return 0; }),
                };
            });
            items.foreach(function (_a, _b) {
                var r0 = _a.r0, c0 = _a.c0, r1 = _a.r1, c1 = _a.c1;
                var size_hint = _b.size_hint, outer = _b.outer;
                var inner = size_hint.inner;
                if (inner != null) {
                    row_aligns[r0].start.apply(outer.top, function (v) { return max(v, inner.top); });
                    row_aligns[r1].end.apply(rows[r1].bottom - outer.bottom, function (v) { return max(v, inner.bottom); });
                    col_aligns[c0].start.apply(outer.left, function (v) { return max(v, inner.left); });
                    col_aligns[c1].end.apply(cols[c1].right - outer.right, function (v) { return max(v, inner.right); });
                }
            });
            items.foreach(function (_a, item) {
                var r0 = _a.r0, c0 = _a.c0, r1 = _a.r1, c1 = _a.c1;
                var size_hint = item.size_hint, outer = item.outer;
                var inner_bbox = function (extents) {
                    var outer_bbox = _this.absolute ? outer : outer.relative();
                    var left = outer_bbox.left + extents.left;
                    var top = outer_bbox.top + extents.top;
                    var right = outer_bbox.right - extents.right;
                    var bottom = outer_bbox.bottom - extents.bottom;
                    return new bbox_1.BBox({ left: left, top: top, right: right, bottom: bottom });
                };
                if (size_hint.inner != null) {
                    var inner_1 = inner_bbox(size_hint.inner);
                    if (size_hint.align !== false) {
                        var top = row_aligns[r0].start.get(outer.top);
                        var bottom = row_aligns[r1].end.get(rows[r1].bottom - outer.bottom);
                        var left = col_aligns[c0].start.get(outer.left);
                        var right = col_aligns[c1].end.get(cols[c1].right - outer.right);
                        try {
                            inner_1 = inner_bbox({ top: top, bottom: bottom, left: left, right: right });
                        }
                        catch (_b) { }
                    }
                    item.inner = inner_1;
                }
                else
                    item.inner = outer;
            });
            items.foreach(function (_, _a) {
                var layout = _a.layout, outer = _a.outer, inner = _a.inner;
                layout.set_geometry(outer, inner);
            });
        };
        return Grid;
    }(layoutable_1.Layoutable));
    exports.Grid = Grid;
    Grid.__name__ = "Grid";
    var Row = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Row, _super);
        function Row(items) {
            var _this = _super.call(this) || this;
            _this.items = items.map(function (item, i) { return ({ layout: item, row: 0, col: i }); });
            _this.rows = "fit";
            return _this;
        }
        return Row;
    }(Grid));
    exports.Row = Row;
    Row.__name__ = "Row";
    var Column = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Column, _super);
        function Column(items) {
            var _this = _super.call(this) || this;
            _this.items = items.map(function (item, i) { return ({ layout: item, row: i, col: 0 }); });
            _this.cols = "fit";
            return _this;
        }
        return Column;
    }(Grid));
    exports.Column = Column;
    Column.__name__ = "Column";
},
/* core/layout/html.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var layoutable_1 = require(240) /* ./layoutable */;
    var types_1 = require(239) /* ./types */;
    var dom_1 = require(158) /* ../dom */;
    var ContentBox = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ContentBox, _super);
        function ContentBox(el) {
            var _this = _super.call(this) || this;
            _this.content_size = (0, dom_1.unsized)(el, function () { return new types_1.Sizeable((0, dom_1.size)(el)); });
            return _this;
        }
        ContentBox.prototype._content_size = function () {
            return this.content_size;
        };
        return ContentBox;
    }(layoutable_1.ContentLayoutable));
    exports.ContentBox = ContentBox;
    ContentBox.__name__ = "ContentBox";
    var VariadicBox = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VariadicBox, _super);
        function VariadicBox(el) {
            var _this = _super.call(this) || this;
            _this.el = el;
            return _this;
        }
        VariadicBox.prototype._measure = function (viewport) {
            var _this = this;
            var bounded = new types_1.Sizeable(viewport).bounded_to(this.sizing.size);
            return (0, dom_1.sized)(this.el, bounded, function () {
                var content = new types_1.Sizeable((0, dom_1.content_size)(_this.el));
                var _a = (0, dom_1.extents)(_this.el), border = _a.border, padding = _a.padding;
                return content.grow_by(border).grow_by(padding).map(Math.ceil);
            });
        };
        return VariadicBox;
    }(layoutable_1.Layoutable));
    exports.VariadicBox = VariadicBox;
    VariadicBox.__name__ = "VariadicBox";
    var CachedVariadicBox = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CachedVariadicBox, _super);
        function CachedVariadicBox(el) {
            var _this = _super.call(this, el) || this;
            _this._cache = new Map();
            return _this;
        }
        CachedVariadicBox.prototype._measure = function (viewport) {
            var width = viewport.width, height = viewport.height;
            var key = width + "," + height;
            var size_hint = this._cache.get(key);
            if (size_hint == null) {
                size_hint = _super.prototype._measure.call(this, viewport);
                this._cache.set(key, size_hint);
            }
            return size_hint;
        };
        CachedVariadicBox.prototype.invalidate_cache = function () {
            this._cache.clear();
        };
        return CachedVariadicBox;
    }(VariadicBox));
    exports.CachedVariadicBox = CachedVariadicBox;
    CachedVariadicBox.__name__ = "CachedVariadicBox";
},
/* core/layout/border.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var types_1 = require(239) /* ./types */;
    var layoutable_1 = require(240) /* ./layoutable */;
    var bbox_1 = require(180) /* ../util/bbox */;
    var BorderLayout = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BorderLayout, _super);
        function BorderLayout() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.min_border = { left: 0, top: 0, right: 0, bottom: 0 };
            _this.padding = { left: 0, top: 0, right: 0, bottom: 0 };
            return _this;
        }
        BorderLayout.prototype[Symbol.iterator] = function () {
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.top_panel];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.bottom_panel];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.left_panel];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, this.right_panel];
                    case 4:
                        _a.sent();
                        return [4 /*yield*/, this.center_panel];
                    case 5:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        };
        BorderLayout.prototype._measure = function (viewport) {
            var _this = this;
            viewport = new types_1.Sizeable({
                width: this.sizing.width_policy == "fixed" || viewport.width == Infinity ? this.sizing.width : viewport.width,
                height: this.sizing.height_policy == "fixed" || viewport.height == Infinity ? this.sizing.height : viewport.height,
            });
            var left_hint = this.left_panel.measure({ width: 0, height: viewport.height });
            var left = Math.max(left_hint.width, this.min_border.left) + this.padding.left;
            var right_hint = this.right_panel.measure({ width: 0, height: viewport.height });
            var right = Math.max(right_hint.width, this.min_border.right) + this.padding.right;
            var top_hint = this.top_panel.measure({ width: viewport.width, height: 0 });
            var top = Math.max(top_hint.height, this.min_border.top) + this.padding.top;
            var bottom_hint = this.bottom_panel.measure({ width: viewport.width, height: 0 });
            var bottom = Math.max(bottom_hint.height, this.min_border.bottom) + this.padding.bottom;
            var center_viewport = new types_1.Sizeable(viewport).shrink_by({ left: left, right: right, top: top, bottom: bottom });
            var center = this.center_panel.measure(center_viewport);
            var width = left + center.width + right;
            var height = top + center.height + bottom;
            var align = (function () {
                var _a = _this.center_panel.sizing, width_policy = _a.width_policy, height_policy = _a.height_policy;
                return width_policy != "fixed" && height_policy != "fixed";
            })();
            return { width: width, height: height, inner: { left: left, right: right, top: top, bottom: bottom }, align: align };
        };
        BorderLayout.prototype._set_geometry = function (outer, inner) {
            _super.prototype._set_geometry.call(this, outer, inner);
            this.center_panel.set_geometry(inner);
            var left_hint = this.left_panel.measure({ width: 0, height: outer.height });
            var right_hint = this.right_panel.measure({ width: 0, height: outer.height });
            var top_hint = this.top_panel.measure({ width: outer.width, height: 0 });
            var bottom_hint = this.bottom_panel.measure({ width: outer.width, height: 0 });
            var left = inner.left, top = inner.top, right = inner.right, bottom = inner.bottom;
            this.top_panel.set_geometry(new bbox_1.BBox({ left: left, right: right, bottom: top, height: top_hint.height }));
            this.bottom_panel.set_geometry(new bbox_1.BBox({ left: left, right: right, top: bottom, height: bottom_hint.height }));
            this.left_panel.set_geometry(new bbox_1.BBox({ top: top, bottom: bottom, right: left, width: left_hint.width }));
            this.right_panel.set_geometry(new bbox_1.BBox({ top: top, bottom: bottom, left: right, width: right_hint.width }));
        };
        return BorderLayout;
    }(layoutable_1.Layoutable));
    exports.BorderLayout = BorderLayout;
    BorderLayout.__name__ = "BorderLayout";
},
/* models/annotations/label.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var text_annotation_1 = require(234) /* ./text_annotation */;
    var math_1 = require(117) /* ../../core/util/math */;
    var enums_1 = require(135) /* ../../core/enums */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var side_panel_1 = require(238) /* ../../core/layout/side_panel */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var LabelView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LabelView, _super);
        function LabelView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LabelView.prototype.update_layout = function () {
            var _this = this;
            var panel = this.panel;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, function () { return _this.get_size(); }, false);
            else
                this.layout = undefined;
        };
        LabelView.prototype._get_size = function () {
            var text = this.model.text;
            var graphics = new graphics_1.TextBox({ text: text });
            var _b = this.model, angle = _b.angle, angle_units = _b.angle_units;
            graphics.angle = (0, math_1.resolve_angle)(angle, angle_units);
            graphics.visuals = this.visuals.text.values();
            var _c = graphics.size(), width = _c.width, height = _c.height;
            return { width: width, height: height };
        };
        LabelView.prototype._render = function () {
            var _b = this.model, angle = _b.angle, angle_units = _b.angle_units;
            var rotation = (0, math_1.resolve_angle)(angle, angle_units);
            var panel = this.layout != null ? this.layout : this.plot_view.frame;
            var xscale = this.coordinates.x_scale;
            var yscale = this.coordinates.y_scale;
            var sx = this.model.x_units == "data" ? xscale.compute(this.model.x) : panel.bbox.xview.compute(this.model.x);
            var sy = this.model.y_units == "data" ? yscale.compute(this.model.y) : panel.bbox.yview.compute(this.model.y);
            sx += this.model.x_offset;
            sy -= this.model.y_offset;
            var draw = this.model.render_mode == "canvas" ? this._canvas_text.bind(this) : this._css_text.bind(this);
            draw(this.layer.ctx, this.model.text, sx, sy, rotation);
        };
        return LabelView;
    }(text_annotation_1.TextAnnotationView));
    exports.LabelView = LabelView;
    LabelView.__name__ = "LabelView";
    var Label = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Label, _super);
        function Label(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Label;
    }(text_annotation_1.TextAnnotation));
    exports.Label = Label;
    _a = Label;
    Label.__name__ = "Label";
    (function () {
        _a.prototype.default_view = LabelView;
        _a.mixins([
            mixins.Text,
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
        ]);
        _a.define(function (_b) {
            var Number = _b.Number, String = _b.String, Angle = _b.Angle;
            return ({
                x: [Number],
                x_units: [enums_1.SpatialUnits, "data"],
                y: [Number],
                y_units: [enums_1.SpatialUnits, "data"],
                text: [String, ""],
                angle: [Angle, 0],
                angle_units: [enums_1.AngleUnits, "rad"],
                x_offset: [Number, 0],
                y_offset: [Number, 0],
            });
        });
        _a.override({
            background_fill_color: null,
            border_line_color: null,
        });
    })();
},
/* models/annotations/label_set.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var data_annotation_1 = require(184) /* ./data_annotation */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var enums_1 = require(135) /* ../../core/enums */;
    var dom_1 = require(158) /* ../../core/dom */;
    var graphics_1 = require(235) /* ../../core/graphics */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var assert_1 = require(127) /* ../../core/util/assert */;
    var LabelSetView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LabelSetView, _super);
        function LabelSetView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LabelSetView.prototype.set_data = function (source) {
            var e_1, _b;
            var _c;
            _super.prototype.set_data.call(this, source);
            (_c = this.els) === null || _c === void 0 ? void 0 : _c.forEach(function (el) { return (0, dom_1.remove)(el); });
            if (this.model.render_mode == "css") {
                var els = this.els = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.text), false).map(function () { return (0, dom_1.div)({ style: { display: "none" } }); });
                try {
                    for (var els_1 = (0, tslib_1.__values)(els), els_1_1 = els_1.next(); !els_1_1.done; els_1_1 = els_1.next()) {
                        var el = els_1_1.value;
                        this.plot_view.canvas_view.add_overlay(el);
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (els_1_1 && !els_1_1.done && (_b = els_1.return))
                            _b.call(els_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
            else
                delete this.els;
        };
        LabelSetView.prototype.remove = function () {
            var _b;
            (_b = this.els) === null || _b === void 0 ? void 0 : _b.forEach(function (el) { return (0, dom_1.remove)(el); });
            _super.prototype.remove.call(this);
        };
        LabelSetView.prototype._rerender = function () {
            if (this.model.render_mode == "css")
                this.render();
            else
                this.request_render();
        };
        LabelSetView.prototype.map_data = function () {
            var _b = this.coordinates, x_scale = _b.x_scale, y_scale = _b.y_scale;
            var panel = this.layout != null ? this.layout : this.plot_view.frame;
            this.sx = this.model.x_units == "data" ? x_scale.v_compute(this._x) : panel.bbox.xview.v_compute(this._x);
            this.sy = this.model.y_units == "data" ? y_scale.v_compute(this._y) : panel.bbox.yview.v_compute(this._y);
        };
        LabelSetView.prototype.paint = function () {
            var draw = this.model.render_mode == "canvas" ? this._v_canvas_text.bind(this) : this._v_css_text.bind(this);
            var ctx = this.layer.ctx;
            for (var i = 0, end = this.text.length; i < end; i++) {
                var x_offset_i = this.x_offset.get(i);
                var y_offset_i = this.y_offset.get(i);
                var sx_i = this.sx[i] + x_offset_i;
                var sy_i = this.sy[i] - y_offset_i;
                var angle_i = this.angle.get(i);
                var text_i = this.text.get(i);
                draw(ctx, i, text_i, sx_i, sy_i, angle_i);
            }
        };
        LabelSetView.prototype._v_canvas_text = function (ctx, i, text, sx, sy, angle) {
            var graphics = new graphics_1.TextBox({ text: text });
            graphics.angle = angle;
            graphics.position = { sx: sx, sy: sy };
            graphics.visuals = this.visuals.text.values(i);
            var _b = this.visuals, background_fill = _b.background_fill, border_line = _b.border_line;
            if (background_fill.doit || border_line.doit) {
                var _c = graphics.rect(), p0 = _c.p0, p1 = _c.p1, p2 = _c.p2, p3 = _c.p3;
                ctx.beginPath();
                ctx.moveTo(p0.x, p0.y);
                ctx.lineTo(p1.x, p1.y);
                ctx.lineTo(p2.x, p2.y);
                ctx.lineTo(p3.x, p3.y);
                ctx.closePath();
                this.visuals.background_fill.apply(ctx, i);
                this.visuals.border_line.apply(ctx, i);
            }
            if (this.visuals.text.doit)
                graphics.paint(ctx);
        };
        LabelSetView.prototype._v_css_text = function (ctx, i, text, sx, sy, angle) {
            var _this = this;
            (0, assert_1.assert)(this.els != null);
            var el = this.els[i];
            el.textContent = text;
            this.visuals.text.set_vectorize(ctx, i);
            el.style.position = "absolute";
            el.style.left = sx + "px";
            el.style.top = sy + "px";
            el.style.color = ctx.fillStyle;
            el.style.font = ctx.font;
            el.style.lineHeight = "normal"; // needed to prevent ipynb css override
            el.style.whiteSpace = "pre";
            var _b = (0, tslib_1.__read)((function () {
                switch (_this.visuals.text.text_align.get(i)) {
                    case "left": return ["left", "0%"];
                    case "center": return ["center", "-50%"];
                    case "right": return ["right", "-100%"];
                }
            })(), 2), x_anchor = _b[0], x_t = _b[1];
            var _c = (0, tslib_1.__read)((function () {
                switch (_this.visuals.text.text_baseline.get(i)) {
                    case "top": return ["top", "0%"];
                    case "middle": return ["center", "-50%"];
                    case "bottom": return ["bottom", "-100%"];
                    default: return ["center", "-50%"]; // "baseline"
                }
            })(), 2), y_anchor = _c[0], y_t = _c[1];
            var transform = "translate(" + x_t + ", " + y_t + ")";
            if (angle) {
                transform += "rotate(" + angle + "rad)";
            }
            el.style.transformOrigin = x_anchor + " " + y_anchor;
            el.style.transform = transform;
            if (this.layout == null) {
                // const {bbox} = this.plot_view.frame
                // const {left, right, top, bottom} = bbox
                // el.style.clipPath = ???
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_vectorize(ctx, i);
                el.style.backgroundColor = ctx.fillStyle;
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_vectorize(ctx, i);
                // attempt to support vector-style ("8 4 8") line dashing for css mode
                el.style.borderStyle = ctx.lineDash.length < 2 ? "solid" : "dashed";
                el.style.borderWidth = ctx.lineWidth + "px";
                el.style.borderColor = ctx.strokeStyle;
            }
            (0, dom_1.display)(el);
        };
        return LabelSetView;
    }(data_annotation_1.DataAnnotationView));
    exports.LabelSetView = LabelSetView;
    LabelSetView.__name__ = "LabelSetView";
    var LabelSet = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LabelSet, _super);
        function LabelSet(attrs) {
            return _super.call(this, attrs) || this;
        }
        return LabelSet;
    }(data_annotation_1.DataAnnotation));
    exports.LabelSet = LabelSet;
    _a = LabelSet;
    LabelSet.__name__ = "LabelSet";
    (function () {
        _a.prototype.default_view = LabelSetView;
        _a.mixins([
            mixins.TextVector,
            ["border_", mixins.LineVector],
            ["background_", mixins.FillVector],
        ]);
        _a.define(function () {
            return ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y: [p.YCoordinateSpec, { field: "y" }],
                x_units: [enums_1.SpatialUnits, "data"],
                y_units: [enums_1.SpatialUnits, "data"],
                text: [p.StringSpec, { field: "text" }],
                angle: [p.AngleSpec, 0],
                x_offset: [p.NumberSpec, { value: 0 }],
                y_offset: [p.NumberSpec, { value: 0 }],
                /** @deprecated */
                render_mode: [enums_1.RenderMode, "canvas"],
            });
        });
        _a.override({
            background_fill_color: null,
            border_line_color: null,
        });
    })();
},
/* models/annotations/legend.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var legend_item_1 = require(330) /* ./legend_item */;
    var enums_1 = require(135) /* ../../core/enums */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var signaling_1 = require(130) /* ../../core/signaling */;
    var side_panel_1 = require(238) /* ../../core/layout/side_panel */;
    var text_1 = require(236) /* ../../core/util/text */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    var array_1 = require(126) /* ../../core/util/array */;
    var types_1 = require(125) /* ../../core/util/types */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var LegendView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LegendView, _super);
        function LegendView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LegendView.prototype.update_layout = function () {
            var _this = this;
            var panel = this.panel;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, function () { return _this.get_size(); });
            else
                this.layout = undefined;
        };
        LegendView.prototype.cursor = function (_sx, _sy) {
            return this.model.click_policy == "none" ? null : "pointer";
        };
        Object.defineProperty(LegendView.prototype, "legend_padding", {
            get: function () {
                return this.model.border_line_color != null ? this.model.padding : 0;
            },
            enumerable: false,
            configurable: true
        });
        LegendView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.change, function () { return _this.request_render(); });
            this.connect(this.model.item_change, function () { return _this.request_render(); });
        };
        LegendView.prototype.compute_legend_bbox = function () {
            var e_1, _b, e_2, _c;
            var legend_names = this.model.get_legend_names();
            var _d = this.model, glyph_height = _d.glyph_height, glyph_width = _d.glyph_width;
            var _e = this.model, label_height = _e.label_height, label_width = _e.label_width;
            this.max_label_height = (0, array_1.max)([(0, text_1.font_metrics)(this.visuals.label_text.font_value()).height, label_height, glyph_height]);
            // this is to measure text properties
            var ctx = this.layer.ctx;
            ctx.save();
            this.visuals.label_text.set_value(ctx);
            this.text_widths = new Map();
            try {
                for (var legend_names_1 = (0, tslib_1.__values)(legend_names), legend_names_1_1 = legend_names_1.next(); !legend_names_1_1.done; legend_names_1_1 = legend_names_1.next()) {
                    var name = legend_names_1_1.value;
                    this.text_widths.set(name, (0, array_1.max)([ctx.measureText(name).width, label_width]));
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (legend_names_1_1 && !legend_names_1_1.done && (_b = legend_names_1.return))
                        _b.call(legend_names_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            this.visuals.title_text.set_value(ctx);
            this.title_height = this.model.title ? (0, text_1.font_metrics)(this.visuals.title_text.font_value()).height + this.model.title_standoff : 0;
            this.title_width = this.model.title ? ctx.measureText(this.model.title).width : 0;
            ctx.restore();
            var max_label_width = Math.max((0, array_1.max)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.text_widths.values()), false)), 0);
            var legend_margin = this.model.margin;
            var legend_padding = this.legend_padding;
            var legend_spacing = this.model.spacing;
            var label_standoff = this.model.label_standoff;
            var legend_height, legend_width;
            if (this.model.orientation == "vertical") {
                legend_height = legend_names.length * this.max_label_height + Math.max(legend_names.length - 1, 0) * legend_spacing + 2 * legend_padding + this.title_height;
                legend_width = (0, array_1.max)([(max_label_width + glyph_width + label_standoff + 2 * legend_padding), this.title_width + 2 * legend_padding]);
            }
            else {
                var item_width = 2 * legend_padding + Math.max(legend_names.length - 1, 0) * legend_spacing;
                try {
                    for (var _f = (0, tslib_1.__values)(this.text_widths), _g = _f.next(); !_g.done; _g = _f.next()) {
                        var _h = (0, tslib_1.__read)(_g.value, 2), width = _h[1];
                        item_width += (0, array_1.max)([width, label_width]) + glyph_width + label_standoff;
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (_g && !_g.done && (_c = _f.return))
                            _c.call(_f);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
                legend_width = (0, array_1.max)([this.title_width + 2 * legend_padding, item_width]);
                legend_height = this.max_label_height + this.title_height + 2 * legend_padding;
            }
            var panel = this.layout != null ? this.layout : this.plot_view.frame;
            var _j = (0, tslib_1.__read)(panel.bbox.ranges, 2), hr = _j[0], vr = _j[1];
            var location = this.model.location;
            var sx, sy;
            if ((0, types_1.isString)(location)) {
                switch (location) {
                    case "top_left":
                        sx = hr.start + legend_margin;
                        sy = vr.start + legend_margin;
                        break;
                    case "top":
                    case "top_center":
                        sx = (hr.end + hr.start) / 2 - legend_width / 2;
                        sy = vr.start + legend_margin;
                        break;
                    case "top_right":
                        sx = hr.end - legend_margin - legend_width;
                        sy = vr.start + legend_margin;
                        break;
                    case "bottom_right":
                        sx = hr.end - legend_margin - legend_width;
                        sy = vr.end - legend_margin - legend_height;
                        break;
                    case "bottom":
                    case "bottom_center":
                        sx = (hr.end + hr.start) / 2 - legend_width / 2;
                        sy = vr.end - legend_margin - legend_height;
                        break;
                    case "bottom_left":
                        sx = hr.start + legend_margin;
                        sy = vr.end - legend_margin - legend_height;
                        break;
                    case "left":
                    case "center_left":
                        sx = hr.start + legend_margin;
                        sy = (vr.end + vr.start) / 2 - legend_height / 2;
                        break;
                    case "center":
                    case "center_center":
                        sx = (hr.end + hr.start) / 2 - legend_width / 2;
                        sy = (vr.end + vr.start) / 2 - legend_height / 2;
                        break;
                    case "right":
                    case "center_right":
                        sx = hr.end - legend_margin - legend_width;
                        sy = (vr.end + vr.start) / 2 - legend_height / 2;
                        break;
                }
            }
            else if ((0, types_1.isArray)(location) && location.length == 2) {
                var _k = (0, tslib_1.__read)(location, 2), vx = _k[0], vy = _k[1];
                sx = panel.bbox.xview.compute(vx);
                sy = panel.bbox.yview.compute(vy) - legend_height;
            }
            else
                (0, assert_1.unreachable)();
            return new bbox_1.BBox({ left: sx, top: sy, width: legend_width, height: legend_height });
        };
        LegendView.prototype.interactive_bbox = function () {
            return this.compute_legend_bbox();
        };
        LegendView.prototype.interactive_hit = function (sx, sy) {
            var bbox = this.interactive_bbox();
            return bbox.contains(sx, sy);
        };
        LegendView.prototype.on_hit = function (sx, sy) {
            var e_3, _b, e_4, _c, _d, _e, e_5, _f, e_6, _g;
            var yoffset;
            var glyph_width = this.model.glyph_width;
            var legend_padding = this.legend_padding;
            var legend_spacing = this.model.spacing;
            var label_standoff = this.model.label_standoff;
            var xoffset = (yoffset = legend_padding);
            var legend_bbox = this.compute_legend_bbox();
            var vertical = this.model.orientation == "vertical";
            try {
                for (var _h = (0, tslib_1.__values)(this.model.items), _j = _h.next(); !_j.done; _j = _h.next()) {
                    var item = _j.value;
                    var labels = item.get_labels_list_from_label_prop();
                    try {
                        for (var labels_1 = (e_4 = void 0, (0, tslib_1.__values)(labels)), labels_1_1 = labels_1.next(); !labels_1_1.done; labels_1_1 = labels_1.next()) {
                            var label = labels_1_1.value;
                            var x1 = legend_bbox.x + xoffset;
                            var y1 = legend_bbox.y + yoffset + this.title_height;
                            var w = void 0, h = void 0;
                            if (vertical)
                                _d = (0, tslib_1.__read)([legend_bbox.width - 2 * legend_padding, this.max_label_height], 2), w = _d[0], h = _d[1];
                            else
                                _e = (0, tslib_1.__read)([this.text_widths.get(label) + glyph_width + label_standoff, this.max_label_height], 2), w = _e[0], h = _e[1];
                            var bbox = new bbox_1.BBox({ left: x1, top: y1, width: w, height: h });
                            if (bbox.contains(sx, sy)) {
                                switch (this.model.click_policy) {
                                    case "hide": {
                                        try {
                                            for (var _k = (e_5 = void 0, (0, tslib_1.__values)(item.renderers)), _l = _k.next(); !_l.done; _l = _k.next()) {
                                                var r = _l.value;
                                                r.visible = !r.visible;
                                            }
                                        }
                                        catch (e_5_1) {
                                            e_5 = { error: e_5_1 };
                                        }
                                        finally {
                                            try {
                                                if (_l && !_l.done && (_f = _k.return))
                                                    _f.call(_k);
                                            }
                                            finally {
                                                if (e_5)
                                                    throw e_5.error;
                                            }
                                        }
                                        break;
                                    }
                                    case "mute": {
                                        try {
                                            for (var _m = (e_6 = void 0, (0, tslib_1.__values)(item.renderers)), _o = _m.next(); !_o.done; _o = _m.next()) {
                                                var r = _o.value;
                                                r.muted = !r.muted;
                                            }
                                        }
                                        catch (e_6_1) {
                                            e_6 = { error: e_6_1 };
                                        }
                                        finally {
                                            try {
                                                if (_o && !_o.done && (_g = _m.return))
                                                    _g.call(_m);
                                            }
                                            finally {
                                                if (e_6)
                                                    throw e_6.error;
                                            }
                                        }
                                        break;
                                    }
                                }
                                return true;
                            }
                            if (vertical)
                                yoffset += this.max_label_height + legend_spacing;
                            else
                                xoffset += this.text_widths.get(label) + glyph_width + label_standoff + legend_spacing;
                        }
                    }
                    catch (e_4_1) {
                        e_4 = { error: e_4_1 };
                    }
                    finally {
                        try {
                            if (labels_1_1 && !labels_1_1.done && (_c = labels_1.return))
                                _c.call(labels_1);
                        }
                        finally {
                            if (e_4)
                                throw e_4.error;
                        }
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_j && !_j.done && (_b = _h.return))
                        _b.call(_h);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return false;
        };
        LegendView.prototype._render = function () {
            var e_7, _b;
            if (this.model.items.length == 0)
                return;
            if (!(0, array_1.some)(this.model.items, function (item) { return item.visible; }))
                return;
            try {
                // set a backref on render so that items can later signal item_change upates
                // on the model to trigger a re-render
                for (var _c = (0, tslib_1.__values)(this.model.items), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var item = _d.value;
                    item.legend = this.model;
                }
            }
            catch (e_7_1) {
                e_7 = { error: e_7_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_7)
                        throw e_7.error;
                }
            }
            var ctx = this.layer.ctx;
            var bbox = this.compute_legend_bbox();
            ctx.save();
            this._draw_legend_box(ctx, bbox);
            this._draw_legend_items(ctx, bbox);
            this._draw_title(ctx, bbox);
            ctx.restore();
        };
        LegendView.prototype._draw_legend_box = function (ctx, bbox) {
            ctx.beginPath();
            ctx.rect(bbox.x, bbox.y, bbox.width, bbox.height);
            this.visuals.background_fill.apply(ctx);
            this.visuals.border_line.apply(ctx);
        };
        LegendView.prototype._draw_legend_items = function (ctx, bbox) {
            var e_8, _b;
            var _this = this;
            var _c = this.model, glyph_width = _c.glyph_width, glyph_height = _c.glyph_height;
            var legend_padding = this.legend_padding;
            var legend_spacing = this.model.spacing;
            var label_standoff = this.model.label_standoff;
            var xoffset = legend_padding;
            var yoffset = legend_padding;
            var vertical = this.model.orientation == "vertical";
            var _loop_1 = function (item) {
                var e_9, _f, e_10, _g, _h, _j;
                if (!item.visible)
                    return "continue";
                var labels = item.get_labels_list_from_label_prop();
                var field = item.get_field_from_label_prop();
                if (labels.length == 0)
                    return "continue";
                var active = (function () {
                    switch (_this.model.click_policy) {
                        case "none": return true;
                        case "hide": return (0, array_1.every)(item.renderers, function (r) { return r.visible; });
                        case "mute": return (0, array_1.every)(item.renderers, function (r) { return !r.muted; });
                    }
                })();
                try {
                    for (var labels_2 = (e_9 = void 0, (0, tslib_1.__values)(labels)), labels_2_1 = labels_2.next(); !labels_2_1.done; labels_2_1 = labels_2.next()) {
                        var label = labels_2_1.value;
                        var x1 = bbox.x + xoffset;
                        var y1 = bbox.y + yoffset + this_1.title_height;
                        var x2 = x1 + glyph_width;
                        var y2 = y1 + glyph_height;
                        if (vertical)
                            yoffset += this_1.max_label_height + legend_spacing;
                        else
                            xoffset += this_1.text_widths.get(label) + glyph_width + label_standoff + legend_spacing;
                        this_1.visuals.label_text.set_value(ctx);
                        ctx.fillText(label, x2 + label_standoff, y1 + this_1.max_label_height / 2.0);
                        try {
                            for (var _k = (e_10 = void 0, (0, tslib_1.__values)(item.renderers)), _l = _k.next(); !_l.done; _l = _k.next()) {
                                var r = _l.value;
                                var view = this_1.plot_view.renderer_view(r);
                                view === null || view === void 0 ? void 0 : view.draw_legend(ctx, x1, x2, y1, y2, field, label, item.index);
                            }
                        }
                        catch (e_10_1) {
                            e_10 = { error: e_10_1 };
                        }
                        finally {
                            try {
                                if (_l && !_l.done && (_g = _k.return))
                                    _g.call(_k);
                            }
                            finally {
                                if (e_10)
                                    throw e_10.error;
                            }
                        }
                        if (!active) {
                            var w = void 0, h = void 0;
                            if (vertical)
                                _h = (0, tslib_1.__read)([bbox.width - 2 * legend_padding, this_1.max_label_height], 2), w = _h[0], h = _h[1];
                            else
                                _j = (0, tslib_1.__read)([this_1.text_widths.get(label) + glyph_width + label_standoff, this_1.max_label_height], 2), w = _j[0], h = _j[1];
                            ctx.beginPath();
                            ctx.rect(x1, y1, w, h);
                            this_1.visuals.inactive_fill.set_value(ctx);
                            ctx.fill();
                        }
                    }
                }
                catch (e_9_1) {
                    e_9 = { error: e_9_1 };
                }
                finally {
                    try {
                        if (labels_2_1 && !labels_2_1.done && (_f = labels_2.return))
                            _f.call(labels_2);
                    }
                    finally {
                        if (e_9)
                            throw e_9.error;
                    }
                }
            };
            var this_1 = this;
            try {
                for (var _d = (0, tslib_1.__values)(this.model.items), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var item = _e.value;
                    _loop_1(item);
                }
            }
            catch (e_8_1) {
                e_8 = { error: e_8_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_8)
                        throw e_8.error;
                }
            }
        };
        LegendView.prototype._draw_title = function (ctx, bbox) {
            var title = this.model.title;
            if (!title || !this.visuals.title_text.doit)
                return;
            ctx.save();
            ctx.translate(bbox.x0, bbox.y0 + this.title_height);
            this.visuals.title_text.set_value(ctx);
            ctx.fillText(title, this.legend_padding, this.legend_padding - this.model.title_standoff);
            ctx.restore();
        };
        LegendView.prototype._get_size = function () {
            var _b = this.compute_legend_bbox(), width = _b.width, height = _b.height;
            return {
                width: width + 2 * this.model.margin,
                height: height + 2 * this.model.margin,
            };
        };
        return LegendView;
    }(annotation_1.AnnotationView));
    exports.LegendView = LegendView;
    LegendView.__name__ = "LegendView";
    var Legend = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Legend, _super);
        function Legend(attrs) {
            return _super.call(this, attrs) || this;
        }
        Legend.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.item_change = new signaling_1.Signal0(this, "item_change");
        };
        Legend.prototype.get_legend_names = function () {
            var e_11, _b;
            var legend_names = [];
            try {
                for (var _c = (0, tslib_1.__values)(this.items), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var item = _d.value;
                    var labels = item.get_labels_list_from_label_prop();
                    legend_names.push.apply(legend_names, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(labels), false));
                }
            }
            catch (e_11_1) {
                e_11 = { error: e_11_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_11)
                        throw e_11.error;
                }
            }
            return legend_names;
        };
        return Legend;
    }(annotation_1.Annotation));
    exports.Legend = Legend;
    _a = Legend;
    Legend.__name__ = "Legend";
    (function () {
        _a.prototype.default_view = LegendView;
        _a.mixins([
            ["label_", mixins.Text],
            ["title_", mixins.Text],
            ["inactive_", mixins.Fill],
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
        ]);
        _a.define(function (_b) {
            var Number = _b.Number, String = _b.String, Array = _b.Array, Tuple = _b.Tuple, Or = _b.Or, Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                orientation: [enums_1.Orientation, "vertical"],
                location: [Or(enums_1.LegendLocation, Tuple(Number, Number)), "top_right"],
                title: [Nullable(String), null],
                title_standoff: [Number, 5],
                label_standoff: [Number, 5],
                glyph_height: [Number, 20],
                glyph_width: [Number, 20],
                label_height: [Number, 20],
                label_width: [Number, 20],
                margin: [Number, 10],
                padding: [Number, 10],
                spacing: [Number, 3],
                items: [Array(Ref(legend_item_1.LegendItem)), []],
                click_policy: [enums_1.LegendClickPolicy, "none"],
            });
        });
        _a.override({
            border_line_color: "#e5e5e5",
            border_line_alpha: 0.5,
            border_line_width: 1,
            background_fill_color: "#ffffff",
            background_fill_alpha: 0.95,
            inactive_fill_color: "white",
            inactive_fill_alpha: 0.7,
            label_text_font_size: "13px",
            label_text_baseline: "middle",
            title_text_font_size: "13px",
            title_text_font_style: "italic",
        });
    })();
},
/* models/annotations/legend_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var glyph_renderer_1 = require(290) /* ../renderers/glyph_renderer */;
    var columnar_data_source_1 = require(185) /* ../sources/columnar_data_source */;
    var vectorization_1 = require(331) /* ../../core/vectorization */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var logging_1 = require(134) /* ../../core/logging */;
    var array_1 = require(126) /* ../../core/util/array */;
    var LegendItem = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LegendItem, _super);
        function LegendItem(attrs) {
            return _super.call(this, attrs) || this;
        }
        /*protected*/ LegendItem.prototype._check_data_sources_on_renderers = function () {
            var e_1, _b;
            var field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length < 1) {
                    return false;
                }
                var source = this.renderers[0].data_source;
                if (source != null) {
                    try {
                        for (var _c = (0, tslib_1.__values)(this.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                            var r = _d.value;
                            if (r.data_source != source) {
                                return false;
                            }
                        }
                    }
                    catch (e_1_1) {
                        e_1 = { error: e_1_1 };
                    }
                    finally {
                        try {
                            if (_d && !_d.done && (_b = _c.return))
                                _b.call(_c);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                    }
                }
            }
            return true;
        };
        /*protected*/ LegendItem.prototype._check_field_label_on_data_source = function () {
            var field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length < 1) {
                    return false;
                }
                var source = this.renderers[0].data_source;
                if (source != null && !(0, array_1.includes)(source.columns(), field)) {
                    return false;
                }
            }
            return true;
        };
        LegendItem.prototype.initialize = function () {
            var _this = this;
            _super.prototype.initialize.call(this);
            this.legend = null;
            this.connect(this.change, function () { var _b; return (_b = _this.legend) === null || _b === void 0 ? void 0 : _b.item_change.emit(); });
            // Validate data_sources match
            var data_source_validation = this._check_data_sources_on_renderers();
            if (!data_source_validation)
                logging_1.logger.error("Non matching data sources on legend item renderers");
            // Validate label in data_source
            var field_validation = this._check_field_label_on_data_source();
            if (!field_validation)
                logging_1.logger.error("Bad column name on label: " + this.label);
        };
        LegendItem.prototype.get_field_from_label_prop = function () {
            var label = this.label;
            return (0, vectorization_1.isField)(label) ? label.field : null;
        };
        LegendItem.prototype.get_labels_list_from_label_prop = function () {
            if (!this.visible)
                return [];
            if ((0, vectorization_1.isValue)(this.label)) {
                var value = this.label.value;
                return value != null ? [value] : [];
            }
            var field = this.get_field_from_label_prop();
            if (field != null) {
                var source = void 0;
                if (this.renderers[0] && this.renderers[0].data_source != null)
                    source = this.renderers[0].data_source;
                else
                    return ["No source found"];
                if (source instanceof columnar_data_source_1.ColumnarDataSource) {
                    var data = source.get_column(field);
                    if (data != null)
                        return (0, array_1.uniq)(Array.from(data));
                    else
                        return ["Invalid field"];
                }
            }
            return [];
        };
        return LegendItem;
    }(model_1.Model));
    exports.LegendItem = LegendItem;
    _a = LegendItem;
    LegendItem.__name__ = "LegendItem";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Int = _b.Int, Array = _b.Array, Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                label: [p.NullStringSpec, null],
                renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
                index: [Nullable(Int), null],
                visible: [Boolean, true],
            });
        });
    })();
},
/* core/vectorization.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(125) /* ./util/types */;
    function isValue(obj) {
        return (0, types_1.isPlainObject)(obj) && "value" in obj;
    }
    exports.isValue = isValue;
    function isField(obj) {
        return (0, types_1.isPlainObject)(obj) && "field" in obj;
    }
    exports.isField = isField;
    function isExpr(obj) {
        return (0, types_1.isPlainObject)(obj) && "expr" in obj;
    }
    exports.isExpr = isExpr;
},
/* models/annotations/poly_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var enums_1 = require(135) /* ../../core/enums */;
    var PolyAnnotationView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolyAnnotationView, _super);
        function PolyAnnotationView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PolyAnnotationView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.change, function () { return _this.request_render(); });
        };
        PolyAnnotationView.prototype._render = function () {
            var _b = this.model, xs = _b.xs, ys = _b.ys;
            if (xs.length != ys.length)
                return;
            var n = xs.length;
            if (n < 3)
                return;
            var frame = this.plot_view.frame;
            var ctx = this.layer.ctx;
            var xscale = this.coordinates.x_scale;
            var yscale = this.coordinates.y_scale;
            var screen = this.model.screen;
            function _calc_dim(values, units, scale, view) {
                if (screen)
                    return values;
                else
                    return units == "data" ? scale.v_compute(values) : view.v_compute(values);
            }
            var sxs = _calc_dim(xs, this.model.xs_units, xscale, frame.bbox.xview);
            var sys = _calc_dim(ys, this.model.ys_units, yscale, frame.bbox.yview);
            ctx.beginPath();
            for (var i = 0; i < n; i++) {
                ctx.lineTo(sxs[i], sys[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
            this.visuals.line.apply(ctx);
        };
        return PolyAnnotationView;
    }(annotation_1.AnnotationView));
    exports.PolyAnnotationView = PolyAnnotationView;
    PolyAnnotationView.__name__ = "PolyAnnotationView";
    var PolyAnnotation = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolyAnnotation, _super);
        function PolyAnnotation(attrs) {
            return _super.call(this, attrs) || this;
        }
        PolyAnnotation.prototype.update = function (_b) {
            var xs = _b.xs, ys = _b.ys;
            this.setv({ xs: xs, ys: ys, screen: true }, { check_eq: false }); // XXX: because of inplace updates in tools
        };
        return PolyAnnotation;
    }(annotation_1.Annotation));
    exports.PolyAnnotation = PolyAnnotation;
    _a = PolyAnnotation;
    PolyAnnotation.__name__ = "PolyAnnotation";
    (function () {
        _a.prototype.default_view = PolyAnnotationView;
        _a.mixins([mixins.Line, mixins.Fill, mixins.Hatch]);
        _a.define(function (_b) {
            var Number = _b.Number, Array = _b.Array;
            return ({
                xs: [Array(Number), []],
                xs_units: [enums_1.SpatialUnits, "data"],
                ys: [Array(Number), []],
                ys_units: [enums_1.SpatialUnits, "data"],
            });
        });
        _a.internal(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                screen: [Boolean, false],
            });
        });
        _a.override({
            fill_color: "#fff9ba",
            fill_alpha: 0.4,
            line_color: "#cccccc",
            line_alpha: 0.3,
        });
    })();
},
/* models/annotations/slope.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var SlopeView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SlopeView, _super);
        function SlopeView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SlopeView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.change, function () { return _this.request_render(); });
        };
        SlopeView.prototype._render = function () {
            var _b = this.model, gradient = _b.gradient, y_intercept = _b.y_intercept;
            if (gradient == null || y_intercept == null)
                return;
            var frame = this.plot_view.frame;
            var xscale = this.coordinates.x_scale;
            var yscale = this.coordinates.y_scale;
            var sy_start, sy_end, sx_start, sx_end;
            if (gradient == 0) {
                sy_start = yscale.compute(y_intercept);
                sy_end = sy_start;
                sx_start = frame.bbox.left;
                sx_end = sx_start + frame.bbox.width;
            }
            else {
                sy_start = frame.bbox.top;
                sy_end = sy_start + frame.bbox.height;
                var y_start = yscale.invert(sy_start);
                var y_end = yscale.invert(sy_end);
                var x_start = (y_start - y_intercept) / gradient;
                var x_end = (y_end - y_intercept) / gradient;
                sx_start = xscale.compute(x_start);
                sx_end = xscale.compute(x_end);
            }
            var ctx = this.layer.ctx;
            ctx.save();
            ctx.beginPath();
            this.visuals.line.set_value(ctx);
            ctx.moveTo(sx_start, sy_start);
            ctx.lineTo(sx_end, sy_end);
            ctx.stroke();
            ctx.restore();
        };
        return SlopeView;
    }(annotation_1.AnnotationView));
    exports.SlopeView = SlopeView;
    SlopeView.__name__ = "SlopeView";
    var Slope = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Slope, _super);
        function Slope(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Slope;
    }(annotation_1.Annotation));
    exports.Slope = Slope;
    _a = Slope;
    Slope.__name__ = "Slope";
    (function () {
        _a.prototype.default_view = SlopeView;
        _a.mixins(mixins.Line);
        _a.define(function (_b) {
            var Number = _b.Number, Nullable = _b.Nullable;
            return ({
                gradient: [Nullable(Number), null],
                y_intercept: [Nullable(Number), null],
            });
        });
        _a.override({
            line_color: "black",
        });
    })();
},
/* models/annotations/span.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var enums_1 = require(135) /* ../../core/enums */;
    var SpanView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SpanView, _super);
        function SpanView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SpanView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.change, function () { return _this.plot_view.request_paint(_this); });
        };
        SpanView.prototype._render = function () {
            var _this = this;
            var location = this.model.location;
            if (location == null) {
                return;
            }
            var frame = this.plot_view.frame;
            var xscale = this.coordinates.x_scale;
            var yscale = this.coordinates.y_scale;
            var _calc_dim = function (scale, view) {
                if (_this.model.location_units == "data")
                    return scale.compute(location);
                else
                    return _this.model.for_hover ? location : view.compute(location);
            };
            var height, sleft, stop, width;
            if (this.model.dimension == "width") {
                stop = _calc_dim(yscale, frame.bbox.yview);
                sleft = frame.bbox.left;
                width = frame.bbox.width;
                height = this.model.line_width;
            }
            else {
                stop = frame.bbox.top;
                sleft = _calc_dim(xscale, frame.bbox.xview);
                width = this.model.line_width;
                height = frame.bbox.height;
            }
            var ctx = this.layer.ctx;
            ctx.save();
            ctx.beginPath();
            this.visuals.line.set_value(ctx);
            ctx.moveTo(sleft, stop);
            if (this.model.dimension == "width") {
                ctx.lineTo(sleft + width, stop);
            }
            else {
                ctx.lineTo(sleft, stop + height);
            }
            ctx.stroke();
            ctx.restore();
        };
        return SpanView;
    }(annotation_1.AnnotationView));
    exports.SpanView = SpanView;
    SpanView.__name__ = "SpanView";
    var Span = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Span, _super);
        function Span(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Span;
    }(annotation_1.Annotation));
    exports.Span = Span;
    _a = Span;
    Span.__name__ = "Span";
    (function () {
        _a.prototype.default_view = SpanView;
        _a.mixins(mixins.Line);
        _a.define(function (_b) {
            var Number = _b.Number, Nullable = _b.Nullable;
            return ({
                render_mode: [enums_1.RenderMode, "canvas"],
                location: [Nullable(Number), null],
                location_units: [enums_1.SpatialUnits, "data"],
                dimension: [enums_1.Dimension, "width"],
            });
        });
        _a.internal(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                for_hover: [Boolean, false],
            });
        });
        _a.override({
            line_color: "black",
        });
    })();
},
/* models/annotations/toolbar_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var toolbar_1 = require(336) /* ../tools/toolbar */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var dom_1 = require(158) /* ../../core/dom */;
    var side_panel_1 = require(238) /* ../../core/layout/side_panel */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    var ToolbarPanelView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolbarPanelView, _super);
        function ToolbarPanelView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._invalidate_toolbar = true;
            _this._previous_bbox = new bbox_1.BBox();
            return _this;
        }
        ToolbarPanelView.prototype.update_layout = function () {
            var _this = this;
            this.layout = new side_panel_1.SideLayout(this.panel, function () { return _this.get_size(); }, true);
        };
        ToolbarPanelView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.el = (0, dom_1.div)();
            this.plot_view.canvas_view.add_event(this.el);
        };
        ToolbarPanelView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var _b;
                var _this = this;
                return (0, tslib_1.__generator)(this, function (_c) {
                    switch (_c.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _c.sent();
                            _b = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(this.model.toolbar, { parent: this })];
                        case 2:
                            _b._toolbar_view = _c.sent();
                            this.plot_view.visibility_callbacks.push(function (visible) { return _this._toolbar_view.set_visibility(visible); });
                            return [2 /*return*/];
                    }
                });
            });
        };
        ToolbarPanelView.prototype.remove = function () {
            this._toolbar_view.remove();
            (0, dom_1.remove)(this.el);
            _super.prototype.remove.call(this);
        };
        ToolbarPanelView.prototype.render = function () {
            if (!this.model.visible)
                (0, dom_1.undisplay)(this.el);
            _super.prototype.render.call(this);
        };
        ToolbarPanelView.prototype._render = function () {
            // TODO: this should be handled by the layout
            var bbox = this.layout.bbox;
            if (!this._previous_bbox.equals(bbox)) {
                (0, dom_1.position)(this.el, bbox);
                this._previous_bbox = bbox;
                this._invalidate_toolbar = true;
            }
            if (this._invalidate_toolbar) {
                this.el.style.position = "absolute";
                this.el.style.overflow = "hidden";
                (0, dom_1.empty)(this.el);
                this.el.appendChild(this._toolbar_view.el);
                this._toolbar_view.layout.bbox = bbox;
                this._toolbar_view.render();
                this._invalidate_toolbar = false;
            }
            (0, dom_1.display)(this.el);
        };
        ToolbarPanelView.prototype._get_size = function () {
            var _b = this.model.toolbar, tools = _b.tools, logo = _b.logo;
            return {
                width: tools.length * 30 + (logo != null ? 25 : 0) + 15,
                height: 30,
            };
        };
        return ToolbarPanelView;
    }(annotation_1.AnnotationView));
    exports.ToolbarPanelView = ToolbarPanelView;
    ToolbarPanelView.__name__ = "ToolbarPanelView";
    var ToolbarPanel = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolbarPanel, _super);
        function ToolbarPanel(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ToolbarPanel;
    }(annotation_1.Annotation));
    exports.ToolbarPanel = ToolbarPanel;
    _a = ToolbarPanel;
    ToolbarPanel.__name__ = "ToolbarPanel";
    (function () {
        _a.prototype.default_view = ToolbarPanelView;
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                toolbar: [Ref(toolbar_1.Toolbar)],
            });
        });
    })();
},
/* models/tools/toolbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var types_1 = require(125) /* ../../core/util/types */;
    var array_1 = require(126) /* ../../core/util/array */;
    var object_1 = require(128) /* ../../core/util/object */;
    var tool_1 = require(337) /* ./tool */;
    var gesture_tool_1 = require(338) /* ./gestures/gesture_tool */;
    var inspect_tool_1 = require(347) /* ./inspectors/inspect_tool */;
    var toolbar_base_1 = require(348) /* ./toolbar_base */;
    exports.Drag = tool_1.Tool;
    exports.Inspection = tool_1.Tool;
    exports.Scroll = tool_1.Tool;
    exports.Tap = tool_1.Tool;
    function _get_active_attr(et) {
        switch (et) {
            case "tap": return "active_tap";
            case "pan": return "active_drag";
            case "pinch":
            case "scroll": return "active_scroll";
            case "multi": return "active_multi";
        }
        return null;
    }
    function _supports_auto(et) {
        return et == "tap" || et == "pan";
    }
    var Toolbar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Toolbar, _super);
        function Toolbar(attrs) {
            return _super.call(this, attrs) || this;
        }
        Toolbar.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var _b = this.properties, tools = _b.tools, active_drag = _b.active_drag, active_inspect = _b.active_inspect, active_scroll = _b.active_scroll, active_tap = _b.active_tap, active_multi = _b.active_multi;
            this.on_change([tools, active_drag, active_inspect, active_scroll, active_tap, active_multi], function () { return _this._init_tools(); });
        };
        Toolbar.prototype._init_tools = function () {
            var e_1, _b, e_2, _c, e_3, _d, e_4, _e, e_5, _f, e_6, _g;
            var _this = this;
            _super.prototype._init_tools.call(this);
            if (this.active_inspect == "auto") {
                // do nothing as all tools are active be default
            }
            else if (this.active_inspect instanceof inspect_tool_1.InspectTool) {
                var found = false;
                try {
                    for (var _h = (0, tslib_1.__values)(this.inspectors), _j = _h.next(); !_j.done; _j = _h.next()) {
                        var inspector = _j.value;
                        if (inspector != this.active_inspect)
                            inspector.active = false;
                        else
                            found = true;
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (_j && !_j.done && (_b = _h.return))
                            _b.call(_h);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
                if (!found) {
                    this.active_inspect = null;
                }
            }
            else if ((0, types_1.isArray)(this.active_inspect)) {
                var active_inspect = (0, array_1.intersection)(this.active_inspect, this.inspectors);
                if (active_inspect.length != this.active_inspect.length) {
                    this.active_inspect = active_inspect;
                }
                try {
                    for (var _k = (0, tslib_1.__values)(this.inspectors), _l = _k.next(); !_l.done; _l = _k.next()) {
                        var inspector = _l.value;
                        if (!(0, array_1.includes)(this.active_inspect, inspector))
                            inspector.active = false;
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (_l && !_l.done && (_c = _k.return))
                            _c.call(_k);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
            }
            else if (this.active_inspect == null) {
                try {
                    for (var _m = (0, tslib_1.__values)(this.inspectors), _o = _m.next(); !_o.done; _o = _m.next()) {
                        var inspector = _o.value;
                        inspector.active = false;
                    }
                }
                catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                }
                finally {
                    try {
                        if (_o && !_o.done && (_d = _m.return))
                            _d.call(_m);
                    }
                    finally {
                        if (e_3)
                            throw e_3.error;
                    }
                }
            }
            var _activate_gesture = function (tool) {
                if (tool.active) {
                    // tool was activated by a proxy, but we need to finish configuration manually
                    _this._active_change(tool);
                }
                else
                    tool.active = true;
            };
            try {
                // Connecting signals has to be done before changing the active state of the tools.
                for (var _p = (0, tslib_1.__values)((0, object_1.values)(this.gestures)), _q = _p.next(); !_q.done; _q = _p.next()) {
                    var gesture = _q.value;
                    gesture.tools = (0, array_1.sort_by)(gesture.tools, function (tool) { return tool.default_order; });
                    var _loop_1 = function (tool) {
                        this_1.connect(tool.properties.active.change, function () { return _this._active_change(tool); });
                    };
                    var this_1 = this;
                    try {
                        for (var _r = (e_5 = void 0, (0, tslib_1.__values)(gesture.tools)), _s = _r.next(); !_s.done; _s = _r.next()) {
                            var tool = _s.value;
                            _loop_1(tool);
                        }
                    }
                    catch (e_5_1) {
                        e_5 = { error: e_5_1 };
                    }
                    finally {
                        try {
                            if (_s && !_s.done && (_f = _r.return))
                                _f.call(_r);
                        }
                        finally {
                            if (e_5)
                                throw e_5.error;
                        }
                    }
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_q && !_q.done && (_e = _p.return))
                        _e.call(_p);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            try {
                for (var _t = (0, tslib_1.__values)((0, object_1.entries)(this.gestures)), _u = _t.next(); !_u.done; _u = _t.next()) {
                    var _v = (0, tslib_1.__read)(_u.value, 2), et = _v[0], gesture = _v[1];
                    var active_attr = _get_active_attr(et);
                    if (active_attr) {
                        var active_tool = this[active_attr];
                        if (active_tool == "auto") {
                            if (gesture.tools.length != 0 && _supports_auto(et)) {
                                _activate_gesture(gesture.tools[0]);
                            }
                        }
                        else if (active_tool != null) {
                            if ((0, array_1.includes)(this.tools, active_tool)) {
                                _activate_gesture(active_tool);
                            }
                            else {
                                this[active_attr] = null;
                            }
                        }
                    }
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_u && !_u.done && (_g = _t.return))
                        _g.call(_t);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
        };
        return Toolbar;
    }(toolbar_base_1.ToolbarBase));
    exports.Toolbar = Toolbar;
    _a = Toolbar;
    Toolbar.__name__ = "Toolbar";
    (function () {
        _a.prototype.default_view = toolbar_base_1.ToolbarBaseView;
        _a.define(function (_b) {
            var Or = _b.Or, Ref = _b.Ref, Auto = _b.Auto, Null = _b.Null;
            return ({
                active_drag: [Or(Ref(exports.Drag), Auto, Null), "auto"],
                active_inspect: [Or(Ref(exports.Inspection), Auto, Null), "auto"],
                active_scroll: [Or(Ref(exports.Scroll), Auto, Null), "auto"],
                active_tap: [Or(Ref(exports.Tap), Auto, Null), "auto"],
                active_multi: [Or(Ref(gesture_tool_1.GestureTool), Auto, Null), "auto"],
            });
        });
    })();
},
/* models/tools/tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var view_1 = require(157) /* ../../core/view */;
    var array_1 = require(126) /* ../../core/util/array */;
    var model_1 = require(168) /* ../../model */;
    var ToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolView, _super);
        function ToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(ToolView.prototype, "plot_view", {
            get: function () {
                return this.parent;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ToolView.prototype, "plot_model", {
            get: function () {
                return this.parent.model;
            },
            enumerable: false,
            configurable: true
        });
        ToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.active.change, function () {
                if (_this.model.active)
                    _this.activate();
                else
                    _this.deactivate();
            });
        };
        // activate is triggered by toolbar ui actions
        ToolView.prototype.activate = function () { };
        // deactivate is triggered by toolbar ui actions
        ToolView.prototype.deactivate = function () { };
        return ToolView;
    }(view_1.View));
    exports.ToolView = ToolView;
    ToolView.__name__ = "ToolView";
    var Tool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Tool, _super);
        function Tool(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(Tool.prototype, "synthetic_renderers", {
            get: function () {
                return [];
            },
            enumerable: false,
            configurable: true
        });
        // utility function to get limits along both dimensions, given
        // optional dimensional constraints
        Tool.prototype._get_dim_limits = function (_b, _c, frame, dims) {
            var _d = (0, tslib_1.__read)(_b, 2), sx0 = _d[0], sy0 = _d[1];
            var _e = (0, tslib_1.__read)(_c, 2), sx1 = _e[0], sy1 = _e[1];
            var hr = frame.bbox.h_range;
            var sxlim;
            if (dims == "width" || dims == "both") {
                sxlim = [(0, array_1.min)([sx0, sx1]), (0, array_1.max)([sx0, sx1])];
                sxlim = [(0, array_1.max)([sxlim[0], hr.start]), (0, array_1.min)([sxlim[1], hr.end])];
            }
            else
                sxlim = [hr.start, hr.end];
            var vr = frame.bbox.v_range;
            var sylim;
            if (dims == "height" || dims == "both") {
                sylim = [(0, array_1.min)([sy0, sy1]), (0, array_1.max)([sy0, sy1])];
                sylim = [(0, array_1.max)([sylim[0], vr.start]), (0, array_1.min)([sylim[1], vr.end])];
            }
            else
                sylim = [vr.start, vr.end];
            return [sxlim, sylim];
        };
        Tool.register_alias = function (name, fn) {
            this.prototype._known_aliases.set(name, fn);
        };
        Tool.from_string = function (name) {
            var fn = this.prototype._known_aliases.get(name);
            if (fn != null)
                return fn();
            else {
                var names = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.prototype._known_aliases.keys()), false);
                throw new Error("unexpected tool name '" + name + "', possible tools are " + names.join(", "));
            }
        };
        return Tool;
    }(model_1.Model));
    exports.Tool = Tool;
    _a = Tool;
    Tool.__name__ = "Tool";
    (function () {
        _a.prototype._known_aliases = new Map();
        _a.define(function (_b) {
            var String = _b.String, Nullable = _b.Nullable;
            return ({
                description: [Nullable(String), null],
            });
        });
        _a.internal(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                active: [Boolean, false],
            });
        });
    })();
},
/* models/tools/gestures/gesture_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var button_tool_1 = require(339) /* ../button_tool */;
    var on_off_button_1 = require(346) /* ../on_off_button */;
    var GestureToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GestureToolView, _super);
        function GestureToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return GestureToolView;
    }(button_tool_1.ButtonToolView));
    exports.GestureToolView = GestureToolView;
    GestureToolView.__name__ = "GestureToolView";
    var GestureTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GestureTool, _super);
        function GestureTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.button_view = on_off_button_1.OnOffButtonView;
            return _this;
        }
        return GestureTool;
    }(button_tool_1.ButtonTool));
    exports.GestureTool = GestureTool;
    GestureTool.__name__ = "GestureTool";
},
/* models/tools/button_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var hammerjs_1 = (0, tslib_1.__importDefault)(require(340) /* hammerjs */);
    var dom_view_1 = require(341) /* ../../core/dom_view */;
    var tool_1 = require(337) /* ./tool */;
    var dom_1 = require(158) /* ../../core/dom */;
    var string_1 = require(149) /* ../../core/util/string */;
    var types_1 = require(125) /* ../../core/util/types */;
    var array_1 = require(126) /* ../../core/util/array */;
    var toolbar_css_1 = (0, tslib_1.__importStar)(require(342) /* ../../styles/toolbar.css */), toolbars = toolbar_css_1;
    var icons_css_1 = (0, tslib_1.__importDefault)(require(343) /* ../../styles/icons.css */);
    var menus_css_1 = (0, tslib_1.__importDefault)(require(344) /* ../../styles/menus.css */);
    var menus_1 = require(345) /* ../../core/util/menus */;
    var ButtonToolButtonView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ButtonToolButtonView, _super);
        function ButtonToolButtonView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ButtonToolButtonView.prototype.initialize = function () {
            var _this = this;
            _super.prototype.initialize.call(this);
            var items = this.model.menu;
            if (items != null) {
                var location = this.parent.model.toolbar_location;
                var reverse = location == "left" || location == "above";
                var orientation = this.parent.model.horizontal ? "vertical" : "horizontal";
                this._menu = new menus_1.ContextMenu(!reverse ? items : (0, array_1.reversed)(items), {
                    orientation: orientation,
                    prevent_hide: function (event) { return event.target == _this.el; },
                });
            }
            this._hammer = new hammerjs_1.default(this.el, {
                touchAction: "auto",
                inputClass: hammerjs_1.default.TouchMouseInput, // https://github.com/bokeh/bokeh/issues/9187
            });
            this.connect(this.model.change, function () { return _this.render(); });
            this._hammer.on("tap", function (e) {
                var _b;
                if ((_b = _this._menu) === null || _b === void 0 ? void 0 : _b.is_open) {
                    _this._menu.hide();
                    return;
                }
                if (e.target == _this.el) {
                    _this._clicked();
                }
            });
            this._hammer.on("press", function () { return _this._pressed(); });
            this.el.addEventListener("keydown", function (event) {
                if (event.keyCode == dom_1.Keys.Enter) {
                    _this._clicked();
                }
            });
        };
        ButtonToolButtonView.prototype.remove = function () {
            var _b;
            this._hammer.destroy();
            (_b = this._menu) === null || _b === void 0 ? void 0 : _b.remove();
            _super.prototype.remove.call(this);
        };
        ButtonToolButtonView.prototype.styles = function () {
            return (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(_super.prototype.styles.call(this)), false), [toolbar_css_1.default, icons_css_1.default, menus_css_1.default], false);
        };
        ButtonToolButtonView.prototype.css_classes = function () {
            return _super.prototype.css_classes.call(this).concat(toolbars.toolbar_button);
        };
        ButtonToolButtonView.prototype.render = function () {
            (0, dom_1.empty)(this.el);
            var icon = this.model.computed_icon;
            if ((0, types_1.isString)(icon)) {
                if ((0, string_1.startsWith)(icon, "data:image"))
                    this.el.style.backgroundImage = "url(\"" + icon + "\")";
                else
                    this.el.classList.add(icon);
            }
            this.el.title = this.model.tooltip;
            this.el.tabIndex = 0;
            if (this._menu != null) {
                this.root.el.appendChild(this._menu.el);
            }
        };
        ButtonToolButtonView.prototype._pressed = function () {
            var _this = this;
            var _b;
            var at = (function () {
                switch (_this.parent.model.toolbar_location) {
                    case "right": return { left_of: _this.el };
                    case "left": return { right_of: _this.el };
                    case "above": return { below: _this.el };
                    case "below": return { above: _this.el };
                }
            })();
            (_b = this._menu) === null || _b === void 0 ? void 0 : _b.toggle(at);
        };
        return ButtonToolButtonView;
    }(dom_view_1.DOMView));
    exports.ButtonToolButtonView = ButtonToolButtonView;
    ButtonToolButtonView.__name__ = "ButtonToolButtonView";
    var ButtonToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ButtonToolView, _super);
        function ButtonToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ButtonToolView;
    }(tool_1.ToolView));
    exports.ButtonToolView = ButtonToolView;
    ButtonToolView.__name__ = "ButtonToolView";
    var ButtonTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ButtonTool, _super);
        function ButtonTool(attrs) {
            return _super.call(this, attrs) || this;
        }
        // utility function to return a tool name, modified
        // by the active dimensions. Used by tools that have dimensions
        ButtonTool.prototype._get_dim_tooltip = function (dims) {
            var _b = this, description = _b.description, tool_name = _b.tool_name;
            if (description != null)
                return description;
            else if (dims == "both")
                return tool_name;
            else
                return tool_name + " (" + (dims == "width" ? "x" : "y") + "-axis)";
        };
        Object.defineProperty(ButtonTool.prototype, "tooltip", {
            get: function () {
                var _b;
                return (_b = this.description) !== null && _b !== void 0 ? _b : this.tool_name;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ButtonTool.prototype, "computed_icon", {
            get: function () {
                return this.icon;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ButtonTool.prototype, "menu", {
            get: function () {
                return null;
            },
            enumerable: false,
            configurable: true
        });
        return ButtonTool;
    }(tool_1.Tool));
    exports.ButtonTool = ButtonTool;
    _a = ButtonTool;
    ButtonTool.__name__ = "ButtonTool";
    (function () {
        _a.internal(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                disabled: [Boolean, false],
            });
        });
    })();
},
/* hammerjs/hammer.js */ function _(require, module, exports, __esModule, __esExport) {
    /*! Hammer.JS - v2.0.7 - 2016-04-22
     * http://hammerjs.github.io/
     *
     * Copyright (c) 2016 Jorik Tangelder;
     * Licensed under the MIT license */
    (function (window, document, exportName, undefined) {
        'use strict';
        var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
        var TEST_ELEMENT = document.createElement('div');
        var TYPE_FUNCTION = 'function';
        var round = Math.round;
        var abs = Math.abs;
        var now = Date.now;
        /**
         * set a timeout with a given scope
         * @param {Function} fn
         * @param {Number} timeout
         * @param {Object} context
         * @returns {number}
         */
        function setTimeoutContext(fn, timeout, context) {
            return setTimeout(bindFn(fn, context), timeout);
        }
        /**
         * if the argument is an array, we want to execute the fn on each entry
         * if it aint an array we don't want to do a thing.
         * this is used by all the methods that accept a single and array argument.
         * @param {*|Array} arg
         * @param {String} fn
         * @param {Object} [context]
         * @returns {Boolean}
         */
        function invokeArrayArg(arg, fn, context) {
            if (Array.isArray(arg)) {
                each(arg, context[fn], context);
                return true;
            }
            return false;
        }
        /**
         * walk objects and arrays
         * @param {Object} obj
         * @param {Function} iterator
         * @param {Object} context
         */
        function each(obj, iterator, context) {
            var i;
            if (!obj) {
                return;
            }
            if (obj.forEach) {
                obj.forEach(iterator, context);
            }
            else if (obj.length !== undefined) {
                i = 0;
                while (i < obj.length) {
                    iterator.call(context, obj[i], i, obj);
                    i++;
                }
            }
            else {
                for (i in obj) {
                    obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
                }
            }
        }
        /**
         * wrap a method with a deprecation warning and stack trace
         * @param {Function} method
         * @param {String} name
         * @param {String} message
         * @returns {Function} A new function wrapping the supplied method.
         */
        function deprecate(method, name, message) {
            var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
            return function () {
                var e = new Error('get-stack-trace');
                var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
                    .replace(/^\s+at\s+/gm, '')
                    .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
                var log = window.console && (window.console.warn || window.console.log);
                if (log) {
                    log.call(window.console, deprecationMessage, stack);
                }
                return method.apply(this, arguments);
            };
        }
        /**
         * extend object.
         * means that properties in dest will be overwritten by the ones in src.
         * @param {Object} target
         * @param {...Object} objects_to_assign
         * @returns {Object} target
         */
        var assign;
        if (typeof Object.assign !== 'function') {
            assign = function assign(target) {
                if (target === undefined || target === null) {
                    throw new TypeError('Cannot convert undefined or null to object');
                }
                var output = Object(target);
                for (var index = 1; index < arguments.length; index++) {
                    var source = arguments[index];
                    if (source !== undefined && source !== null) {
                        for (var nextKey in source) {
                            if (source.hasOwnProperty(nextKey)) {
                                output[nextKey] = source[nextKey];
                            }
                        }
                    }
                }
                return output;
            };
        }
        else {
            assign = Object.assign;
        }
        /**
         * extend object.
         * means that properties in dest will be overwritten by the ones in src.
         * @param {Object} dest
         * @param {Object} src
         * @param {Boolean} [merge=false]
         * @returns {Object} dest
         */
        var extend = deprecate(function extend(dest, src, merge) {
            var keys = Object.keys(src);
            var i = 0;
            while (i < keys.length) {
                if (!merge || (merge && dest[keys[i]] === undefined)) {
                    dest[keys[i]] = src[keys[i]];
                }
                i++;
            }
            return dest;
        }, 'extend', 'Use `assign`.');
        /**
         * merge the values from src in the dest.
         * means that properties that exist in dest will not be overwritten by src
         * @param {Object} dest
         * @param {Object} src
         * @returns {Object} dest
         */
        var merge = deprecate(function merge(dest, src) {
            return extend(dest, src, true);
        }, 'merge', 'Use `assign`.');
        /**
         * simple class inheritance
         * @param {Function} child
         * @param {Function} base
         * @param {Object} [properties]
         */
        function inherit(child, base, properties) {
            var baseP = base.prototype, childP;
            childP = child.prototype = Object.create(baseP);
            childP.constructor = child;
            childP._super = baseP;
            if (properties) {
                assign(childP, properties);
            }
        }
        /**
         * simple function bind
         * @param {Function} fn
         * @param {Object} context
         * @returns {Function}
         */
        function bindFn(fn, context) {
            return function boundFn() {
                return fn.apply(context, arguments);
            };
        }
        /**
         * let a boolean value also be a function that must return a boolean
         * this first item in args will be used as the context
         * @param {Boolean|Function} val
         * @param {Array} [args]
         * @returns {Boolean}
         */
        function boolOrFn(val, args) {
            if (typeof val == TYPE_FUNCTION) {
                return val.apply(args ? args[0] || undefined : undefined, args);
            }
            return val;
        }
        /**
         * use the val2 when val1 is undefined
         * @param {*} val1
         * @param {*} val2
         * @returns {*}
         */
        function ifUndefined(val1, val2) {
            return (val1 === undefined) ? val2 : val1;
        }
        /**
         * addEventListener with multiple events at once
         * @param {EventTarget} target
         * @param {String} types
         * @param {Function} handler
         */
        function addEventListeners(target, types, handler) {
            each(splitStr(types), function (type) {
                target.addEventListener(type, handler, false);
            });
        }
        /**
         * removeEventListener with multiple events at once
         * @param {EventTarget} target
         * @param {String} types
         * @param {Function} handler
         */
        function removeEventListeners(target, types, handler) {
            each(splitStr(types), function (type) {
                target.removeEventListener(type, handler, false);
            });
        }
        /**
         * find if a node is in the given parent
         * @method hasParent
         * @param {HTMLElement} node
         * @param {HTMLElement} parent
         * @return {Boolean} found
         */
        function hasParent(node, parent) {
            while (node) {
                if (node == parent) {
                    return true;
                }
                node = node.parentNode;
            }
            return false;
        }
        /**
         * small indexOf wrapper
         * @param {String} str
         * @param {String} find
         * @returns {Boolean} found
         */
        function inStr(str, find) {
            return str.indexOf(find) > -1;
        }
        /**
         * split string on whitespace
         * @param {String} str
         * @returns {Array} words
         */
        function splitStr(str) {
            return str.trim().split(/\s+/g);
        }
        /**
         * find if a array contains the object using indexOf or a simple polyFill
         * @param {Array} src
         * @param {String} find
         * @param {String} [findByKey]
         * @return {Boolean|Number} false when not found, or the index
         */
        function inArray(src, find, findByKey) {
            if (src.indexOf && !findByKey) {
                return src.indexOf(find);
            }
            else {
                var i = 0;
                while (i < src.length) {
                    if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
                        return i;
                    }
                    i++;
                }
                return -1;
            }
        }
        /**
         * convert array-like objects to real arrays
         * @param {Object} obj
         * @returns {Array}
         */
        function toArray(obj) {
            return Array.prototype.slice.call(obj, 0);
        }
        /**
         * unique array with objects based on a key (like 'id') or just by the array's value
         * @param {Array} src [{id:1},{id:2},{id:1}]
         * @param {String} [key]
         * @param {Boolean} [sort=False]
         * @returns {Array} [{id:1},{id:2}]
         */
        function uniqueArray(src, key, sort) {
            var results = [];
            var values = [];
            var i = 0;
            while (i < src.length) {
                var val = key ? src[i][key] : src[i];
                if (inArray(values, val) < 0) {
                    results.push(src[i]);
                }
                values[i] = val;
                i++;
            }
            if (sort) {
                if (!key) {
                    results = results.sort();
                }
                else {
                    results = results.sort(function sortUniqueArray(a, b) {
                        return a[key] > b[key];
                    });
                }
            }
            return results;
        }
        /**
         * get the prefixed property
         * @param {Object} obj
         * @param {String} property
         * @returns {String|Undefined} prefixed
         */
        function prefixed(obj, property) {
            var prefix, prop;
            var camelProp = property[0].toUpperCase() + property.slice(1);
            var i = 0;
            while (i < VENDOR_PREFIXES.length) {
                prefix = VENDOR_PREFIXES[i];
                prop = (prefix) ? prefix + camelProp : property;
                if (prop in obj) {
                    return prop;
                }
                i++;
            }
            return undefined;
        }
        /**
         * get a unique id
         * @returns {number} uniqueId
         */
        var _uniqueId = 1;
        function uniqueId() {
            return _uniqueId++;
        }
        /**
         * get the window object of an element
         * @param {HTMLElement} element
         * @returns {DocumentView|Window}
         */
        function getWindowForElement(element) {
            var doc = element.ownerDocument || element;
            return (doc.defaultView || doc.parentWindow || window);
        }
        var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
        var SUPPORT_TOUCH = ('ontouchstart' in window);
        var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
        var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
        var INPUT_TYPE_TOUCH = 'touch';
        var INPUT_TYPE_PEN = 'pen';
        var INPUT_TYPE_MOUSE = 'mouse';
        var INPUT_TYPE_KINECT = 'kinect';
        var COMPUTE_INTERVAL = 25;
        var INPUT_START = 1;
        var INPUT_MOVE = 2;
        var INPUT_END = 4;
        var INPUT_CANCEL = 8;
        var DIRECTION_NONE = 1;
        var DIRECTION_LEFT = 2;
        var DIRECTION_RIGHT = 4;
        var DIRECTION_UP = 8;
        var DIRECTION_DOWN = 16;
        var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
        var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
        var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
        var PROPS_XY = ['x', 'y'];
        var PROPS_CLIENT_XY = ['clientX', 'clientY'];
        /**
         * create new input type manager
         * @param {Manager} manager
         * @param {Function} callback
         * @returns {Input}
         * @constructor
         */
        function Input(manager, callback) {
            var self = this;
            this.manager = manager;
            this.callback = callback;
            this.element = manager.element;
            this.target = manager.options.inputTarget;
            // smaller wrapper around the handler, for the scope and the enabled state of the manager,
            // so when disabled the input events are completely bypassed.
            this.domHandler = function (ev) {
                if (boolOrFn(manager.options.enable, [manager])) {
                    self.handler(ev);
                }
            };
            this.init();
        }
        Input.prototype = {
            /**
             * should handle the inputEvent data and trigger the callback
             * @virtual
             */
            handler: function () { },
            /**
             * bind the events
             */
            init: function () {
                this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
                this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
                this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
            },
            /**
             * unbind the events
             */
            destroy: function () {
                this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
                this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
                this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
            }
        };
        /**
         * create new input type manager
         * called by the Manager constructor
         * @param {Hammer} manager
         * @returns {Input}
         */
        function createInputInstance(manager) {
            var Type;
            var inputClass = manager.options.inputClass;
            if (inputClass) {
                Type = inputClass;
            }
            else if (SUPPORT_POINTER_EVENTS) {
                Type = PointerEventInput;
            }
            else if (SUPPORT_ONLY_TOUCH) {
                Type = TouchInput;
            }
            else if (!SUPPORT_TOUCH) {
                Type = MouseInput;
            }
            else {
                Type = TouchMouseInput;
            }
            return new (Type)(manager, inputHandler);
        }
        /**
         * handle input events
         * @param {Manager} manager
         * @param {String} eventType
         * @param {Object} input
         */
        function inputHandler(manager, eventType, input) {
            var pointersLen = input.pointers.length;
            var changedPointersLen = input.changedPointers.length;
            var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
            var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));
            input.isFirst = !!isFirst;
            input.isFinal = !!isFinal;
            if (isFirst) {
                manager.session = {};
            }
            // source event is the normalized value of the domEvents
            // like 'touchstart, mouseup, pointerdown'
            input.eventType = eventType;
            // compute scale, rotation etc
            computeInputData(manager, input);
            // emit secret event
            manager.emit('hammer.input', input);
            manager.recognize(input);
            manager.session.prevInput = input;
        }
        /**
         * extend the data with some usable properties like scale, rotate, velocity etc
         * @param {Object} manager
         * @param {Object} input
         */
        function computeInputData(manager, input) {
            var session = manager.session;
            var pointers = input.pointers;
            var pointersLength = pointers.length;
            // store the first input to calculate the distance and direction
            if (!session.firstInput) {
                session.firstInput = simpleCloneInputData(input);
            }
            // to compute scale and rotation we need to store the multiple touches
            if (pointersLength > 1 && !session.firstMultiple) {
                session.firstMultiple = simpleCloneInputData(input);
            }
            else if (pointersLength === 1) {
                session.firstMultiple = false;
            }
            var firstInput = session.firstInput;
            var firstMultiple = session.firstMultiple;
            var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
            var center = input.center = getCenter(pointers);
            input.timeStamp = now();
            input.deltaTime = input.timeStamp - firstInput.timeStamp;
            input.angle = getAngle(offsetCenter, center);
            input.distance = getDistance(offsetCenter, center);
            computeDeltaXY(session, input);
            input.offsetDirection = getDirection(input.deltaX, input.deltaY);
            var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
            input.overallVelocityX = overallVelocity.x;
            input.overallVelocityY = overallVelocity.y;
            input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;
            input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
            input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
            input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
                session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);
            computeIntervalInputData(session, input);
            // find the correct target
            var target = manager.element;
            if (hasParent(input.srcEvent.target, target)) {
                target = input.srcEvent.target;
            }
            input.target = target;
        }
        function computeDeltaXY(session, input) {
            var center = input.center;
            var offset = session.offsetDelta || {};
            var prevDelta = session.prevDelta || {};
            var prevInput = session.prevInput || {};
            if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
                prevDelta = session.prevDelta = {
                    x: prevInput.deltaX || 0,
                    y: prevInput.deltaY || 0
                };
                offset = session.offsetDelta = {
                    x: center.x,
                    y: center.y
                };
            }
            input.deltaX = prevDelta.x + (center.x - offset.x);
            input.deltaY = prevDelta.y + (center.y - offset.y);
        }
        /**
         * velocity is calculated every x ms
         * @param {Object} session
         * @param {Object} input
         */
        function computeIntervalInputData(session, input) {
            var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction;
            if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
                var deltaX = input.deltaX - last.deltaX;
                var deltaY = input.deltaY - last.deltaY;
                var v = getVelocity(deltaTime, deltaX, deltaY);
                velocityX = v.x;
                velocityY = v.y;
                velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
                direction = getDirection(deltaX, deltaY);
                session.lastInterval = input;
            }
            else {
                // use latest velocity info if it doesn't overtake a minimum period
                velocity = last.velocity;
                velocityX = last.velocityX;
                velocityY = last.velocityY;
                direction = last.direction;
            }
            input.velocity = velocity;
            input.velocityX = velocityX;
            input.velocityY = velocityY;
            input.direction = direction;
        }
        /**
         * create a simple clone from the input used for storage of firstInput and firstMultiple
         * @param {Object} input
         * @returns {Object} clonedInputData
         */
        function simpleCloneInputData(input) {
            // make a simple copy of the pointers because we will get a reference if we don't
            // we only need clientXY for the calculations
            var pointers = [];
            var i = 0;
            while (i < input.pointers.length) {
                pointers[i] = {
                    clientX: round(input.pointers[i].clientX),
                    clientY: round(input.pointers[i].clientY)
                };
                i++;
            }
            return {
                timeStamp: now(),
                pointers: pointers,
                center: getCenter(pointers),
                deltaX: input.deltaX,
                deltaY: input.deltaY
            };
        }
        /**
         * get the center of all the pointers
         * @param {Array} pointers
         * @return {Object} center contains `x` and `y` properties
         */
        function getCenter(pointers) {
            var pointersLength = pointers.length;
            // no need to loop when only one touch
            if (pointersLength === 1) {
                return {
                    x: round(pointers[0].clientX),
                    y: round(pointers[0].clientY)
                };
            }
            var x = 0, y = 0, i = 0;
            while (i < pointersLength) {
                x += pointers[i].clientX;
                y += pointers[i].clientY;
                i++;
            }
            return {
                x: round(x / pointersLength),
                y: round(y / pointersLength)
            };
        }
        /**
         * calculate the velocity between two points. unit is in px per ms.
         * @param {Number} deltaTime
         * @param {Number} x
         * @param {Number} y
         * @return {Object} velocity `x` and `y`
         */
        function getVelocity(deltaTime, x, y) {
            return {
                x: x / deltaTime || 0,
                y: y / deltaTime || 0
            };
        }
        /**
         * get the direction between two points
         * @param {Number} x
         * @param {Number} y
         * @return {Number} direction
         */
        function getDirection(x, y) {
            if (x === y) {
                return DIRECTION_NONE;
            }
            if (abs(x) >= abs(y)) {
                return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
            }
            return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
        }
        /**
         * calculate the absolute distance between two points
         * @param {Object} p1 {x, y}
         * @param {Object} p2 {x, y}
         * @param {Array} [props] containing x and y keys
         * @return {Number} distance
         */
        function getDistance(p1, p2, props) {
            if (!props) {
                props = PROPS_XY;
            }
            var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]];
            return Math.sqrt((x * x) + (y * y));
        }
        /**
         * calculate the angle between two coordinates
         * @param {Object} p1
         * @param {Object} p2
         * @param {Array} [props] containing x and y keys
         * @return {Number} angle
         */
        function getAngle(p1, p2, props) {
            if (!props) {
                props = PROPS_XY;
            }
            var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]];
            return Math.atan2(y, x) * 180 / Math.PI;
        }
        /**
         * calculate the rotation degrees between two pointersets
         * @param {Array} start array of pointers
         * @param {Array} end array of pointers
         * @return {Number} rotation
         */
        function getRotation(start, end) {
            return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
        }
        /**
         * calculate the scale factor between two pointersets
         * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
         * @param {Array} start array of pointers
         * @param {Array} end array of pointers
         * @return {Number} scale
         */
        function getScale(start, end) {
            return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
        }
        var MOUSE_INPUT_MAP = {
            mousedown: INPUT_START,
            mousemove: INPUT_MOVE,
            mouseup: INPUT_END
        };
        var MOUSE_ELEMENT_EVENTS = 'mousedown';
        var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
        /**
         * Mouse events input
         * @constructor
         * @extends Input
         */
        function MouseInput() {
            this.evEl = MOUSE_ELEMENT_EVENTS;
            this.evWin = MOUSE_WINDOW_EVENTS;
            this.pressed = false; // mousedown state
            Input.apply(this, arguments);
        }
        inherit(MouseInput, Input, {
            /**
             * handle mouse events
             * @param {Object} ev
             */
            handler: function MEhandler(ev) {
                var eventType = MOUSE_INPUT_MAP[ev.type];
                // on start we want to have the left mouse button down
                if (eventType & INPUT_START && ev.button === 0) {
                    this.pressed = true;
                }
                if (eventType & INPUT_MOVE && ev.which !== 1) {
                    eventType = INPUT_END;
                }
                // mouse must be down
                if (!this.pressed) {
                    return;
                }
                if (eventType & INPUT_END) {
                    this.pressed = false;
                }
                this.callback(this.manager, eventType, {
                    pointers: [ev],
                    changedPointers: [ev],
                    pointerType: INPUT_TYPE_MOUSE,
                    srcEvent: ev
                });
            }
        });
        var POINTER_INPUT_MAP = {
            pointerdown: INPUT_START,
            pointermove: INPUT_MOVE,
            pointerup: INPUT_END,
            pointercancel: INPUT_CANCEL,
            pointerout: INPUT_CANCEL
        };
        // in IE10 the pointer types is defined as an enum
        var IE10_POINTER_TYPE_ENUM = {
            2: INPUT_TYPE_TOUCH,
            3: INPUT_TYPE_PEN,
            4: INPUT_TYPE_MOUSE,
            5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
        };
        var POINTER_ELEMENT_EVENTS = 'pointerdown';
        var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
        // IE10 has prefixed support, and case-sensitive
        if (window.MSPointerEvent && !window.PointerEvent) {
            POINTER_ELEMENT_EVENTS = 'MSPointerDown';
            POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
        }
        /**
         * Pointer events input
         * @constructor
         * @extends Input
         */
        function PointerEventInput() {
            this.evEl = POINTER_ELEMENT_EVENTS;
            this.evWin = POINTER_WINDOW_EVENTS;
            Input.apply(this, arguments);
            this.store = (this.manager.session.pointerEvents = []);
        }
        inherit(PointerEventInput, Input, {
            /**
             * handle mouse events
             * @param {Object} ev
             */
            handler: function PEhandler(ev) {
                var store = this.store;
                var removePointer = false;
                var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
                var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
                var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
                var isTouch = (pointerType == INPUT_TYPE_TOUCH);
                // get index of the event in the store
                var storeIndex = inArray(store, ev.pointerId, 'pointerId');
                // start and mouse must be down
                if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
                    if (storeIndex < 0) {
                        store.push(ev);
                        storeIndex = store.length - 1;
                    }
                }
                else if (eventType & (INPUT_END | INPUT_CANCEL)) {
                    removePointer = true;
                }
                // it not found, so the pointer hasn't been down (so it's probably a hover)
                if (storeIndex < 0) {
                    return;
                }
                // update the event in the store
                store[storeIndex] = ev;
                this.callback(this.manager, eventType, {
                    pointers: store,
                    changedPointers: [ev],
                    pointerType: pointerType,
                    srcEvent: ev
                });
                if (removePointer) {
                    // remove from the store
                    store.splice(storeIndex, 1);
                }
            }
        });
        var SINGLE_TOUCH_INPUT_MAP = {
            touchstart: INPUT_START,
            touchmove: INPUT_MOVE,
            touchend: INPUT_END,
            touchcancel: INPUT_CANCEL
        };
        var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
        var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
        /**
         * Touch events input
         * @constructor
         * @extends Input
         */
        function SingleTouchInput() {
            this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
            this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
            this.started = false;
            Input.apply(this, arguments);
        }
        inherit(SingleTouchInput, Input, {
            handler: function TEhandler(ev) {
                var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
                // should we handle the touch events?
                if (type === INPUT_START) {
                    this.started = true;
                }
                if (!this.started) {
                    return;
                }
                var touches = normalizeSingleTouches.call(this, ev, type);
                // when done, reset the started state
                if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
                    this.started = false;
                }
                this.callback(this.manager, type, {
                    pointers: touches[0],
                    changedPointers: touches[1],
                    pointerType: INPUT_TYPE_TOUCH,
                    srcEvent: ev
                });
            }
        });
        /**
         * @this {TouchInput}
         * @param {Object} ev
         * @param {Number} type flag
         * @returns {undefined|Array} [all, changed]
         */
        function normalizeSingleTouches(ev, type) {
            var all = toArray(ev.touches);
            var changed = toArray(ev.changedTouches);
            if (type & (INPUT_END | INPUT_CANCEL)) {
                all = uniqueArray(all.concat(changed), 'identifier', true);
            }
            return [all, changed];
        }
        var TOUCH_INPUT_MAP = {
            touchstart: INPUT_START,
            touchmove: INPUT_MOVE,
            touchend: INPUT_END,
            touchcancel: INPUT_CANCEL
        };
        var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
        /**
         * Multi-user touch events input
         * @constructor
         * @extends Input
         */
        function TouchInput() {
            this.evTarget = TOUCH_TARGET_EVENTS;
            this.targetIds = {};
            Input.apply(this, arguments);
        }
        inherit(TouchInput, Input, {
            handler: function MTEhandler(ev) {
                var type = TOUCH_INPUT_MAP[ev.type];
                var touches = getTouches.call(this, ev, type);
                if (!touches) {
                    return;
                }
                this.callback(this.manager, type, {
                    pointers: touches[0],
                    changedPointers: touches[1],
                    pointerType: INPUT_TYPE_TOUCH,
                    srcEvent: ev
                });
            }
        });
        /**
         * @this {TouchInput}
         * @param {Object} ev
         * @param {Number} type flag
         * @returns {undefined|Array} [all, changed]
         */
        function getTouches(ev, type) {
            var allTouches = toArray(ev.touches);
            var targetIds = this.targetIds;
            // when there is only one touch, the process can be simplified
            if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
                targetIds[allTouches[0].identifier] = true;
                return [allTouches, allTouches];
            }
            var i, targetTouches, changedTouches = toArray(ev.changedTouches), changedTargetTouches = [], target = this.target;
            // get target touches from touches
            targetTouches = allTouches.filter(function (touch) {
                return hasParent(touch.target, target);
            });
            // collect touches
            if (type === INPUT_START) {
                i = 0;
                while (i < targetTouches.length) {
                    targetIds[targetTouches[i].identifier] = true;
                    i++;
                }
            }
            // filter changed touches to only contain touches that exist in the collected target ids
            i = 0;
            while (i < changedTouches.length) {
                if (targetIds[changedTouches[i].identifier]) {
                    changedTargetTouches.push(changedTouches[i]);
                }
                // cleanup removed touches
                if (type & (INPUT_END | INPUT_CANCEL)) {
                    delete targetIds[changedTouches[i].identifier];
                }
                i++;
            }
            if (!changedTargetTouches.length) {
                return;
            }
            return [
                // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
                uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
                changedTargetTouches
            ];
        }
        /**
         * Combined touch and mouse input
         *
         * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
         * This because touch devices also emit mouse events while doing a touch.
         *
         * @constructor
         * @extends Input
         */
        var DEDUP_TIMEOUT = 2500;
        var DEDUP_DISTANCE = 25;
        function TouchMouseInput() {
            Input.apply(this, arguments);
            var handler = bindFn(this.handler, this);
            this.touch = new TouchInput(this.manager, handler);
            this.mouse = new MouseInput(this.manager, handler);
            this.primaryTouch = null;
            this.lastTouches = [];
        }
        inherit(TouchMouseInput, Input, {
            /**
             * handle mouse and touch events
             * @param {Hammer} manager
             * @param {String} inputEvent
             * @param {Object} inputData
             */
            handler: function TMEhandler(manager, inputEvent, inputData) {
                var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
                if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
                    return;
                }
                // when we're in a touch event, record touches to  de-dupe synthetic mouse event
                if (isTouch) {
                    recordTouches.call(this, inputEvent, inputData);
                }
                else if (isMouse && isSyntheticEvent.call(this, inputData)) {
                    return;
                }
                this.callback(manager, inputEvent, inputData);
            },
            /**
             * remove the event listeners
             */
            destroy: function destroy() {
                this.touch.destroy();
                this.mouse.destroy();
            }
        });
        function recordTouches(eventType, eventData) {
            if (eventType & INPUT_START) {
                this.primaryTouch = eventData.changedPointers[0].identifier;
                setLastTouch.call(this, eventData);
            }
            else if (eventType & (INPUT_END | INPUT_CANCEL)) {
                setLastTouch.call(this, eventData);
            }
        }
        function setLastTouch(eventData) {
            var touch = eventData.changedPointers[0];
            if (touch.identifier === this.primaryTouch) {
                var lastTouch = { x: touch.clientX, y: touch.clientY };
                this.lastTouches.push(lastTouch);
                var lts = this.lastTouches;
                var removeLastTouch = function () {
                    var i = lts.indexOf(lastTouch);
                    if (i > -1) {
                        lts.splice(i, 1);
                    }
                };
                setTimeout(removeLastTouch, DEDUP_TIMEOUT);
            }
        }
        function isSyntheticEvent(eventData) {
            var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;
            for (var i = 0; i < this.lastTouches.length; i++) {
                var t = this.lastTouches[i];
                var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
                if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
                    return true;
                }
            }
            return false;
        }
        var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
        var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
        // magical touchAction value
        var TOUCH_ACTION_COMPUTE = 'compute';
        var TOUCH_ACTION_AUTO = 'auto';
        var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
        var TOUCH_ACTION_NONE = 'none';
        var TOUCH_ACTION_PAN_X = 'pan-x';
        var TOUCH_ACTION_PAN_Y = 'pan-y';
        var TOUCH_ACTION_MAP = getTouchActionProps();
        /**
         * Touch Action
         * sets the touchAction property or uses the js alternative
         * @param {Manager} manager
         * @param {String} value
         * @constructor
         */
        function TouchAction(manager, value) {
            this.manager = manager;
            this.set(value);
        }
        TouchAction.prototype = {
            /**
             * set the touchAction value on the element or enable the polyfill
             * @param {String} value
             */
            set: function (value) {
                // find out the touch-action by the event handlers
                if (value == TOUCH_ACTION_COMPUTE) {
                    value = this.compute();
                }
                if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
                    this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
                }
                this.actions = value.toLowerCase().trim();
            },
            /**
             * just re-set the touchAction value
             */
            update: function () {
                this.set(this.manager.options.touchAction);
            },
            /**
             * compute the value for the touchAction property based on the recognizer's settings
             * @returns {String} value
             */
            compute: function () {
                var actions = [];
                each(this.manager.recognizers, function (recognizer) {
                    if (boolOrFn(recognizer.options.enable, [recognizer])) {
                        actions = actions.concat(recognizer.getTouchAction());
                    }
                });
                return cleanTouchActions(actions.join(' '));
            },
            /**
             * this method is called on each input cycle and provides the preventing of the browser behavior
             * @param {Object} input
             */
            preventDefaults: function (input) {
                var srcEvent = input.srcEvent;
                var direction = input.offsetDirection;
                // if the touch action did prevented once this session
                if (this.manager.session.prevented) {
                    srcEvent.preventDefault();
                    return;
                }
                var actions = this.actions;
                var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
                var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
                var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
                if (hasNone) {
                    //do not prevent defaults if this is a tap gesture
                    var isTapPointer = input.pointers.length === 1;
                    var isTapMovement = input.distance < 2;
                    var isTapTouchTime = input.deltaTime < 250;
                    if (isTapPointer && isTapMovement && isTapTouchTime) {
                        return;
                    }
                }
                if (hasPanX && hasPanY) {
                    // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
                    return;
                }
                if (hasNone ||
                    (hasPanY && direction & DIRECTION_HORIZONTAL) ||
                    (hasPanX && direction & DIRECTION_VERTICAL)) {
                    return this.preventSrc(srcEvent);
                }
            },
            /**
             * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
             * @param {Object} srcEvent
             */
            preventSrc: function (srcEvent) {
                this.manager.session.prevented = true;
                srcEvent.preventDefault();
            }
        };
        /**
         * when the touchActions are collected they are not a valid value, so we need to clean things up. *
         * @param {String} actions
         * @returns {*}
         */
        function cleanTouchActions(actions) {
            // none
            if (inStr(actions, TOUCH_ACTION_NONE)) {
                return TOUCH_ACTION_NONE;
            }
            var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
            var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
            // if both pan-x and pan-y are set (different recognizers
            // for different directions, e.g. horizontal pan but vertical swipe?)
            // we need none (as otherwise with pan-x pan-y combined none of these
            // recognizers will work, since the browser would handle all panning
            if (hasPanX && hasPanY) {
                return TOUCH_ACTION_NONE;
            }
            // pan-x OR pan-y
            if (hasPanX || hasPanY) {
                return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
            }
            // manipulation
            if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
                return TOUCH_ACTION_MANIPULATION;
            }
            return TOUCH_ACTION_AUTO;
        }
        function getTouchActionProps() {
            if (!NATIVE_TOUCH_ACTION) {
                return false;
            }
            var touchMap = {};
            var cssSupports = window.CSS && window.CSS.supports;
            ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function (val) {
                // If css.supports is not supported but there is native touch-action assume it supports
                // all values. This is the case for IE 10 and 11.
                touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
            });
            return touchMap;
        }
        /**
         * Recognizer flow explained; *
         * All recognizers have the initial state of POSSIBLE when a input session starts.
         * The definition of a input session is from the first input until the last input, with all it's movement in it. *
         * Example session for mouse-input: mousedown -> mousemove -> mouseup
         *
         * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
         * which determines with state it should be.
         *
         * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
         * POSSIBLE to give it another change on the next cycle.
         *
         *               Possible
         *                  |
         *            +-----+---------------+
         *            |                     |
         *      +-----+-----+               |
         *      |           |               |
         *   Failed      Cancelled          |
         *                          +-------+------+
         *                          |              |
         *                      Recognized       Began
         *                                         |
         *                                      Changed
         *                                         |
         *                                  Ended/Recognized
         */
        var STATE_POSSIBLE = 1;
        var STATE_BEGAN = 2;
        var STATE_CHANGED = 4;
        var STATE_ENDED = 8;
        var STATE_RECOGNIZED = STATE_ENDED;
        var STATE_CANCELLED = 16;
        var STATE_FAILED = 32;
        /**
         * Recognizer
         * Every recognizer needs to extend from this class.
         * @constructor
         * @param {Object} options
         */
        function Recognizer(options) {
            this.options = assign({}, this.defaults, options || {});
            this.id = uniqueId();
            this.manager = null;
            // default is enable true
            this.options.enable = ifUndefined(this.options.enable, true);
            this.state = STATE_POSSIBLE;
            this.simultaneous = {};
            this.requireFail = [];
        }
        Recognizer.prototype = {
            /**
             * @virtual
             * @type {Object}
             */
            defaults: {},
            /**
             * set options
             * @param {Object} options
             * @return {Recognizer}
             */
            set: function (options) {
                assign(this.options, options);
                // also update the touchAction, in case something changed about the directions/enabled state
                this.manager && this.manager.touchAction.update();
                return this;
            },
            /**
             * recognize simultaneous with an other recognizer.
             * @param {Recognizer} otherRecognizer
             * @returns {Recognizer} this
             */
            recognizeWith: function (otherRecognizer) {
                if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
                    return this;
                }
                var simultaneous = this.simultaneous;
                otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
                if (!simultaneous[otherRecognizer.id]) {
                    simultaneous[otherRecognizer.id] = otherRecognizer;
                    otherRecognizer.recognizeWith(this);
                }
                return this;
            },
            /**
             * drop the simultaneous link. it doesnt remove the link on the other recognizer.
             * @param {Recognizer} otherRecognizer
             * @returns {Recognizer} this
             */
            dropRecognizeWith: function (otherRecognizer) {
                if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
                    return this;
                }
                otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
                delete this.simultaneous[otherRecognizer.id];
                return this;
            },
            /**
             * recognizer can only run when an other is failing
             * @param {Recognizer} otherRecognizer
             * @returns {Recognizer} this
             */
            requireFailure: function (otherRecognizer) {
                if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
                    return this;
                }
                var requireFail = this.requireFail;
                otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
                if (inArray(requireFail, otherRecognizer) === -1) {
                    requireFail.push(otherRecognizer);
                    otherRecognizer.requireFailure(this);
                }
                return this;
            },
            /**
             * drop the requireFailure link. it does not remove the link on the other recognizer.
             * @param {Recognizer} otherRecognizer
             * @returns {Recognizer} this
             */
            dropRequireFailure: function (otherRecognizer) {
                if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
                    return this;
                }
                otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
                var index = inArray(this.requireFail, otherRecognizer);
                if (index > -1) {
                    this.requireFail.splice(index, 1);
                }
                return this;
            },
            /**
             * has require failures boolean
             * @returns {boolean}
             */
            hasRequireFailures: function () {
                return this.requireFail.length > 0;
            },
            /**
             * if the recognizer can recognize simultaneous with an other recognizer
             * @param {Recognizer} otherRecognizer
             * @returns {Boolean}
             */
            canRecognizeWith: function (otherRecognizer) {
                return !!this.simultaneous[otherRecognizer.id];
            },
            /**
             * You should use `tryEmit` instead of `emit` directly to check
             * that all the needed recognizers has failed before emitting.
             * @param {Object} input
             */
            emit: function (input) {
                var self = this;
                var state = this.state;
                function emit(event) {
                    self.manager.emit(event, input);
                }
                // 'panstart' and 'panmove'
                if (state < STATE_ENDED) {
                    emit(self.options.event + stateStr(state));
                }
                emit(self.options.event); // simple 'eventName' events
                if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
                    emit(input.additionalEvent);
                }
                // panend and pancancel
                if (state >= STATE_ENDED) {
                    emit(self.options.event + stateStr(state));
                }
            },
            /**
             * Check that all the require failure recognizers has failed,
             * if true, it emits a gesture event,
             * otherwise, setup the state to FAILED.
             * @param {Object} input
             */
            tryEmit: function (input) {
                if (this.canEmit()) {
                    return this.emit(input);
                }
                // it's failing anyway
                this.state = STATE_FAILED;
            },
            /**
             * can we emit?
             * @returns {boolean}
             */
            canEmit: function () {
                var i = 0;
                while (i < this.requireFail.length) {
                    if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
                        return false;
                    }
                    i++;
                }
                return true;
            },
            /**
             * update the recognizer
             * @param {Object} inputData
             */
            recognize: function (inputData) {
                // make a new copy of the inputData
                // so we can change the inputData without messing up the other recognizers
                var inputDataClone = assign({}, inputData);
                // is is enabled and allow recognizing?
                if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
                    this.reset();
                    this.state = STATE_FAILED;
                    return;
                }
                // reset when we've reached the end
                if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
                    this.state = STATE_POSSIBLE;
                }
                this.state = this.process(inputDataClone);
                // the recognizer has recognized a gesture
                // so trigger an event
                if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
                    this.tryEmit(inputDataClone);
                }
            },
            /**
             * return the state of the recognizer
             * the actual recognizing happens in this method
             * @virtual
             * @param {Object} inputData
             * @returns {Const} STATE
             */
            process: function (inputData) { },
            /**
             * return the preferred touch-action
             * @virtual
             * @returns {Array}
             */
            getTouchAction: function () { },
            /**
             * called when the gesture isn't allowed to recognize
             * like when another is being recognized or it is disabled
             * @virtual
             */
            reset: function () { }
        };
        /**
         * get a usable string, used as event postfix
         * @param {Const} state
         * @returns {String} state
         */
        function stateStr(state) {
            if (state & STATE_CANCELLED) {
                return 'cancel';
            }
            else if (state & STATE_ENDED) {
                return 'end';
            }
            else if (state & STATE_CHANGED) {
                return 'move';
            }
            else if (state & STATE_BEGAN) {
                return 'start';
            }
            return '';
        }
        /**
         * direction cons to string
         * @param {Const} direction
         * @returns {String}
         */
        function directionStr(direction) {
            if (direction == DIRECTION_DOWN) {
                return 'down';
            }
            else if (direction == DIRECTION_UP) {
                return 'up';
            }
            else if (direction == DIRECTION_LEFT) {
                return 'left';
            }
            else if (direction == DIRECTION_RIGHT) {
                return 'right';
            }
            return '';
        }
        /**
         * get a recognizer by name if it is bound to a manager
         * @param {Recognizer|String} otherRecognizer
         * @param {Recognizer} recognizer
         * @returns {Recognizer}
         */
        function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
            var manager = recognizer.manager;
            if (manager) {
                return manager.get(otherRecognizer);
            }
            return otherRecognizer;
        }
        /**
         * This recognizer is just used as a base for the simple attribute recognizers.
         * @constructor
         * @extends Recognizer
         */
        function AttrRecognizer() {
            Recognizer.apply(this, arguments);
        }
        inherit(AttrRecognizer, Recognizer, {
            /**
             * @namespace
             * @memberof AttrRecognizer
             */
            defaults: {
                /**
                 * @type {Number}
                 * @default 1
                 */
                pointers: 1
            },
            /**
             * Used to check if it the recognizer receives valid input, like input.distance > 10.
             * @memberof AttrRecognizer
             * @param {Object} input
             * @returns {Boolean} recognized
             */
            attrTest: function (input) {
                var optionPointers = this.options.pointers;
                return optionPointers === 0 || input.pointers.length === optionPointers;
            },
            /**
             * Process the input and return the state for the recognizer
             * @memberof AttrRecognizer
             * @param {Object} input
             * @returns {*} State
             */
            process: function (input) {
                var state = this.state;
                var eventType = input.eventType;
                var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
                var isValid = this.attrTest(input);
                // on cancel input and we've recognized before, return STATE_CANCELLED
                if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
                    return state | STATE_CANCELLED;
                }
                else if (isRecognized || isValid) {
                    if (eventType & INPUT_END) {
                        return state | STATE_ENDED;
                    }
                    else if (!(state & STATE_BEGAN)) {
                        return STATE_BEGAN;
                    }
                    return state | STATE_CHANGED;
                }
                return STATE_FAILED;
            }
        });
        /**
         * Pan
         * Recognized when the pointer is down and moved in the allowed direction.
         * @constructor
         * @extends AttrRecognizer
         */
        function PanRecognizer() {
            AttrRecognizer.apply(this, arguments);
            this.pX = null;
            this.pY = null;
        }
        inherit(PanRecognizer, AttrRecognizer, {
            /**
             * @namespace
             * @memberof PanRecognizer
             */
            defaults: {
                event: 'pan',
                threshold: 10,
                pointers: 1,
                direction: DIRECTION_ALL
            },
            getTouchAction: function () {
                var direction = this.options.direction;
                var actions = [];
                if (direction & DIRECTION_HORIZONTAL) {
                    actions.push(TOUCH_ACTION_PAN_Y);
                }
                if (direction & DIRECTION_VERTICAL) {
                    actions.push(TOUCH_ACTION_PAN_X);
                }
                return actions;
            },
            directionTest: function (input) {
                var options = this.options;
                var hasMoved = true;
                var distance = input.distance;
                var direction = input.direction;
                var x = input.deltaX;
                var y = input.deltaY;
                // lock to axis?
                if (!(direction & options.direction)) {
                    if (options.direction & DIRECTION_HORIZONTAL) {
                        direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
                        hasMoved = x != this.pX;
                        distance = Math.abs(input.deltaX);
                    }
                    else {
                        direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
                        hasMoved = y != this.pY;
                        distance = Math.abs(input.deltaY);
                    }
                }
                input.direction = direction;
                return hasMoved && distance > options.threshold && direction & options.direction;
            },
            attrTest: function (input) {
                return AttrRecognizer.prototype.attrTest.call(this, input) &&
                    (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
            },
            emit: function (input) {
                this.pX = input.deltaX;
                this.pY = input.deltaY;
                var direction = directionStr(input.direction);
                if (direction) {
                    input.additionalEvent = this.options.event + direction;
                }
                this._super.emit.call(this, input);
            }
        });
        /**
         * Pinch
         * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
         * @constructor
         * @extends AttrRecognizer
         */
        function PinchRecognizer() {
            AttrRecognizer.apply(this, arguments);
        }
        inherit(PinchRecognizer, AttrRecognizer, {
            /**
             * @namespace
             * @memberof PinchRecognizer
             */
            defaults: {
                event: 'pinch',
                threshold: 0,
                pointers: 2
            },
            getTouchAction: function () {
                return [TOUCH_ACTION_NONE];
            },
            attrTest: function (input) {
                return this._super.attrTest.call(this, input) &&
                    (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
            },
            emit: function (input) {
                if (input.scale !== 1) {
                    var inOut = input.scale < 1 ? 'in' : 'out';
                    input.additionalEvent = this.options.event + inOut;
                }
                this._super.emit.call(this, input);
            }
        });
        /**
         * Press
         * Recognized when the pointer is down for x ms without any movement.
         * @constructor
         * @extends Recognizer
         */
        function PressRecognizer() {
            Recognizer.apply(this, arguments);
            this._timer = null;
            this._input = null;
        }
        inherit(PressRecognizer, Recognizer, {
            /**
             * @namespace
             * @memberof PressRecognizer
             */
            defaults: {
                event: 'press',
                pointers: 1,
                time: 251,
                threshold: 9 // a minimal movement is ok, but keep it low
            },
            getTouchAction: function () {
                return [TOUCH_ACTION_AUTO];
            },
            process: function (input) {
                var options = this.options;
                var validPointers = input.pointers.length === options.pointers;
                var validMovement = input.distance < options.threshold;
                var validTime = input.deltaTime > options.time;
                this._input = input;
                // we only allow little movement
                // and we've reached an end event, so a tap is possible
                if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
                    this.reset();
                }
                else if (input.eventType & INPUT_START) {
                    this.reset();
                    this._timer = setTimeoutContext(function () {
                        this.state = STATE_RECOGNIZED;
                        this.tryEmit();
                    }, options.time, this);
                }
                else if (input.eventType & INPUT_END) {
                    return STATE_RECOGNIZED;
                }
                return STATE_FAILED;
            },
            reset: function () {
                clearTimeout(this._timer);
            },
            emit: function (input) {
                if (this.state !== STATE_RECOGNIZED) {
                    return;
                }
                if (input && (input.eventType & INPUT_END)) {
                    this.manager.emit(this.options.event + 'up', input);
                }
                else {
                    this._input.timeStamp = now();
                    this.manager.emit(this.options.event, this._input);
                }
            }
        });
        /**
         * Rotate
         * Recognized when two or more pointer are moving in a circular motion.
         * @constructor
         * @extends AttrRecognizer
         */
        function RotateRecognizer() {
            AttrRecognizer.apply(this, arguments);
        }
        inherit(RotateRecognizer, AttrRecognizer, {
            /**
             * @namespace
             * @memberof RotateRecognizer
             */
            defaults: {
                event: 'rotate',
                threshold: 0,
                pointers: 2
            },
            getTouchAction: function () {
                return [TOUCH_ACTION_NONE];
            },
            attrTest: function (input) {
                return this._super.attrTest.call(this, input) &&
                    (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
            }
        });
        /**
         * Swipe
         * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
         * @constructor
         * @extends AttrRecognizer
         */
        function SwipeRecognizer() {
            AttrRecognizer.apply(this, arguments);
        }
        inherit(SwipeRecognizer, AttrRecognizer, {
            /**
             * @namespace
             * @memberof SwipeRecognizer
             */
            defaults: {
                event: 'swipe',
                threshold: 10,
                velocity: 0.3,
                direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
                pointers: 1
            },
            getTouchAction: function () {
                return PanRecognizer.prototype.getTouchAction.call(this);
            },
            attrTest: function (input) {
                var direction = this.options.direction;
                var velocity;
                if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
                    velocity = input.overallVelocity;
                }
                else if (direction & DIRECTION_HORIZONTAL) {
                    velocity = input.overallVelocityX;
                }
                else if (direction & DIRECTION_VERTICAL) {
                    velocity = input.overallVelocityY;
                }
                return this._super.attrTest.call(this, input) &&
                    direction & input.offsetDirection &&
                    input.distance > this.options.threshold &&
                    input.maxPointers == this.options.pointers &&
                    abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
            },
            emit: function (input) {
                var direction = directionStr(input.offsetDirection);
                if (direction) {
                    this.manager.emit(this.options.event + direction, input);
                }
                this.manager.emit(this.options.event, input);
            }
        });
        /**
         * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
         * between the given interval and position. The delay option can be used to recognize multi-taps without firing
         * a single tap.
         *
         * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
         * multi-taps being recognized.
         * @constructor
         * @extends Recognizer
         */
        function TapRecognizer() {
            Recognizer.apply(this, arguments);
            // previous time and center,
            // used for tap counting
            this.pTime = false;
            this.pCenter = false;
            this._timer = null;
            this._input = null;
            this.count = 0;
        }
        inherit(TapRecognizer, Recognizer, {
            /**
             * @namespace
             * @memberof PinchRecognizer
             */
            defaults: {
                event: 'tap',
                pointers: 1,
                taps: 1,
                interval: 300,
                time: 250,
                threshold: 9,
                posThreshold: 10 // a multi-tap can be a bit off the initial position
            },
            getTouchAction: function () {
                return [TOUCH_ACTION_MANIPULATION];
            },
            process: function (input) {
                var options = this.options;
                var validPointers = input.pointers.length === options.pointers;
                var validMovement = input.distance < options.threshold;
                var validTouchTime = input.deltaTime < options.time;
                this.reset();
                if ((input.eventType & INPUT_START) && (this.count === 0)) {
                    return this.failTimeout();
                }
                // we only allow little movement
                // and we've reached an end event, so a tap is possible
                if (validMovement && validTouchTime && validPointers) {
                    if (input.eventType != INPUT_END) {
                        return this.failTimeout();
                    }
                    var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
                    var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
                    this.pTime = input.timeStamp;
                    this.pCenter = input.center;
                    if (!validMultiTap || !validInterval) {
                        this.count = 1;
                    }
                    else {
                        this.count += 1;
                    }
                    this._input = input;
                    // if tap count matches we have recognized it,
                    // else it has began recognizing...
                    var tapCount = this.count % options.taps;
                    if (tapCount === 0) {
                        // no failing requirements, immediately trigger the tap event
                        // or wait as long as the multitap interval to trigger
                        if (!this.hasRequireFailures()) {
                            return STATE_RECOGNIZED;
                        }
                        else {
                            this._timer = setTimeoutContext(function () {
                                this.state = STATE_RECOGNIZED;
                                this.tryEmit();
                            }, options.interval, this);
                            return STATE_BEGAN;
                        }
                    }
                }
                return STATE_FAILED;
            },
            failTimeout: function () {
                this._timer = setTimeoutContext(function () {
                    this.state = STATE_FAILED;
                }, this.options.interval, this);
                return STATE_FAILED;
            },
            reset: function () {
                clearTimeout(this._timer);
            },
            emit: function () {
                if (this.state == STATE_RECOGNIZED) {
                    this._input.tapCount = this.count;
                    this.manager.emit(this.options.event, this._input);
                }
            }
        });
        /**
         * Simple way to create a manager with a default set of recognizers.
         * @param {HTMLElement} element
         * @param {Object} [options]
         * @constructor
         */
        function Hammer(element, options) {
            options = options || {};
            options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
            return new Manager(element, options);
        }
        /**
         * @const {string}
         */
        Hammer.VERSION = '2.0.7';
        /**
         * default settings
         * @namespace
         */
        Hammer.defaults = {
            /**
             * set if DOM events are being triggered.
             * But this is slower and unused by simple implementations, so disabled by default.
             * @type {Boolean}
             * @default false
             */
            domEvents: false,
            /**
             * The value for the touchAction property/fallback.
             * When set to `compute` it will magically set the correct value based on the added recognizers.
             * @type {String}
             * @default compute
             */
            touchAction: TOUCH_ACTION_COMPUTE,
            /**
             * @type {Boolean}
             * @default true
             */
            enable: true,
            /**
             * EXPERIMENTAL FEATURE -- can be removed/changed
             * Change the parent input target element.
             * If Null, then it is being set the to main element.
             * @type {Null|EventTarget}
             * @default null
             */
            inputTarget: null,
            /**
             * force an input class
             * @type {Null|Function}
             * @default null
             */
            inputClass: null,
            /**
             * Default recognizer setup when calling `Hammer()`
             * When creating a new Manager these will be skipped.
             * @type {Array}
             */
            preset: [
                // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
                [RotateRecognizer, { enable: false }],
                [PinchRecognizer, { enable: false }, ['rotate']],
                [SwipeRecognizer, { direction: DIRECTION_HORIZONTAL }],
                [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']],
                [TapRecognizer],
                [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']],
                [PressRecognizer]
            ],
            /**
             * Some CSS properties can be used to improve the working of Hammer.
             * Add them to this method and they will be set when creating a new Manager.
             * @namespace
             */
            cssProps: {
                /**
                 * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
                 * @type {String}
                 * @default 'none'
                 */
                userSelect: 'none',
                /**
                 * Disable the Windows Phone grippers when pressing an element.
                 * @type {String}
                 * @default 'none'
                 */
                touchSelect: 'none',
                /**
                 * Disables the default callout shown when you touch and hold a touch target.
                 * On iOS, when you touch and hold a touch target such as a link, Safari displays
                 * a callout containing information about the link. This property allows you to disable that callout.
                 * @type {String}
                 * @default 'none'
                 */
                touchCallout: 'none',
                /**
                 * Specifies whether zooming is enabled. Used by IE10>
                 * @type {String}
                 * @default 'none'
                 */
                contentZooming: 'none',
                /**
                 * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
                 * @type {String}
                 * @default 'none'
                 */
                userDrag: 'none',
                /**
                 * Overrides the highlight color shown when the user taps a link or a JavaScript
                 * clickable element in iOS. This property obeys the alpha value, if specified.
                 * @type {String}
                 * @default 'rgba(0,0,0,0)'
                 */
                tapHighlightColor: 'rgba(0,0,0,0)'
            }
        };
        var STOP = 1;
        var FORCED_STOP = 2;
        /**
         * Manager
         * @param {HTMLElement} element
         * @param {Object} [options]
         * @constructor
         */
        function Manager(element, options) {
            this.options = assign({}, Hammer.defaults, options || {});
            this.options.inputTarget = this.options.inputTarget || element;
            this.handlers = {};
            this.session = {};
            this.recognizers = [];
            this.oldCssProps = {};
            this.element = element;
            this.input = createInputInstance(this);
            this.touchAction = new TouchAction(this, this.options.touchAction);
            toggleCssProps(this, true);
            each(this.options.recognizers, function (item) {
                var recognizer = this.add(new (item[0])(item[1]));
                item[2] && recognizer.recognizeWith(item[2]);
                item[3] && recognizer.requireFailure(item[3]);
            }, this);
        }
        Manager.prototype = {
            /**
             * set options
             * @param {Object} options
             * @returns {Manager}
             */
            set: function (options) {
                assign(this.options, options);
                // Options that need a little more setup
                if (options.touchAction) {
                    this.touchAction.update();
                }
                if (options.inputTarget) {
                    // Clean up existing event listeners and reinitialize
                    this.input.destroy();
                    this.input.target = options.inputTarget;
                    this.input.init();
                }
                return this;
            },
            /**
             * stop recognizing for this session.
             * This session will be discarded, when a new [input]start event is fired.
             * When forced, the recognizer cycle is stopped immediately.
             * @param {Boolean} [force]
             */
            stop: function (force) {
                this.session.stopped = force ? FORCED_STOP : STOP;
            },
            /**
             * run the recognizers!
             * called by the inputHandler function on every movement of the pointers (touches)
             * it walks through all the recognizers and tries to detect the gesture that is being made
             * @param {Object} inputData
             */
            recognize: function (inputData) {
                var session = this.session;
                if (session.stopped) {
                    return;
                }
                // run the touch-action polyfill
                this.touchAction.preventDefaults(inputData);
                var recognizer;
                var recognizers = this.recognizers;
                // this holds the recognizer that is being recognized.
                // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
                // if no recognizer is detecting a thing, it is set to `null`
                var curRecognizer = session.curRecognizer;
                // reset when the last recognizer is recognized
                // or when we're in a new session
                if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
                    curRecognizer = session.curRecognizer = null;
                }
                var i = 0;
                while (i < recognizers.length) {
                    recognizer = recognizers[i];
                    // find out if we are allowed try to recognize the input for this one.
                    // 1.   allow if the session is NOT forced stopped (see the .stop() method)
                    // 2.   allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
                    //      that is being recognized.
                    // 3.   allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
                    //      this can be setup with the `recognizeWith()` method on the recognizer.
                    if (session.stopped !== FORCED_STOP && ( // 1
                    !curRecognizer || recognizer == curRecognizer || // 2
                        recognizer.canRecognizeWith(curRecognizer))) { // 3
                        recognizer.recognize(inputData);
                    }
                    else {
                        recognizer.reset();
                    }
                    // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
                    // current active recognizer. but only if we don't already have an active recognizer
                    if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
                        curRecognizer = session.curRecognizer = recognizer;
                    }
                    i++;
                }
            },
            /**
             * get a recognizer by its event name.
             * @param {Recognizer|String} recognizer
             * @returns {Recognizer|Null}
             */
            get: function (recognizer) {
                if (recognizer instanceof Recognizer) {
                    return recognizer;
                }
                var recognizers = this.recognizers;
                for (var i = 0; i < recognizers.length; i++) {
                    if (recognizers[i].options.event == recognizer) {
                        return recognizers[i];
                    }
                }
                return null;
            },
            /**
             * add a recognizer to the manager
             * existing recognizers with the same event name will be removed
             * @param {Recognizer} recognizer
             * @returns {Recognizer|Manager}
             */
            add: function (recognizer) {
                if (invokeArrayArg(recognizer, 'add', this)) {
                    return this;
                }
                // remove existing
                var existing = this.get(recognizer.options.event);
                if (existing) {
                    this.remove(existing);
                }
                this.recognizers.push(recognizer);
                recognizer.manager = this;
                this.touchAction.update();
                return recognizer;
            },
            /**
             * remove a recognizer by name or instance
             * @param {Recognizer|String} recognizer
             * @returns {Manager}
             */
            remove: function (recognizer) {
                if (invokeArrayArg(recognizer, 'remove', this)) {
                    return this;
                }
                recognizer = this.get(recognizer);
                // let's make sure this recognizer exists
                if (recognizer) {
                    var recognizers = this.recognizers;
                    var index = inArray(recognizers, recognizer);
                    if (index !== -1) {
                        recognizers.splice(index, 1);
                        this.touchAction.update();
                    }
                }
                return this;
            },
            /**
             * bind event
             * @param {String} events
             * @param {Function} handler
             * @returns {EventEmitter} this
             */
            on: function (events, handler) {
                if (events === undefined) {
                    return;
                }
                if (handler === undefined) {
                    return;
                }
                var handlers = this.handlers;
                each(splitStr(events), function (event) {
                    handlers[event] = handlers[event] || [];
                    handlers[event].push(handler);
                });
                return this;
            },
            /**
             * unbind event, leave emit blank to remove all handlers
             * @param {String} events
             * @param {Function} [handler]
             * @returns {EventEmitter} this
             */
            off: function (events, handler) {
                if (events === undefined) {
                    return;
                }
                var handlers = this.handlers;
                each(splitStr(events), function (event) {
                    if (!handler) {
                        delete handlers[event];
                    }
                    else {
                        handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
                    }
                });
                return this;
            },
            /**
             * emit event to the listeners
             * @param {String} event
             * @param {Object} data
             */
            emit: function (event, data) {
                // we also want to trigger dom events
                if (this.options.domEvents) {
                    triggerDomEvent(event, data);
                }
                // no handlers, so skip it all
                var handlers = this.handlers[event] && this.handlers[event].slice();
                if (!handlers || !handlers.length) {
                    return;
                }
                data.type = event;
                data.preventDefault = function () {
                    data.srcEvent.preventDefault();
                };
                var i = 0;
                while (i < handlers.length) {
                    handlers[i](data);
                    i++;
                }
            },
            /**
             * destroy the manager and unbinds all events
             * it doesn't unbind dom events, that is the user own responsibility
             */
            destroy: function () {
                this.element && toggleCssProps(this, false);
                this.handlers = {};
                this.session = {};
                this.input.destroy();
                this.element = null;
            }
        };
        /**
         * add/remove the css properties as defined in manager.options.cssProps
         * @param {Manager} manager
         * @param {Boolean} add
         */
        function toggleCssProps(manager, add) {
            var element = manager.element;
            if (!element.style) {
                return;
            }
            var prop;
            each(manager.options.cssProps, function (value, name) {
                prop = prefixed(element.style, name);
                if (add) {
                    manager.oldCssProps[prop] = element.style[prop];
                    element.style[prop] = value;
                }
                else {
                    element.style[prop] = manager.oldCssProps[prop] || '';
                }
            });
            if (!add) {
                manager.oldCssProps = {};
            }
        }
        /**
         * trigger dom event
         * @param {String} event
         * @param {Object} data
         */
        function triggerDomEvent(event, data) {
            var gestureEvent = document.createEvent('Event');
            gestureEvent.initEvent(event, true, true);
            gestureEvent.gesture = data;
            data.target.dispatchEvent(gestureEvent);
        }
        assign(Hammer, {
            INPUT_START: INPUT_START,
            INPUT_MOVE: INPUT_MOVE,
            INPUT_END: INPUT_END,
            INPUT_CANCEL: INPUT_CANCEL,
            STATE_POSSIBLE: STATE_POSSIBLE,
            STATE_BEGAN: STATE_BEGAN,
            STATE_CHANGED: STATE_CHANGED,
            STATE_ENDED: STATE_ENDED,
            STATE_RECOGNIZED: STATE_RECOGNIZED,
            STATE_CANCELLED: STATE_CANCELLED,
            STATE_FAILED: STATE_FAILED,
            DIRECTION_NONE: DIRECTION_NONE,
            DIRECTION_LEFT: DIRECTION_LEFT,
            DIRECTION_RIGHT: DIRECTION_RIGHT,
            DIRECTION_UP: DIRECTION_UP,
            DIRECTION_DOWN: DIRECTION_DOWN,
            DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
            DIRECTION_VERTICAL: DIRECTION_VERTICAL,
            DIRECTION_ALL: DIRECTION_ALL,
            Manager: Manager,
            Input: Input,
            TouchAction: TouchAction,
            TouchInput: TouchInput,
            MouseInput: MouseInput,
            PointerEventInput: PointerEventInput,
            TouchMouseInput: TouchMouseInput,
            SingleTouchInput: SingleTouchInput,
            Recognizer: Recognizer,
            AttrRecognizer: AttrRecognizer,
            Tap: TapRecognizer,
            Pan: PanRecognizer,
            Swipe: SwipeRecognizer,
            Pinch: PinchRecognizer,
            Rotate: RotateRecognizer,
            Press: PressRecognizer,
            on: addEventListeners,
            off: removeEventListeners,
            each: each,
            merge: merge,
            extend: extend,
            assign: assign,
            inherit: inherit,
            bindFn: bindFn,
            prefixed: prefixed
        });
        // this prevents errors when Hammer is loaded in the presence of an AMD
        //  style loader but by script tag, not by the loader.
        var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
        freeGlobal.Hammer = Hammer;
        if (typeof define === 'function' && define.amd) {
            define(function () {
                return Hammer;
            });
        }
        else if (typeof module != 'undefined' && module.exports) {
            module.exports = Hammer;
        }
        else {
            window[exportName] = Hammer;
        }
    })(window, document, 'Hammer');
},
/* core/dom_view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var view_1 = require(157) /* ./view */;
    var dom_1 = require(158) /* ./dom */;
    var DOMView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DOMView, _super);
        function DOMView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        DOMView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.el = this._createElement();
        };
        DOMView.prototype.remove = function () {
            (0, dom_1.remove)(this.el);
            _super.prototype.remove.call(this);
        };
        DOMView.prototype.css_classes = function () {
            return [];
        };
        DOMView.prototype.render = function () { };
        DOMView.prototype.renderTo = function (element) {
            element.appendChild(this.el);
            this.render();
            this._has_finished = true;
            this.notify_finished();
        };
        DOMView.prototype._createElement = function () {
            return (0, dom_1.createElement)(this.constructor.tag_name, { class: this.css_classes() });
        };
        return DOMView;
    }(view_1.View));
    exports.DOMView = DOMView;
    DOMView.__name__ = "DOMView";
    DOMView.tag_name = "div";
},
/* styles/toolbar.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.toolbar_hidden = "bk-toolbar-hidden";
    exports.toolbar = "bk-toolbar";
    exports.logo = "bk-logo";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.toolbar_button = "bk-toolbar-button";
    exports.tool_overflow = "bk-tool-overflow";
    exports.active = "bk-active";
    exports.divider = "bk-divider";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.default = ".bk-root .bk-toolbar-hidden{visibility:hidden;opacity:0;transition:visibility 0.3s linear, opacity 0.3s linear;}.bk-root .bk-toolbar{display:flex;flex-wrap:nowrap;align-items:center;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;}.bk-root .bk-toolbar .bk-logo{flex-shrink:0;}.bk-root .bk-toolbar.bk-above,.bk-root .bk-toolbar.bk-below{flex-direction:row;justify-content:flex-end;}.bk-root .bk-toolbar.bk-above .bk-logo,.bk-root .bk-toolbar.bk-below .bk-logo{order:1;margin-left:5px;margin-right:0px;}.bk-root .bk-toolbar.bk-left,.bk-root .bk-toolbar.bk-right{flex-direction:column;justify-content:flex-start;}.bk-root .bk-toolbar.bk-left .bk-logo,.bk-root .bk-toolbar.bk-right .bk-logo{order:0;margin-bottom:5px;margin-top:0px;}.bk-root .bk-toolbar-button{width:30px;height:30px;cursor:pointer;background-size:60% 60%;background-origin:border-box;background-color:transparent;background-repeat:no-repeat;background-position:center center;}.bk-root .bk-toolbar-button:hover,.bk-root .bk-tool-overflow:hover{background-color:rgba(192, 192, 192, 0.15);}.bk-root .bk-toolbar-button:focus,.bk-root .bk-tool-overflow:focus,.bk-root .bk-toolbar-button:focus-visible,.bk-root .bk-tool-overflow:focus-visible{outline:1px dotted #26aae1;outline-offset:-1px;}.bk-root .bk-toolbar-button::-moz-focus-inner,.bk-root .bk-tool-overflow::-moz-focus-inner{border:0;}.bk-root .bk-above .bk-toolbar-button{border-bottom:2px solid transparent;}.bk-root .bk-above .bk-toolbar-button.bk-active{border-bottom-color:#26aae1;}.bk-root .bk-below .bk-toolbar-button{border-top:2px solid transparent;}.bk-root .bk-below .bk-toolbar-button.bk-active{border-top-color:#26aae1;}.bk-root .bk-right .bk-toolbar-button{border-left:2px solid transparent;}.bk-root .bk-right .bk-toolbar-button.bk-active{border-left-color:#26aae1;}.bk-root .bk-left .bk-toolbar-button{border-right:2px solid transparent;}.bk-root .bk-left .bk-toolbar-button.bk-active{border-right-color:#26aae1;}.bk-root .bk-divider{content:\" \";display:inline-block;background-color:lightgray;}.bk-root .bk-above .bk-divider,.bk-root .bk-below .bk-divider{height:10px;width:1px;}.bk-root .bk-left .bk-divider,.bk-root .bk-right .bk-divider{height:1px;width:10px;}.bk-root .bk-tool-overflow{color:gray;display:flex;align-items:center;}.bk-root .bk-above .bk-tool-overflow,.bk-root .bk-below .bk-tool-overflow,.bk-root .bk-horizontal .bk-tool-overflow{width:15px;height:30px;flex-direction:row;}.bk-root .bk-left .bk-tool-overflow,.bk-root .bk-right .bk-tool-overflow,.bk-root .bk-vertical .bk-tool-overflow{width:30px;height:15px;flex-direction:column;}";
},
/* styles/icons.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tool_icon_copy_to_clipboard = "bk-tool-icon-copy-to-clipboard";
    exports.tool_icon_replace_mode = "bk-tool-icon-replace-mode";
    exports.tool_icon_append_mode = "bk-tool-icon-append-mode";
    exports.tool_icon_intersect_mode = "bk-tool-icon-intersect-mode";
    exports.tool_icon_subtract_mode = "bk-tool-icon-subtract-mode";
    exports.tool_icon_clear_selection = "bk-tool-icon-clear-selection";
    exports.tool_icon_box_select = "bk-tool-icon-box-select";
    exports.tool_icon_box_zoom = "bk-tool-icon-box-zoom";
    exports.tool_icon_zoom_in = "bk-tool-icon-zoom-in";
    exports.tool_icon_zoom_out = "bk-tool-icon-zoom-out";
    exports.tool_icon_help = "bk-tool-icon-help";
    exports.tool_icon_hover = "bk-tool-icon-hover";
    exports.tool_icon_crosshair = "bk-tool-icon-crosshair";
    exports.tool_icon_lasso_select = "bk-tool-icon-lasso-select";
    exports.tool_icon_pan = "bk-tool-icon-pan";
    exports.tool_icon_xpan = "bk-tool-icon-xpan";
    exports.tool_icon_ypan = "bk-tool-icon-ypan";
    exports.tool_icon_range = "bk-tool-icon-range";
    exports.tool_icon_polygon_select = "bk-tool-icon-polygon-select";
    exports.tool_icon_redo = "bk-tool-icon-redo";
    exports.tool_icon_reset = "bk-tool-icon-reset";
    exports.tool_icon_save = "bk-tool-icon-save";
    exports.tool_icon_tap_select = "bk-tool-icon-tap-select";
    exports.tool_icon_undo = "bk-tool-icon-undo";
    exports.tool_icon_wheel_pan = "bk-tool-icon-wheel-pan";
    exports.tool_icon_wheel_zoom = "bk-tool-icon-wheel-zoom";
    exports.tool_icon_box_edit = "bk-tool-icon-box-edit";
    exports.tool_icon_freehand_draw = "bk-tool-icon-freehand-draw";
    exports.tool_icon_poly_draw = "bk-tool-icon-poly-draw";
    exports.tool_icon_point_draw = "bk-tool-icon-point-draw";
    exports.tool_icon_poly_edit = "bk-tool-icon-poly-edit";
    exports.tool_icon_line_edit = "bk-tool-icon-line-edit";
    exports.default = ".bk-root .bk-tool-icon-copy-to-clipboard{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUSDBoBvcHQeQAAAG9JREFUWMNjXLhsJcNAAiaGAQYwB/xHwh/Q+ITEkfHQCwEWND4jmeb8H/JpgBwfI6cNBhLSEkqaGXRpgFRAcZoZsmlg1AGjDhh1wKgDRh0w6gCaVcf/R2wIkNqw+D9s0wADvUNiyIYA47BJAwPuAAAj/Cjd0TCN6wAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-replace-mode{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxokK3gniQAAAHpJREFUWMNjXLhsJcNAAiaGAQajDhhwB7DgEP+PxmeksvjgDwFcLmYkUh2hkBj8IcBIZXsYh1w2/I8v3sgAOM0bLYhGc8GgrwuICgldfQO88pcvXvg/aOuCUQeM5oLRuoCFCJcTbOMh5XOiW0JDNhdQS3y0IBp1ABwAAF8KGrhC1Eg6AAAAAElFTkSuQmCC\");}.bk-root .bk-tool-icon-append-mode{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxkZWD04WwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAoUlEQVRYw+1WQQ6AIAwrhO8Y/bIXEz9jIMSDr8ETCUEPQzA4pMeFLKNbu4l5WR0CDOMEALBGIzMuQIBEZQjPgP9JLjwTfBjY9sO9lZsFA9IafZng3BlIyVefgd8XQFZBAWe8jfNxwsDhir6rzoCiPiy1K+J8/FRQemv2XfAdFcQ9znU4Viqg9ta1qYJ+D1BnAIBrkgGVOrXNqUA9rbyZm/AEzFh4jEeY/soAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-intersect-mode{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxkrkOpp2wAAAPhJREFUWMPtV1EKwjAMTUavI3oawR/vtn5srJdREfzwMvHHQlcT2mpdMzFfWxiP5r2+JMN+mAiCOB72CABgR1cln4oOGocJnuMTSxWk8jMm7OggYkYXA9gPE3uyd8NXHONJ+eYMdE/NqCJmEZ5ZqlJJ4sUksKN7cYSaPoCZFWR1QI+Xm1fBACU63Cw22x0AAJxudwrffVwvZ+JmQdAHZkw0d4EpAMCw8k87pMdbnwtizQumJYv3nwV6XOA1qbUT/oQLUJgFRbsiNwFVucBIlyR3p0tdMp+XmFjfLKi1LatyAXtCRjPWBdL3Ke3VuACJKFfDr/xFN2fgAR/Go0qaLlmEAAAAAElFTkSuQmCC\");}.bk-root .bk-tool-icon-subtract-mode{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxgsF5XNOQAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAABFUlEQVRYw9VWUQqDMAxNpWfxQxD1MoP97G7zQ5mH2RTZYLtM9lWoMbXtxLXNX4OG9r28l4hrd0PQoqxqAACYpxH25C/nkwCHyCBwSPoS09k1T5Fo+4EiExcC4v584xGFmyIXHBLRISAVZyZufUPVa4rcrwmPDgr93ylo+2GliLRUYHK6th/o/6r7nfLpqaCsagEA8Hh9FmcNKeRmgeYDC+SCq0B6FFi8/BcV6BdR9cL3gCv3ijPKOacsn3rBEcjmaVxpfGcg4wHxzgJJnc6241Hn23DERFRAu1bNcWa3Q0uXi62XR6sCaWoSejbtdLYmU3kTEunNgj0bUbQqYG/IcMaqwPS9jftoVCAQ0ZVDJwf0zQdH4AsyW6fpQu4YegAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-clear-selection{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUGEhcuan3d3wAAAoRJREFUWMPtlzFP3EAQhd+b3TNSzg0N5TWXLkJQUUaKhIQ4fgP/g5ArrriE/I3opEgRrZtIVJR0FJQ010SioUmEZHtnUpwN9gWHGA5BJCy58MraffvmfZ41v3z9hqe8BE98vQh4cgG+Ydzmnrng8efvQJNi/uN7dznx/B3ggtfhf4ehNdUttRzBDIm/2VTiiWCG1HK0nc+3UWtq8BQIiEEakEQOADBIA4QCQmBqoHBhFNR27ikQSmGdYCdTqCpEHMDZmEKRWUBEv1gBDg5SzRJnpopILWICgWuRYflLamuzxB2BmtYqSRIka5VWU8QduXO+1hRc5YZu5GAwmP2ZJzND0IBu5HCV2+NQcAhAVRsnC2IbPzPdSjzd6to6VtfWkXi6YLaVWr7xoAwkfpb8MnC3SH7rKSMBe4M0jA/OTicFIbtCGRIyNbURhcf3ErCd6YwA1m0HgAxhw1NGQnlXBHG4kylVlSJuH0RfIP2CkL2I/qS1gIAAQiBl1QwFggIHtyxgrxK5PgyfC0JWKoT0HLh8LwoietB4TYKaIl7yeNURxB05UtMxDOcVQlZIrlRKdK6m47gjR/fuBRQihyLArtNeJD50Izcx2Eczu7iFkIug4VM3cpOr3MKDekFED0fWUHv9Zq0kpLnridjhY3XDg7NTN0jDrhO3X7O9Wg7wwyANu4mnayNg3gmbu0tCNoUyBNGv2l4rB9EXynA7082FOxAQLhU6rQVO9T2AvWowFToNCJcPORGxIRcnpjZSKATSU9NxvOQnAPArDSaQoUKnNI4iufkGtD4P3EHIcWZhz4HLceSOyrR3Izf5memPAL2cX3yhAkonysZVaWLBkd9dw1Ivv2a/AYPkK+ty1U1DAAAAAElFTkSuQmCC\");}.bk-root .bk-tool-icon-box-select{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg0kduFrowAAAIdJREFUWMPtVtEKwCAI9KL//4e9DPZ3+wP3KgOjNZouFYI4C8q7s7DtB1lGIeMoRMRinCLXg/ML3EcFqpjjloOyZxRntxpwQ8HsgHYARKFAtSFrCg3TCdMFCE1BuuALEXJLjC4qENsFVXCESZw38/kWLOkC/K4PcOc/Hj03WkoDT3EaWW9egQul6CUbq90JTwAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-box-zoom{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg82t254aQAAAkBJREFUWMPN11+E1FEUB/DPTFn2qaeIpcSwr5NlUyJiKWVXWUqvlUh/iE3RY9mUekkPPURtLKNRrFJEeuphGfUUaVliiX1aVjGs6aG7+XX9ZnZ+d2fTl2vmnHvPPfeee/79Sk+may2/UQq/q7Qu+bAJoxjHIKqB/wlfUMcMVqI9bLZ+DGIKwzlzQ2GcxCx2xwvKOUKlaHTiX8bHNspjDONHkOmJBW5jIof/FvPh/06MZOb6cRc7cGn1AKUE5cdzlM/gAr5F/O24H3xkFRfxAbVygvK+cIsspjGWo1zgjeFpxL+BvnLw7laBA4xjIFJwrgu52DoVjKdY4HBEX8dSF3JLYe1fe6UcYCii3xWQjdfuSTnAtoheKCC7GNED5Zx4L4qt61jbTLHA94geKSC7P7ZeShQ0Inoi1IJuEOeORooFXkV0FZNdZs5qvFfKAeqYy7nZ6yg//HG0MBfffh71lFrQDCW2EvEP4mt4okZUDftz9rmGZkotmMxJRtlisy+MTniAWrty3AlXw0hFM2TD89l+oNsoOJXjbIs4EpqNtTCLXbiZ0g+M4mFObj8U3vsNjoZCVcmk60ZwthpepLZkB/AsivWfOJZxtpUQHfWib7KWDwzjeegBZJSdKFiE2qJTFFTwElsi/unQ/awXrU4WGMD7nOJxBY/1EO2iYConq93CHT1GOwucjdqnRyFz+VcHmMNefMY9nNkA3SWUOoXhQviSWQ4huLIRFlirFixnQq/XaKXUgg2xQNGv4V7x/RcW+AXPB3h7H1PaiQAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-zoom-in{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgsUBmL8iQAAA2JJREFUWMO9l12IlFUYx3//MzPrLpSjkm5oN4FFIWVEl66IQlFYwtLOzozsjHdGRSCRF0sfBEXRVV0FQuQiLm5CZNBFgRRaRLVFhbJ2EdiN5gbK7toObTPn6eYdPTvNzPvOBz5Xh/ec5/n/n89zXtEHmZqeSXSuXBz/3zfdKvBWJHQrwZuRcP0El+QkbQXeBX6WZEgm6TtJk5lM5o4Lc+cV6qpf4Ga20Tm338zeATItVK9Ker6yvPzp4NDQ3+XieGsCU9MzTYumGbhz7m4ze9/MHgvBgItACrgfGAj2jgAvAYs3wlEujjc13kii8YyZrXXOfWhmo9GnFUlvOOemarVapVqtkslksmb2KjARqL62ecuWN9NxbRInzrldAXhV0uFSIfdew7G/gNLU9MwS8CwSmE3Oz88fcXG5blfpqVRq0Ix8VIAAX0XgrVL7HDCHGcCaWrV60LUBN8Dae58aQIxEqcA592I9M610JL0cpG/U9TIHJNKY3RV5z0R+7Nd4HZ0P1g/2RMBuegLAsRMnb4vT8d5vqKfMzOgtAlADrkmqGywmiMBTwfr3dC9j1Xv/r6Tvg/5/5ejxE6cO7M9faVbQZrYNOFSPmqQvVo9FKexvi5uWX58943aM7DwAfBDY+FbSCxP5sdkGx55GeguzrUEXPaSo2pFkAbiSZQCAzZJOmdkjwd6SpB/M7KykQTPbA2wDhoIzRzcNDx9MJwGNIXdJ0mEzmwbujL7dbma7gd03A7lKfnTOvf74nl0r6bonTUbujRSUCrm2d4L3/kvn3JPe+8+BDW2i9o+kT7z3kxP5sYsA6W47oE64TsR7P9tQL4vA2mh9WdIscKxUyJ0M7aR7acOGzikD65EQLEjaa2ZXzMwDFeB6qZBbbLTRE4EGeSaozNOZgYFf8qP7lmIvs354n0qlHpB0T7B9Ogl4IgJJrmjv/SiQjbrkD+BMUkfSbYATPdckrTOzkciWAXOlQu5cYgLdPEIapud9wMOR9zVJH3ViKx333mtHMJvNuoWFhZ3A+ojMcja77njXBEKwJJfTcqUyCIQ34Mf7nnh0paMnXacFuGoC1mr3AtuDfLzd8Zuyl+rfuGn4HLAD+Az4qZQf+61TAj0Noj8vX6oC35SL43u7teG6rf5+iXppwW7/JUL5D03qaFRvvUe+AAAAAElFTkSuQmCC\");}.bk-root .bk-tool-icon-zoom-out{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgsHgty9VwAAA0FJREFUWMO9l09oXFUUxn/fmXlpItppi22k7UJBRSlVkCytSAuKUloIdjKT0El3FXVXdVFKRVAQV7qQohsNwdA0UFvBhYtqUVyIVlRaogtFQVq7qSTVjA3z3nHzBq/jvPmTN/Ss7rv3nvN99/y794kByMzcfE/7picn/jenmwWeRUI3E7wdCRskuCSTdDfwBvCtJEdySV9KOhpF0e0/LF5SqKtBgbv7ZjObcvfXgShD9Zqk5+orKx8Oj4z8NT05kU1gZm6+bdK0Azezu9z9hLs/HoIBvwAF4H5gKFh7B3gBWFY3460kWve4+3oze9fdx9OpVUmvmNlMHMf1RqNBFEUldz8OHAxUX9q6bduryut+Sfvc/Wz62ZD0fK1afjND9y3gGSRwv1GMojstTxUUCoVhdyopEYDzKXjWwZ4FFnEHWBc3Goet00m7lZlZYQixKw0FZnakGZksHUnHgvCN5/KARBH37enpOVg58H13HV0Kxg/kIuD/ngSA2ZMLt3bTSZJkUzNk7k4+D0AM/CGpaXCyBw/sC8Y/qZd2GpZiuL9YLN4Sx/HpoP5/c/exQ1OVq+1yyt13SLoArEsJnMjlgfOffvK3u58Kprab2QezJxfG2iTzUzI70wRPG9jbmpmb95SNB9mpzp7/j2yVdNbdx4K565K+cvfPJQ27+x5gBzAS7Hlvy+jo4WIvoC3kWpcvS3rR3eeAO9K529x9N7C7zX6AC2b28hN7Hl1Vt44niVq13LUjmtlYkiQfA5s6eO+GpDNJkhw9NFX5ueNt2ARodyF1IHIN2JiOl4H16fiKpK+B2Vq1vBAqFAf4IJkGNiIhWJK0192vunsC1IE/a9XycquNXARa5OnApeeioaHvKuP7r3dTGsiLqFAo7JR0T7B8rhfwXARa2us4UEqr5Ffgs151i/08oTNKdIO770ptObBYq5Yv5ibQq/sl3Qc8lJ4+lnSqH1vFfp9koZRKJVtaWnqkWXqSVkqlDe+vmUDWpZMlK/X6MBDegKf3P/nYaj8ErN9fqZBYEsf3Ag8G8Xit33BaniTcvGX0IvAw8BHwTa1y4Md+CeRqRL9fudwAvpienNi7Vhu21uwflOT+L+i1X2TJP57iUvUFtHWsAAAAAElFTkSuQmCC\");}.bk-root .bk-tool-icon-help{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABltpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIgogICAgICAgICAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgICAgICAgICAgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiCiAgICAgICAgICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgICAgICAgICAgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIj4KICAgICAgICAgPHRpZmY6UmVzb2x1dGlvblVuaXQ+MjwvdGlmZjpSZXNvbHV0aW9uVW5pdD4KICAgICAgICAgPHRpZmY6Q29tcHJlc3Npb24+NTwvdGlmZjpDb21wcmVzc2lvbj4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+NzI8L3RpZmY6WFJlc29sdXRpb24+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgICAgIDx0aWZmOllSZXNvbHV0aW9uPjcyPC90aWZmOllSZXNvbHV0aW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MzI8L2V4aWY6UGl4ZWxZRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFhEaW1lbnNpb24+MzI8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjE8L2V4aWY6Q29sb3JTcGFjZT4KICAgICAgICAgPHhtcE1NOkluc3RhbmNlSUQ+eG1wLmlpZDpBODVDNDBDMzIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRTwveG1wTU06SW5zdGFuY2VJRD4KICAgICAgICAgPHhtcE1NOkRvY3VtZW50SUQ+eG1wLmRpZDpBODVDNDBDNDIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRTwveG1wTU06RG9jdW1lbnRJRD4KICAgICAgICAgPHhtcE1NOkRlcml2ZWRGcm9tIHJkZjpwYXJzZVR5cGU9IlJlc291cmNlIj4KICAgICAgICAgICAgPHN0UmVmOmluc3RhbmNlSUQ+eG1wLmlpZDpBODVDNDBDMTIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRTwvc3RSZWY6aW5zdGFuY2VJRD4KICAgICAgICAgICAgPHN0UmVmOmRvY3VtZW50SUQ+eG1wLmRpZDpBODVDNDBDMjIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRTwvc3RSZWY6ZG9jdW1lbnRJRD4KICAgICAgICAgPC94bXBNTTpEZXJpdmVkRnJvbT4KICAgICAgICAgPGRjOnN1YmplY3Q+CiAgICAgICAgICAgIDxyZGY6U2VxLz4KICAgICAgICAgPC9kYzpzdWJqZWN0PgogICAgICAgICA8eG1wOk1vZGlmeURhdGU+MjAxNjoxMToyOCAxMToxMTo4MjwveG1wOk1vZGlmeURhdGU+CiAgICAgICAgIDx4bXA6Q3JlYXRvclRvb2w+UGl4ZWxtYXRvciAzLjY8L3htcDpDcmVhdG9yVG9vbD4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cphjt2AAAAT7SURBVFgJxRdbaFxFdGb2bhui227BWrsVKYgf2kJUbP9EUPuzEB803WTXJjH61Q/7Ya1+CMYKEVTsh4J/EpvY7BoabUiNiA8s1p+4KIhpoUUEselHqyS76TbZ3HuP58ydc3d2u4+IkQxczpz3mZkzZ86VYpXjvenpjZsLhUcliE4AuUuASAgptmt1EFdwPiclzIIUUwubNn17OJlcXo1p2UpodHRiux9xB1Eug1+slbzhFxGOKc851tu7/0oznYYBDA8Pt0U2tL8KQryIq2tvZqQhD0QJHRz3yqWhgYGBpXpydQMwqz6NCnurleCSADkJEfgKfOePqL80R/wV1ZaQyr1LenKfkPCkEPKeaj0xg7vxVL3duCmA0Vyuw/fl52hgBxsBED+h4Cv9z3R/zbRm8MTJTx7HQN7GQB6w5C4L4SX7M5lfLBpurjXMyvNIShiyi0l1pL8n9b7EDGPR8fHxzSsQ6XDB3618/xqo6Pk25V5MpVJllgHM1BO58RdQ612kOYZ+GXdij70TYQB05mpj+1kU5G2fB+l3PZtOf8NGx6ambnMXb3yAxg8wjSEG6OKKR9oicBQD+ZvpH2Wzj0lQpxCPG9qMv1x6hHNCsSAlHM7ZOa682vlI9tRDbvHGbD3nZAPpDoD/3JIrLpAs26UFkC3EMUA99hpfGtEBfJjNJnS2Gwnadnvl+Xw+iuc3DAJuNyIaSCHpilVldyDjjUxj3WDZIAhxhHHyRcdNuA7AAfUaXzVKODpzFiZ4/uLvh5G+m2no+C/pyIf7MqlEJB7bpqR6nXkEUfbeawuLaZsW2ISfNQ2vtaktQlGFQyIVGT0o2+2EC4iQNGwjBIN9qdQ5Qg4mk4X4rW3vCClLtowE2FOFUxKDfNmiZci3ovKKRFPh4FK9q4Zbdr+lKKJiA13TcHR2dmLBgdmQ0GAS2MZaEowY+XbAk09IvgtYZGp16SyvFhaHcIUh645t8T9DBCcnz5zZ4hZLu3DzK2QlL1QQa0Y+pHiJKPSuOGj3PmZTheM5w2TwqBxnvBZOTk7G5gvXJ5Aelms8wnJURL+olSWcfEhf6gDoUXPMq6ZlqbzWU2pE+3hi4s6F68tfIj9cBMlikr7Z0/P0b/X0yIcUXsDCF1WhtL4OROHaXk+xlkbV0Cu732Nmhc4peaWSg73pA8dq5RkvO37ldUTfXCKZv2q45MkhvG87WQEzpCCUSvV1d9GONBy3lMvgKSwrZig8gjAietWY0QriylO2jIo4yVbOSb7KB/qmI9BPKjHpSSXYauRyn92Nq9/Kcrj13x3s3v8D481glQ/0raiNYgX9njPSBOImbrHZePl+tfFmc9sH+Xaoh8NjOKSVdDMhjjYzQLy+dFceH5+IJQf9VYXX4tROg4ZFU8m31M3mfPEqUoJqCGJfvWpo2xnNfdrhC28n06SCeSzNZxlvBINGRXCtKS7EY1uV6V7HWAm38y1cXaXsMcOCvr9ySPj+af7A1U2HJXHzVNvUXVLIGyPf+jV0pf8GHoN+TLAyPkidTCi2RpPApmnR0Bd1zGRaB/B8Oj2HSw7LLbVR1MmskW8RdEWVXSJf3JbpAMgRtc4IZoxTh9qotQjCasm46M0YX9pV1VmbpvRH5OwwgdRtSg2vKaAz/1dNKVtb17Y8DCL4HVufHxMOYl1/zTgIgiYvBnFKfaNp3YjTdPz3n9Na8//X7/k/O1tdwopcZlcAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-hover{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4oVHp0SwAAAQJJREFUWMPtlsENgzAMRb8RQ5VJItFDOgaZAMaAA0iZpN3KPZSoEEHSQBCViI/G8pfNt/KAFFcPshPdoAGgZkYVVYjQAFCyFLN8tlAbXRwAxp61nc9XCkGERpZCxRDvBl0zoxp7K98GAACxxH29srNNmPsK2l7zHoHHXZDr+/9vwDfB3kgeSB5IHkgeOH0DmesJjSXi6pUvkYt5u9teVy6aWREDM0D0BRvmGRV5N6DsQkMzI64FidtI5t3AOKWaFhuioY8dlYf9TO1PREUh/9HVeAqzIThHgWZ6MuNmC1jiL1mK4pAzlKUojEmNsxcmL0J60tazWjLZFpClPbd9BMJfL95145YajN5RHQAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-crosshair{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADEUlEQVRYR81XXVIaQRCeHqug8CXmBNETaE4gniDwIgpVspxAbxC9ATkBkCpQ8gKeQDiB5AQxNyAvUlrldr7eHxyGXZi1rMJ5opbp7m++7un+htSGF204vsoMoNXrlzSpfWa1oxQfhAegCZGaEtPorHo8znIoJwCt6+td8uk7ApUQCIHTF4BNAWzImq8ap6cP68CsBdDp9i9ZqXM7ML79g/EnCWD+jgMKENKqWT+tXK0CkQqgNRjs0OxpQIqKhoMxaG6/6JeRnK7T6yO2UvVqhYSlLX+ryORfgKn9ORDFIy7ky41yGcwsr0QAQfDH5zucOswx819fs4egI9OFCcD8DjBF7VNbEX0JzdWEt3NHSSASAcCxBDqMgt/623kvyTgNgNjJIfTjk4D4FqaJR1715MjmYAmA5Bx3AwUXQL+t105KaTlcBSC26XRvhjEIoLiq1yqXpr8FAGG16/ug4IT27fxBWu7EiQuAiImJpEMKE6nYM30uAIDDttSUOPfJP7JzbjPhAiBIh9QE67vIvoOi9WJfCwDavf40ulpjbCqmUf+W753ezURuh7Dg1SqflwAEHU6pgfyBq9Y4qx0LG++2fnZ/eUzcstmdM2AWH+jfc+liWdBJfSENf8Lifi3GVwC9mybOfi5dzatWVrbbLIHNva8p5h/16gkaFiLGGxbufkoE6XguwePiXLF3XmMfCUCUAqtKXU7sumd1CowOuJEi3Pg1FBpjitIGhyvVSfvmjci6ZR+rFQfDiPVE2jFYeICQ+PoewwjC5h7CZld6DBdyu6nDSKgzOyIMhmhK5TTqXYbRorZYM46TmpKAAOrGWwSJJekSB1yqJNOzp1Gs7YJ0EDeySDIMtJbQHh6Kf/uFfNFZkolJICRmz0P8DKWZuIG2g1hpok+Mk0Qphs0h9lzMtWRoNvYLuVImUWrmPJDlBKeRBDfATGOpHkhw670QSHWGLLckmF1PTsMlYqMJpyUbiO0weiMMceqLVTcotnMCYAYJJbcuQrVgZFP0NOOJYpr62pf3AmrHfWUG4O7abefGAfwH7EXSMJafOlYAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-lasso-select{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgwlGP1qdAAABMBJREFUWMO9V1uIVVUY/r61z57ZMx4DnbzgkbQXL5iCJphlWdpIGY4jpFBkEiU9ZNaDRRcITcIwMwgxoQtU2IMXdAZfMjFvpERXYiSbysyBEXFmyuHMnLP32uvrwT2xnY5nxvHQ93Jg7fWv71/r//7L4a59TRgqJk+Z6v3a+sv0OI5nk5wu6VaSVZImAThHsgjgrKTvM5nMUWvtmf5n8HodCIKgOgzDhc65pSTrJQWDsSNpJX1ljHnDOfdT37oZLLHv+8OMMasKhcIJ59xHAJYMlhwAJGUAzJfUTHLFuFzOG5QDU6dNMyQfs9Yedc5tBpAD4IYYNQGoBrDtQnt7/b0LFrJsCHzfn2itfQfAnZLiazytA3AaQAuAiwDaEgeNpGkkswAWSBqRONB38b88z5uTKePt6iiKXkk8jq+iJC5LOmiMaTLGHLPWhmWeHr7vV0dRtATAapAzIVmSo51zyzIlbm2stesFPA6pKk0r6Ryg93y/ek8YFvPOOTg3cDSiKCoC2OP7/rEoirYm4rUkF12lAWNM1lr7lqQn0+QA8gI2jBg5cj6Aj8OwmB+KAKIoukhyp6SRJAUgl0ndPLDWPi9pJQCbuviXvu+/GIZhW1dnJ24UJFuTjCCA2ADA8sYGWmsXS3qmL94kDYAtkh4Nw7ANlQJ5U6INT1KrAYC9zQdykl7nFSj5fXp5Y8NWVBhy7mUAjqShMYdMXV2dJ2klyRwAJ8lIeuGWCRMP7N7frEqSG2OmAFhKshNAp5wrmO7u7jEAngPQm1S2z2pqapr+OPt7XEly0oxwzq2RdFmSD2AMgKKJouhhAL4kA+Cs53l7e3t7uytJHgRBreTWkXwkKVJnJD0B4GAGwIJE9R6AFufc6UqSZ7PZbD6ff5dkA4CQZEHSqwAOISmXtwGIE+F1SeqqIP8d+Xz+C0mLJYWSAODteXffczjdDQNJ0BWMCoLg5gqIbRTJNwHsljQhUb0luWPM2LE7Thw/9m/5NCT/TByxAOYWi8X6/gdWV1dnfN8fNRBxJpMZTXKdc+6IpFVJWAEgkvSJpA0X2tvtVTaSjgOYBCAEEADYSHK87/sfhmEYA9gShuEDkgzJHyWtB/B1irQ2juP7ADxkrX0wOUOpzmdpzEY590HJ7Ni1r2kSyZOSiv2+hSRjSTXp/QAukzySNJOJkmalyNIl10hqMcasdc61XDNcQRD8BnITgNp+36r6kfcNFMMlLQGwTNLMEuQGQBfJl2bdPru+HDkAZAqFQux53jZHEsC6aw0eg2gylNRBcqcx5v04ji999+03AwsWAOI4Lsy9a94WkisAnE5a5WCJYwCfA1g7LJudI2lTHMeXBm1faiQzxkyRtF3S5CTupeAB+KG2tnZFT0/P30NO2VKLzrmfAbwGMipjG5Oc0dPTc0Md05SZ5U4Q2FxChErtEYD7jTGNQ3UgM8Asv90Yc9I5LSKRlXSI5CxJa0jWSALJjKRnAewfkniT+vwf7N7fXHK9rq7O7+jo+BTA/NRrdBpjnnLOnUrvXd7YMPQXSBunneno6IhIHgYwW1JtkgmBpBkATlVMAwOk3nFJ+VSoqgCMr6gIy2FcLtdKspAedyQN/98caDt/3kpyabUmf8WvG/8A1vODTBVE/0MAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-pan{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4lKssI9gAAAOtJREFUWMPVll0KwyAMgNPgoc0JzDX2Mtgp3csKErSamGabIEUo/T6bHz0ezxdsjPJ5kvUDaROem7VJAp3gufkbtwtI+JYEOsHNEugIN0mgM1wtsVoF1MnyKtZHZBW4DVxoMh6jaAW0MTfnBAbALyUwCD6UwEB4VyJN4FXx4aqUAACgFLjzrsRP9AECAP4Cm88QtJeJrGivdeNdPpko+j1H7XzUB+6WYHmo4eDk4wj41XFMEfBZGXpK0F/eB+QhVcXslVo7i6eANjF5NYSojCN7wi05MJNgbfKiMaPZA75TBVKCrWWbnGrb3DPePZ9Bcbe/QecAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-xpan{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4X4hxZdgAAAMpJREFUWMPtlsEKwjAMhr/pwOOedINJe/PobWXCfAIvgo/nA4heOiilZQqN2yE5lpD/I38SWt3uD9aMHSuHAiiAAmwaYCqoM/0KMABtQYDW11wEaHyiEei28bWb8LGOkk5C4iEEgE11YBQWDyHGuAMD0CeS30IQPfACbC3o+Vd2bOIOWMCtoO1mC+ap3CfmoCokFs/SZd6E0ILjnzrhvFbyEJ2FIZzXyB6iZ3AkjITn8WOdSbbAoaD4NSW+tIZdQYBOPyQKoAAKkIsPv0se4A/1UC0AAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-ypan{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4anK0lywAAAMVJREFUWMPtlzEKwzAMRX/S7rlpIMXeOnaLaME36FLo8XqCdNFghGljyc4kgQi2Q/SUj0F/eL7eMMTKz6j9wNlYPGRrFcSoLH4XxQPvdQeYuPOlcLbw2dRTgqvoXEaolWM0aP4LYm0NkHYWzyFSSwlmzjw2sR6OvAXNwgEcwAEcwAEcwAEcoGYk20SiMCHlmVoCzACoojEqjHBmCeJOCOo1lgPA7Q8E8TvdjMmHuzsV3NFD4w+1t+Ai/gTx3qHuOFqdMQB8ASMwJX0IEHOeAAAAAElFTkSuQmCC\");}.bk-root .bk-tool-icon-range{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABCJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIgogICAgICAgICAgICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgICAgICAgICAgIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyI+CiAgICAgICAgIDx0aWZmOlJlc29sdXRpb25Vbml0PjI8L3RpZmY6UmVzb2x1dGlvblVuaXQ+CiAgICAgICAgIDx0aWZmOkNvbXByZXNzaW9uPjU8L3RpZmY6Q29tcHJlc3Npb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjcyPC90aWZmOlhSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICAgICA8dGlmZjpZUmVzb2x1dGlvbj43MjwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxYRGltZW5zaW9uPjMyPC9leGlmOlBpeGVsWERpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6Q29sb3JTcGFjZT4xPC9leGlmOkNvbG9yU3BhY2U+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4zMjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxkYzpzdWJqZWN0PgogICAgICAgICAgICA8cmRmOkJhZy8+CiAgICAgICAgIDwvZGM6c3ViamVjdD4KICAgICAgICAgPHhtcDpNb2RpZnlEYXRlPjIwMTgtMDQtMjhUMTQ6MDQ6NDk8L3htcDpNb2RpZnlEYXRlPgogICAgICAgICA8eG1wOkNyZWF0b3JUb29sPlBpeGVsbWF0b3IgMy43PC94bXA6Q3JlYXRvclRvb2w+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgrsrWBhAAAD60lEQVRYCcVWv2scRxSemZ097SHbSeWkcYwwclDhzr1Q5T6QE1LghP6BGNIYJGRWNlaZItiFK1mr+JAu4HQu0kjpU8sgF3ITAsaFg0hOvt2Zyfvmdsa7a610Unx44Zgf773vvfneezPHNzrbhn3CT3xC3wPXYOC8LDzqdi8YY/gwh4BeknS/2th6dr2kf94AOp3OFyWgMyziOPbMDxV9FTtJnl1ut795Xd0/YQ0/vtYQwMT1KXWCfr2IjOWwtNehwN4xL9ykTrm6Pzl58yLn3J+mKh9mXbT3uRjGEDph+O8/TjfP5dBp7Ha7AX7O3o5nZeD/0E/OGyXntDgzA0X6qmCnrVutVlrUWV9f/3xo+pwhGDhvEPHOjoxnZjJggXmMHzBQ7NGNp9vxk61fr0HR7e/u7pZzCGHlc7qwBYYTT7tJYSx1AQzppyFPft5apta9w7SKcn0b7P7+/jCsDQ5mbc0dCmIJGDN0ehdcjsmkm6A6KUeKFOTE11PLxrC7Ukqh3ylL2fT0NAP9q6ur6rRCJJYsbKB0JsbCKMuy+xREePDyxQPCz+Crlw062QcA5wBOOt1l6vIl2WiI9F1fN6Q+BBqit6hEC4Hk08GQJMn4myjSP7RavVxgdaVUh/3U6HCMsPr9pYnJKRziHtWQ+un58+hGs6nsjQSjpuTyKGN3CX+FBwHXSiEVgjP+O8X6N12kIePES+GzTKAkGbNp8yJsGUMVzz8jPKReiyAQRimy5/cjye5RpF8utFp/+nwmT7d/NMzcFkS7yjJNGDaPURQxIQThEQy0SyF4l5WJYYhBa816vZ6dU7A6CAhbZVow/pDe0O9hVOoCi13r4BgBAvJHqMSQL2vE/iH6IAXEwgrRVUmBoRRwnwJQT98xEeVeSUyB4dJ5nwJBKdCFFGRmUCcu7rwIYypCTblaChuNBhWODrman5ub+4v0rMNBt8z6Ezh7GksJQpCbm79cMQE7QBFm/X6f0rjWnv8WRYg/QdbUpwDAEBy8vPyA8rNGzg3a8MiElwiM7dAtRqNoNptjGPM1laVxP9umWEMGLOKhKUOJDtBwDmzsw9fC/CzHr9SGuCTi2LbbKvVtmqXpCjMihBFa79Wrt5fGx9PDzc3fmu32Lf8qFliwU9emKhBSp+kRKn/hu9k1COEDbFdt/BoKWOAkuEbdVYyoIXv8+I/QK9dMHEb1Knb7MHOv8LFFOsjzCVHWOD7Ltn+MXCRF4729vWMDK+p8rLkvwjLg4N4v741m5YuwCI9CvHp1Ha8gFdBoPnQAkGsYYGxxcfEI7QQlFCTGUXwjAz4tWF+EpymOWu7fglE7qsOvrYE6g4+9/x/vhRbMdLOCFgAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-polygon-select{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEjc1OfiVKAAAAe1JREFUWMPt1r9rU1EUB/DPK0XbqphFHETo4OCiFhwF0V1KHbRSROLqon+AUMVRRFBwEbRFMBiV+mMW/wIxi5OD1kERRVKRJHUwLvfBTZrU5OWBGXLgQu7Jfe98z/ec7z0vKa88b2q1BDtRHdAPBaylm1NzsxsOjPnPNt6WSWprbft+/c3I3zOAjhT1Y4+fvcjEQJIXnVECSa+AhqIHqlHH5lWCZoe+Gk4GRgDG86j9SAUdlDBSQaZhlOkuHyoVdJmsw98D1S5fM4NYM1LCpqM+Lwa240oLgmZzpVZvzKT75VLZcqksSZKWlQeAy/iORVwIvh31xvotvK7VG3Px4aWHj3Jl4C2uYSvq+Bn8v6LLbaVWb9zsBiKLCvbiNG7gLm7jAYqbPHMJMziZ9lsKoh8GtqCEVVzHftwJn+TFHp4/hg8BSCYVfMOZoPEv2NZGdy9WCGUr9toDR3E2/H4V6nwRe/BmgN65H1ZhvMuB3XiKIyFoGefwO6ysVkUlrNUNsyAK/jli533Q+Y8cJFvAeXyMS1CI/jiMr/gUtD2LQwMGr4R3p7bY3oQHQ5b38CT4D2AXXg6YcQXHpyYnlqKsi5iOAVSwL9zd7zJ09r+Cpwq72omFMazjT9Dnibym0dTkRDUKrrgwH7MwXVyYB38BstaGDfLUTsgAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-redo{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4itK+dVQAAAaFJREFUWMPt1L1rFFEUBfDfJDaBBSslIFjbaSFp1FJQFMVCHkzhKIqdUYOCoBgErVz8rCwiTDMwBCIKipDWyip/gxAIWAmBgBC0eYFh2Gx2l9lFcA5M8e59782Zc84dWrT435Hs1siLchqn43MS0zgW22vYxjesYjVLw3YjBPKinMUTBOwf8J5fKLGYpWFjJAJ5Uc7gIW6jM6Kim3iNZ1katgYmEL/6I+YasvY7Lg6iRpIX5VF8wuEe/XV8wGf8jN6LWTiAc7iEQ7ucPZ+lYW0vAtfwvlbfwCKW9gpXDOv1mJvZHiSO91MiyYsyiQSuxtpXXM7SsDmM5nlRdrCMMz3sOJWl4Xevc/vwBzdwAl+yNNwZxfRI+GxelK9ikHcwh8d4NNR/YFRES1ZwoTYdR7I0rNf3TzVNIGbmSvR/Bx08mIgCFSVu4l2ltIWD9WxNGR+W8KOynqnZ0rwCeVG+wa0hjrxtWoF5dAfc28V8Mib/n+Nev5dnabg/zgw87aNEN/bHOwVRiRe4Wym9zNKwMKkpgIWKEt24njxiJlq0aPFv4i9ZWXMSPPhE/QAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-reset{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4gWqH8eQAABLdJREFUWMPtlktsVGUUx3/nfvfOlLQaY2IiRRMQIRpI0PjamJhoVASDvNpCpYw1vJQYSVwZwIVQF6wwRHmkAUof9ElrI6VqDAXcID4TF0IiYQMkSlTokNCZ+b7jove2t+NMH7rQBWd3v+989/zP+Z8X3Jb/WGQySvUNTQBJESkNguAVYIWqzhaRhwBU9WcR+QXoymazn6jqzUQiMQSQzWZRVdal1vwzAI2tHQBPOuc2AbWTdOyQ53n7nHNfRwee51GzqoIQMCLDpr3x/tLQ0oZzrk5Vj0/BOEBt+KYuOlBVGlrahr0Wob27t3gEjnZ2AyQzmUwHsDgP6J/AYRE553neDwDOuUdU9QngNeCumK4TkRMhZUORcYC1qysLA6iuSQHIwkWLD6lqapQsuSmwTVV3h99I7EcAR462A2xR2Ilq6ehTaejvO1774kuLNALR33eclsaGsQDe3fYegHl43vyNwEeqGl1963mm2jl7YZRTQ82qlWP4HM6ZToC5ztkW4LHQoALru7s6Di5dvlIj/e6ujrEAWoZDn8hmMjXATMACGaAVuBjXTVVXFc/AxhaA+4zvn1DV+eHxVWPMAmvtb5GeMWZyZVhI2rt7qVy2pOh9U1snwIPW2vMi4oWJuBPYHkVAVScPoKmtkzVVK6cEMsyJraHhiCqJqJUwj/JRz7TW1iSSyR2rVyylqa0Ta+24Ic8vXaAEmDFc/l5Z2A/80OibuVyuz/f9ElUdHCmvw82t5HK5h6y1PYhsz2YyGw43t2KtBZHIGwB6+j4rCkBVUdV7gXrggnPuu8h4eP+xMeZS2D0rJYZ6AdAMzAt1b4nI26p6IFZOY8pugijcKSIHVLUK0LyST4vnrVfnWr3mjmP4QTATaERkXkypRFX3isjmuHdRJEK6Ckqquopp06bdKCkp2Sgi7XnGLcg7gzeutwNIiPYc8HixqIrIOlU9ONVIhHPEd851icgSVXUiskVV94gIqoonIt0i8gfQCfwae38e6BWRXuBZz5jZ8VbaOE4EIqlZVUEQBLlkMplS1QER2RwkEnsSyaREDUzyeNsvIhvCMqkH1kdIJ2o+k8iJB1LVVRfjZ6nqqlEAIbdVQGto8Lrv+/dbawcjAL7vc+6bs+zetetfLSHxniIFGofGGsU2oC7eOCbDfZ7nQawBOSAX74SF9oEPImOq+r7nmVmxb5raukZa8UReGmNmhbMkAwwBH467EYVZe49z7kdgenj8k7V2oTHm8kgdWcvrNdVFjR8cHkYzjDH9wLjDaEwEzpwa4MypgWvAjtjxfGNMj4jMiT+M+kFsZI/Q6Pv+HGNMT8w4wI7TAyevxXVPD5z8+zD64tRXAMHVK1eaVLUyVvuDqroV2BOnJF4ZIedviUidqt4Re9s+vbx8zZXLl7PR2+nl5Tz/zNOFp2FzxzGAklw22wUsLLaSKXwf8vhosZUM6PeDYEUum70VHfpBwKsVyyfeikOP6oBNwN1TrLbfgX3A1kKLzKeff8nLLzw38T5wZDgxn1LnNk5lLRfP26/OnR2hwfNYW2Atn9RCsrf+EECyrKysDFimqhXhyjY3VLkAXBKRDqA7nU6nS0tLhyIj6XSaN9bVclv+l/IXAmkwvZc+jNUAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-save{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4UexUIzAAAAIRJREFUWMNjXLhs5X+GAQRMDAMMWJDYjGhyf7CoIQf8x2H+f0KGM9M7BBio5FNcITo408CoA0YdQM1cwEhtB/ylgqMkCJmFLwrOQguj/xTg50hmkeyARAYGhlNUCIXjDAwM0eREwTUGBgbz0Ww46oBRB4w6YNQBow4YdcCIahP+H5EhAAAH2R8hH3Rg0QAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-tap-select{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3NzIwRUFGMDYyMjE2ODExOTdBNUNBNjVEQTY5OTRDRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpCOTJBQzE0RDQ0RDUxMUU0QTE0ODk2NTE1M0M0MkZENCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpCOTJBQzE0QzQ0RDUxMUU0QTE0ODk2NTE1M0M0MkZENCIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1LjEgTWFjaW50b3NoIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6OTQ0QzIwMUM1RjIxNjgxMUE3QkFFMzhGRjc2NTI3MjgiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NzcyMEVBRjA2MjIxNjgxMTk3QTVDQTY1REE2OTk0Q0UiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6eYZ88AAADLklEQVR42rSXf2TUYRzHv7tuGcfE6Vwb5zLSSjEj7Y9KWqfEmFZJP+yPMdKKmUrrn0iUfjhWlLFi6YfNrF+StBoTo39iYkTGco4xxxG59P7k/T2PT8/37nu3bx9ezvPj+zyf5/PreS78bGLS8SmrwE6yje3NHJsDBTALpknBz6JhH3NiYAB0gHqPOVv52wJ6QQ48BzdAttTioRJjdeA8mAHHS2xuk3p+M8M16ipVQE49Ds6CiFO9RLjGONf05QLx6wPQaBlbBlPgJVgkP0ETiIJ2sB/E1XfimjfgBOOlKDUqCGOcqBcQnw6BYW5YTo4wbvQhMmCfGRemC2rBiGXzWUb+kM/NRZ6CHWBM9ce5R61NgX6ayhSJ5EPlItlDRNkz4JbFHf06BkSzHjXxM+gDv1S/mPUo2AXWgt9UUHL/IVhS8yUV1/EbV3o4N+NaoE9Fu/i827K5pNYHnqAVJECShWmAaddpscYFFXwR7vnXBRGlnUN/L6kqKJlxnRUuDbaDBiL+vst5d4gpcpBrqk/2jIgCKVUolhntplzivHmwh4stGOPfwBWwl/2dpp8p7xjQZqFLiQJtauKkivYm+kzccpK57yXfOUe+P23JqAnVbhMFmlXntCWnxbT31am9ZJ4BJifsUmNTqt0cYhA5ypympPg7VkEKunPbVb8cIG+0kyHLJZNR7fUMooUKFHAPkfQo58VLK+RzwRDd4FdWG9mjpaAXzqkJa1R7kQttqEABWXMjOOxxVRfnhRm5URX1prk/0pQHwNcKlchZ+jdpC+hFdVqO0my9Hj5dkYgCn1Rfh/KdlNDHrJhPqlDih+IfBd6qwpOgEqYMsorJ2HtWxtagLJDn/W3KRfPOZhoeBJfZPgVeGKeKrkQBh5dLXl25Ny3pc4/1fkTdbvFqFQgbxWeYD0hXulhQ0pYiM1jG547fcbMQpVnHTZEn9W3ljsCzwHxCdVteNHIZvQa7/7cC7nV6zHIfyFP9EXjFa7YxKAVqPP4bxhhoLWW+z9JyCb6M/MREg59/RlmmXbmneIybB+YC/ay+yrffqEddDzwGvKxxDmzhc0tc80XVgblqFfgjwAAPubcGjAOl1wAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-undo{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4em8Dh0gAAAatJREFUWMPt1rFrFFEQBvDfGhACASshkL/ALpWVrSAKEQV5sIULWlgZNSgIFkGIVQ412gkBt1lYLERREFJqJRaW1oHAoZUQsDqwecWy7N3tbe6C4H2wxc682Zn3zTfvLXPM8b8j6RqYF+UCzsfnHBawGt3fMcAX7GEvS8NgKgXkRbmMxwg41TLsN0psZmnodyogL8pFPMIdLHUk7hA7eJKl4U/rAuKu3+HslFr/FZezNPSTFslX8QErDe4DvMVH/Iq9F7VwGpdwZUjsPtaSFjv/1vCBPjaxO0xcNbHejLpZrrlvJCMCT+JzA+2fcC1Lw+GE4l3CG1yIptfjCtiKoqtiJ0vD3aM0Py/K57iIMxgkQxat4EdN7e9xdRzlk+LEEPvDWvIDXJ928sYxjL36icWK+VaWhlezOIqbGFirJd/H7szugrwoX+D2BDEvszSsT5OBdfRaru/F9dPXQF6U27g/KnmWhgctxqyzBrZGMNGL/rHI0nDkKXiKexXTsywNGx0OnFbFNk3BRoWJXnw//j+ivCi32/S8CxPVNiWOAdUiJtXITIqYY45/Cn8B2D97FYW2H+IAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-wheel-pan{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgswOmEYWAAABddJREFUWMO9l09oXNcVxn/n3vc0fzRjj2RHyIZ6ERuy6CarxJtS0pQSCsXNpqGFWK5tTHAwyqIGN7VdEts1LV04BEoxdlJnUbfNogtDCYWQRZOSxtAUCoFiJY0pWJVUjeTKM9LMe+9+Xcyb8ZMychuofeHCffeee7/vnXvOuefYlV/+mv932//tb91z/Y2rvxmMHQ+4FcEfOIGN4A+UwDDwoQScc7vM7AIwB8yZ2QXn3K77Ab6OgJnVgeOSbkqaBiaACUnTkm4Cx3OZzwf+qzcRQup1zNZ9RwDe+0YI4YKZTUn6zCGSMLOfAF/03r+QZdnyfwO+ePEiI6N1nPMgMDMkETLRbd2mXG8gCbd9YiIKIUxLKoLfBN7I+80+CUlTIYTp7RMT0b3Af37p8kh5y9gZcy4Fzt+5szqSaxkzUR7dwtrKMmaGW242d0t6vrD/He/90865o865o977p4F3Ctp4frnZ3L0Z+OryUrVSrZ0z8ZxhHjhcq1XPrS43q/0flDlK9XpPA2ma7gMeyvfPx3H8TJZlH4YQWiGEVpZlH8Zx/Awwn8s8lKbpvmq1ahvB641SXNk6dhLskNA2MIBtwKHK1vGTW8bKMRbAMgyPqWeETxUM8VSSJAv52JmZA0iSZMHMThWwnipXKp8hsLLcSaIR92oU8xjSayCQXotiHotG3Ku3m+0EOQwPQCDggMf7BzQajSs5eAk4B5zLx4O1vD2eJMmAQKliscgASJMw21pansFs1swQ/DNLmUmTMNuXX+taXHTDaj5OW612R1JZ0nFJJ/J+XFJ5aWmpA6S5bHV8fHsPHFU6q3pJCjtFxtrKMuXRLUUXXxdrRLazFOtUolZlsGhmACsgnHPTwJnCnjP5HMBKLotzxsTE9rgDL0t6LoriKsDIaB31ZEK+JxQJRHFUBR2NqLw8OTkZR0OC0ntm9k1JWU7OA4vD/mZ+YfElsANmNEKi75vztzB5M8uAr+bx48me88g757PQ1U5zNg52YH7hX8l6f+4Fi3c3BqHNmkI4YQOV2MGCNu9qHPYCewfzbrC+XSGcWEcgTRKA3wFfyzdDz5d+D3x9CIcfA4eBbQS9LscskgfLnHNPAnslvS/pbZDHLLPADpx9N9fqpSIBH8cxWZY9m6bpb4Ev5fN/iKLo2TRNgdx/eo8Wk5O7Ts/N/SOSdMjHdj4kmgkIEJLJzPZKetvMTkIvFLsR25Ml2gfuF5M7vnA66sdooJYkCSGERe/9VAjhzRxoKk3Tvg3U8nulVqvx8cyNpER2umM+SdOkbc5B8JhpqBdIgTRR24h+lpKen731aRIN7thscH9Zlv0d2F8YD2TIX7F2uw3A7ZWV1a0TYz9ca8cJZHRbuRuaDfUCw9/qJHamPOKToAwHtHN6lMvlSkH2o7wDMDo6WuGuQbbn5+YAKNcb3J5fSvrhtTY+vsOPuD1IOyRhMOkj9kSx29HfXB5RUnS964NT2+3vbGbxG9auO2cDNuV6A8NTb5TitBuOpQkfYD2vwOxgmvBB2g3Hto5X42EJyVsFlztbKpXGNgqVSqUxSWcLU2+tdToa9hasLjfPYlwGa+bTi8Dl1dvNsyvNtQQL9MO2w+HM7BqwlAtPdrvdq9773WAVsIr3fne3270KTOYyS2Z2bbXdHhogKmPj7YWF+VOSXs/v/9KdO+0fVBrjbRkgB/KIDBnYu9f/7D+ZmfmRxPd6qwB8YmZXcq1MAQ/nJhTM+OnDe/a8+PGNG9lm19V/D1Qw7HXZlcRa69+U6w38l5/4ipxzf5X0CPBILjcGPJH34pVcc8692FxcXLlXRnTwwH7+9P4f8aWe3fY59LIqo1NMyQBCCHNmdgx4BegUWefjDvCKmR0LIcz9L8nokSNH+PRvH4HC3YQ098pSbevg24qlmZmNmtmjkg4D3+j/tZldkvQXSa3PW5ptlpL3ZaIN99OS9F7+IgKUgSyEkNyv2nHT7DZX0dr9rpjua2l2r4rogRAYVqZvnPsPqVnpEXjEaB4AAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-wheel-zoom{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgskILvMJQAABTtJREFUWMPdl1+MXVUVxn/fPvf2zrSFmUKnoBCUdjRoVaIxEpO2JhilMYBCtBQS2hejpg1Uo2NUrIFAoyGmtiE+GHwQGtvQJhqDmKYRBv+URFsFDNCSptH60DJTO3dKnX/33rM/H7rvsDu9M20fDMaVnGTvtb69z7fWXmvtc/TEzqd4OyXwNsv/FwFJQVI/sA14SZKRLOlPkr5TrVYXHz70quYkEEK4TtI2YAgYkrQthHDdhV5uuw+43/ZrwCbgRttgY/tjtrc0m83X3/f+D6ydnJhYcB4BSZcBA7aP2d4ELAGW2N5k+xgwkDB0IH19CGGH7R8B1aQeAf4KvAw0ku4K2zu7uru3ApdPEyiKohd4TNKjtjt5h6RHgccSNrddbvuHtm9Jqoak7xVF8WFgdavV+pSk5cCObNmXgK++85prCj3z28HKqZMnH7D9YAY4BvwujT8BvCuL1INX9vVt+dfwcCvNb7f9q2RuSfrGvWu/sL2Nf3LX7pzvj4ENSGBPVarVd4fRkZFltjdmoMGiKO4IIWwIIWwoiuIOYDDzeOPoyMiyFLkum7WJCMDztrcrTTrIRuAQZ6NcK1utL4dWq/VZoC8BhqvV6l1lWb4YYxyLMY6VZflitVq9CxhOmL60hhCKeYiV7WMKIXw9jT1HpXw3c+bOAKzOjJubzebJrKQCQLPZPClpc7bP6rMYKtjXth2OMf7tIkr11Wz8oQDc1Fb09vY+kQw1YAuwJY2nbUluAnCWpKkaFl6IQIzxivaR2SYA89sJVK/Xp2x32R6w/a30DNjuqtfrU0ArYecDCEqgLqm94T0dEm9mBG7PxkdDlkBnkhebgIezNQ8nHcCZPL9ijE1Jf/bZZoPtzbavmqNZLbf9tSxq+yoduuJ+SZ+zXSZyBXCqU+d8fvC5yRUrV+0G2j3g2hDCLyXd/+Su3QdnvP/zCuH72LWsgf2k0oHlH2c2odlkxcpVEdgr6aDtjyb8x20/J+mA7T9I6rL9SWA5dne2/GdXLl58qNJh398An85yTMA+4DOz8Dgu6Zu2dwJXJ91ltm8Gbp7Fgb+EEB4aHhpq5CEtACqVyr3AC0AlPS8k3TSmQ2YPhhBuS/1/LpmS9JTtNTHGfwBU2uUALARotVqniqJYH2Pck85pfavVaufAwnQvnHc0McaDKVptebN94QAnJB0EdtjekydyZXqjs/0ZgLIs/w6sy8bnYGYJ63pgERKC05JutT1kOwITwL9tvzlzUQUYB+Zjs2DBgu6xsbGJZHstByZbezregcBXeCsEz1bnzXt5anLyzLq71zDLxTRdVgemdx0fv2e2w5thO5DbiqL4oKT3ZKpnpyYnz+SY2ZpTAPZmJfdIrVZbNBNUq9UW2X4kU+2dcf53Aj1pj2PA7y/6m1DS00A9za9uNBq7iqJYBuoGdRdFsazRaOzKSqye1rTbaa/tlbYrqXQP2X4FIA9/J1l39xrC0v7+w5IeB8XkwS1lWe6TGJAYKMty31tfO4qSHl/a3384I3CDpI+kzC4lnRfrue6GytEjR8oQwlY73gC0L4qlth/q0M1/LYWtR48cKQF6enrC6dOnVwGLEpnxnp7en4+O1i/tszzGOCTpPmB7ahb57QUwBWyXdF+McWg6MScmuoA8OX8xOlpvXGz422XYTsB/SnpA0h7bX5R0WzI9HUL4qe2XbI+dk3xl+V7gxoztD5jRI+YK/zkEEokx2/uB/RdzIfUtueqVN04cXwF8G3iHY3z9Urw/j8ClyhsnjrcS2Vv/J/8NLxT+/zqBTkcxU/cfEkyEAu3kmjAAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-box-edit{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4QfHjM1QAAAGRJREFUWMNjXLhsJcNAAiaGAQYsDAwM/+lsJ+OgCwGsLqMB+D8o08CoA0YdMOqAUQewDFQdMBoFIyoN/B/U7YFRB7DQIc7xyo9GwbBMA4xDqhxgISH1klXbDYk0QOseEeOgDgEAIS0JQleje6IAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-freehand-draw{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADTElEQVRYCeWWTWwMYRjH/88721X1lZJIGxJxcEE4OOiBgzjXWh8TJKR76kWacOBGxdEJIdk4VChZI/phidRBHMRRIr7DSUiaSCRFRM3u88gz+o7Z6bBTdjmYZPf9eJ55fv/5zzvvDPC/H9QsA66Olo9Ga+/MdR+Ljm2/KQIULsz9FqItGdOfJKLhApLgVkiSCGODjWit7QpKWy+TNrFeXvzKVUT8NiTVaIgDcbiCFJ7GiT8WkARXAdYBK0Lbhi/CenArRNskuM7/tgNp4ArQ42dwjf3WY5gWTqC7O/NbNn2Xkfw/YwdSw/We14HP2IEZwX+y9cZ9SH0LmgFP7UCz4KkENBNeV0Cz4b8U8DfgKiDxMWwUXETqLvJpCQpXZfawbzS7t9v5pL19cHBwfja7YA0y/lyCM0+E5hv5+piZXwKYcF23as+37bTXsQVqgkL0p/34fHR7DcBtbetFsBmGDwMOJCggYG55yw7dMlk6DuC1Bdu2RsCU9TYWQq2IoGbsreZ5NzvEqfSBsIsIy8OTbcdgiRHeh4o8AFAEwDakbY2AaCCpH7V9aGhoUUUy3UyVbkPYFuYLDlUZH8XBpwxkK0Dbgxg5HcVi0ent7a0RULMIozaHBSMfF9b2SzdutFcFB2FkwMIJOG6qfteXOa1nHZ48tyefuwyfT9s6wtzZ3t7eZse2DR2I228TtHXzuWCx9g8MtK5cuHCZTH4tiHEOa4xFngvTyS8f35d6enomiCi4/foEXBkZaQuukChL4FYA2Whd7YcC4gEdW3CpdL3LtGAVCVYJywEyTpAuJKeMOKXZs/Bw947C50KhUFOG4cwz35cjWNBlHGeD53n3xsfHP/T19U1qciggar8Fa4I3PHobIotBWBtc2hSiChyZxVzM53Pv7FVH6Tp3uVy+g0r1ImD2GjIrQGYIxjnfuXTZGICS5k/bBwJoubwEFX4TLah9EXomJGMA3za+f9913Yl4TnzsDQ+vE6YTZOjHh4ngibstt1pzQwd04F0bPStEBpXqRoBeQ/AKghfBnOEKgS+Q7z91Xfdz/HGKg8Ox7z8iYD9z6wqTkZFgnvhMGP9VZ2or1XVkPM9z0mytSfVsHa1RLBZbLoyNzUnK+ydz3wC6I9x+lwbngwAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-poly-draw{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEjglo9eZgwAAAc5JREFUWMPt1zFrU1EUB/DfS4OmVTGDIChCP4BgnQXRxVHqIJUupp9AB8VBQcRBQUXIB9DWQoMRiXZzcnQSA34A7aAuHSJKkgo2LvfBrU3aJnlYkBy4vHcP557zP/9z3r33JdXa647N0kHSZd5Nn0rSxc8G3cXp85sMcnZZ8vge3osZ+l3vB8CWFA0iL14t79h210swAjACMAIwAjACkB90D/8/GchI9ve4nPwTBh5E9ws7OepzGWb9EddSn51Op9ZstadSg4VK1UKlKkmSDSMLALewiuNh/hVJq71Wxttmqz0dG88vPc+MgWP4grvYG3SLOBrZFFFrttqPe4HIDxh4GSei+98iSlusuYopXEAjBtEPA3tQwUpwluAbDm4TPJUz+BTW9l2Ce6G7L0X/Bw8D3T/7SKKIDzHg7QCcxjvcQAEtXAnrrg/RP0/DKPbqgcN4iVOR7gcO4dcQgRuoh7HSqwlP4n20m63jJu5n8MkWMYfP3UowhzdR8FU8w9iQwevBdyq3/27CMRzAE5yLuvsRLg+ZcR1nJ8YL81HWJUzGAPaFZwe/Q5MdyYDyNHgjzO90YyGHtVDncuiJchaHw8R4oREFV5qdiVmYLM3OgD9k5209/atmIAAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-point-draw{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEiERGWPELgAAA4RJREFUWMO1lr1uG1cQhb9ztdRSP7AF1QxgwKlcuZSqRC9gWUUUINWqTh5AnaFOnVPEteQmRuhCURqWsSqqc9IolREXdEvQBElxtdw7KURSFEVKu4w8wAKLxdw9Z+bMnRmZGXfZ29//II8th4WwGVNyIoQLYB5vxA9Caq04iUd9A+7ZlsNC2I7TdSd2hZXMJKlnTqp9jtl/GBaqoyQ0noFKpUIzBicYYc+DEFpxkglc4oVJa5gvDn8v1xV2irG3FM4NSVwjUKlUaMcpJhCGmSEJQ6QGD8M5WnHCd8+f3QCXpPLx8WNwv0j6Bm9FMK7FJ3WBE+R/2t7c/GBmFvSBrzRTCsyTDjXrxUgEMtpxynJYmJoBJ4VAybwVARgvL7Oik0okCodnKpVKX7P0leiVMb0VvbJT+upznK4vh0GIeQwwQStJkHQD3MwsCALTJRG7Qrdrj5m/djgYaIa0hlkRdJk26XEgC9txurccBtVW3IudBImmZuACUP+ZlIDBt9FKcubYNTcAH/X0RYM1E7utJPlqe+uZzPxUcEkiSS4sTT95n15Mud0xWC0o2PAWOCdK3KYZlFxfM+tHOcnMzNr1es18ug+cgsVjP4yBU/Ppfrter1m/+l0+zYygML1xRVHU7TSb1cSzBzoBzszsH+AMdJJ49jrNZjWKou6wBnwOzcyndBpNbuueURR1Dw8Pq35p9cc5p/Dy9Dypt7jXrtdGwQECS9NPhr6Gq6txUzNigE6zydLK6lTw12/KT4FGFEUfJX2YJNONq5tVs4ODA7sD/DnwJ/BoADZuE3tHFs12dna6d4C/BI6AlbyzI8ii2TTw12/KK33gb2cdXsNZoAntbZC2SeO4c9592k/5eNQbiwvFd1kJuFGwLJr1wSPg/SwpvyFBHufOeXcFeAlE97U/uCxOY+P3b+Bn4B3Q+L8EdJfD4a+/AbC4UBzPxiPg3wlHZquB28Cn2IuR9x3gr3uV4DbwfvSDOvi4uFA8BDZmIRHkjHpS9Ht9iRqd8+5G3g05mAGcQbsdiX5QJ428G7Kygo8XYdb1/K4NWVmjzkNge2sz84bs+ELmpDDLtqWsNZBXgvmw8CTtpWVMT7x5YWBjLARnwZfKQNYN2U2LPvrh+5nBt7c2M2/It9bArCTKR8eZN+SJ13AScPnoODeRdqNenH+wul5w2gUr2WUjMFAt8bZ/0axX/wNnv4H8vTFb1QAAAABJRU5ErkJggg==\");}.bk-root .bk-tool-icon-poly-edit{background-image:url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gELFi46qJmxxAAABV9JREFUWMOdl19vFFUYxn9n9u9sCyylUIzWUoMQBAWCMdEEIt6xIRQSLIEKtvHe6AcA4yeQb7CAUNJy0daLeomJN8SEULAC2kBBapBKoLvbmdl/c14vdmY7u91tF95kknPOnHmf95znPc97Ro2OTeBbdjFDT3c32ZxVHUOE9kSMB0/m6ExuoJn1H+ur6Y+OTfD50SMN5168OgrAlyf7CfuD+z7+iDs3p8hkLUQ0iFQ/yFl5Nm/qonfHVva+s32Zw9GxCYILsZ08tpNfBhbs+1YN4OH9+7huGdECSBVfqUosbsllfmauBqiR+cCNwOr7AEo8pPHJnymXykhg5fUWjoQpl0vVvhZhbSzGoUOHqgBlt6B6uruj2Zy1E9jo0fhfeyL2x4Mnc8VErK0KUEOB64JSyptfG4RSytsJjUJVxw2lsFy3urL9nx1Qd25ObctkrVMi+jQivd7U2ZyV/3Hzpq7h3h1b/7p9Y0o8v8rwAbTWrGpSocN/FGDlbAI0Rl23PCBan0Ok158H9Ipwzi25A/Mzc9Gl/BYx/E4kYqC1NKRARNAaDCNUM27Z+Zr+ouXs0q4+LSLBHPYCFkTkC6uU39kwCdsS7WRKmaYUiAhdnZ3MPX2K4+QjQI+C94A93rMzm8ltMwyDeDzWjMZeEb2pYQDdW3vITU2jtUZ5QThOPgm8C7wP7J15OPsBsB3oWpGnVWisCeDS1VHj4vBI92+/3tgB7Ab2AruAXiDBK5oIOkhtkEYRNRuJhObrd8Dl9ewf4D5wG7hVLpen29vb5wzD+BrkbBMaL3d1dk5nsrnlFDTTFWAWmAZueWD3gCemGde2k2fw1Al1YXhEvjozoO49eczdqekrWmsc2zlrmvEKOGoW1GUjFLqSk2KpJrCLwyMCPAP+BO54QL8DM6YZX/ClsP9YnwKkXnIBP4jdIpJRpdJTCYdMwwi98KU0Hjc/dDILNyUcwTCWdOSMJ0TRmBktGRhLugu0xyLk7CIqVNm+0bGJptl1YXikD0grpY4Rjc4a8Fbgdab/6OGbAJeCUuyJnnHmZH9pbSyGuBXV8NUwlUpR1EWyixmSyTWEwqGlJ2Swbo2JXbAAfgDGgGQA9I1A9t1tlq0AxrXxn0ilUpw4fhQqYkH/sT41OTnJJwf2s6FjI5mshdYa7bqVR2uezr9MJmJt14FvGrh/O9D+e6UkM/xyCuCqEKCYnJyUTKFQrZDHjxzGshwWLQcRsOz8Hi85P23id0ug/XilAMLBmm4tPGdoaKjSH5+oAGrhwvBI9SjZTn4QSK9yenoD7dlrExPoJlXW8G8ytpNHxRKk02lGxsdRKFwXLNvx5yY94HQLGhGk4LFCYQSqaE0AwWM1eOoEbR0dKBSW7bC4mKuffxs4D/wCLKwQQPAUzIkslfp6cVomROWSolh0GjldAM4nzDi2k9/i5UAzC9aKfwNJ3zgJg9YEvN6+C7SHgKm69+sD7RfNnKTTaZRPQfAut4oFV//IS7gkcB34VlVo8kGzphlfB+DU+TfNGBpZtRastvrvARJmfMF28ge9sc2B9/PNnCilMIDwK6y8/ow/Ai4kvILTljAXvDvEvrqKSUs60KolzPjBxspavQD2tKqCAGF/Ba+xE/Wbilu54wZV8NEKF5fXzQHl/bh4hUsE0WAXSlDMYcQSrQXgCmsTseXHsJkNnjqBFGwKJaHsKlxtUHYVhbLCzr1kaOA4bcn1y1Swmb+iLpJKpVrfgdpfsiVVCYcgluwgnU7jEgJ4s5UkLFtWYyHyEg0/N1q1tmQH+YXnAMFr97Nmv3p+0QsHQRsF8qpBOE5+rb9Nkaj50tVQKjqh4OU3GNL/1/So3vuUgbAAAAAASUVORK5CYII=\");}.bk-root .bk-tool-icon-line-edit{background-image:url(\"data:image/png;base64, \");}";
},
/* styles/menus.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.menu_icon = "bk-menu-icon";
    exports.context_menu = "bk-context-menu";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.divider = "bk-divider";
    exports.active = "bk-active";
    exports.menu = "bk-menu";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.caret = "bk-caret";
    exports.down = "bk-down";
    exports.up = "bk-up";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.default = ".bk-root .bk-menu-icon{width:28px;height:28px;background-size:60%;background-color:transparent;background-repeat:no-repeat;background-position:center center;}.bk-root .bk-context-menu{position:absolute;display:inline-flex;flex-wrap:nowrap;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;width:auto;height:auto;z-index:100;cursor:pointer;font-size:12px;background-color:#fff;border:1px solid #ccc;border-radius:4px;box-shadow:0 6px 12px rgba(0, 0, 0, 0.175);}.bk-root .bk-context-menu.bk-horizontal{flex-direction:row;}.bk-root .bk-context-menu.bk-vertical{flex-direction:column;}.bk-root .bk-context-menu > .bk-divider{cursor:default;overflow:hidden;background-color:#e5e5e5;}.bk-root .bk-context-menu.bk-horizontal > .bk-divider{width:1px;margin:5px 0;}.bk-root .bk-context-menu.bk-vertical > .bk-divider{height:1px;margin:0 5px;}.bk-root .bk-context-menu > :not(.bk-divider){border:1px solid transparent;}.bk-root .bk-context-menu > :not(.bk-divider).bk-active{border-color:#26aae1;}.bk-root .bk-context-menu > :not(.bk-divider):hover{background-color:#f9f9f9;}.bk-root .bk-context-menu > :not(.bk-divider):focus,.bk-root .bk-context-menu > :not(.bk-divider):focus-visible{outline:1px dotted #26aae1;outline-offset:-1px;}.bk-root .bk-context-menu > :not(.bk-divider)::-moz-focus-inner{border:0;}.bk-root .bk-context-menu.bk-horizontal > :not(.bk-divider):first-child{border-top-left-radius:4px;border-bottom-left-radius:4px;}.bk-root .bk-context-menu.bk-horizontal > :not(.bk-divider):last-child{border-top-right-radius:4px;border-bottom-right-radius:4px;}.bk-root .bk-context-menu.bk-vertical > :not(.bk-divider):first-child{border-top-left-radius:4px;border-top-right-radius:4px;}.bk-root .bk-context-menu.bk-vertical > :not(.bk-divider):last-child{border-bottom-left-radius:4px;border-bottom-right-radius:4px;}.bk-root .bk-menu{position:absolute;left:0;width:100%;z-index:100;cursor:pointer;font-size:12px;background-color:#fff;border:1px solid #ccc;border-radius:4px;box-shadow:0 6px 12px rgba(0, 0, 0, 0.175);}.bk-root .bk-menu.bk-above{bottom:100%;}.bk-root .bk-menu.bk-below{top:100%;}.bk-root .bk-menu > .bk-divider{height:1px;margin:7.5px 0;overflow:hidden;background-color:#e5e5e5;}.bk-root .bk-menu > :not(.bk-divider){padding:6px 12px;}.bk-root .bk-menu > :not(.bk-divider):hover,.bk-root .bk-menu > :not(.bk-divider).bk-active{background-color:#e6e6e6;}.bk-root .bk-caret{display:inline-block;vertical-align:middle;width:0;height:0;margin:0 5px;}.bk-root .bk-caret.bk-down{border-top:4px solid;}.bk-root .bk-caret.bk-up{border-bottom:4px solid;}.bk-root .bk-caret.bk-down,.bk-root .bk-caret.bk-up{border-right:4px solid transparent;border-left:4px solid transparent;}.bk-root .bk-caret.bk-left{border-right:4px solid;}.bk-root .bk-caret.bk-right{border-left:4px solid;}.bk-root .bk-caret.bk-left,.bk-root .bk-caret.bk-right{border-top:4px solid transparent;border-bottom:4px solid transparent;}";
},
/* core/util/menus.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var dom_1 = require(158) /* ../dom */;
    var array_1 = require(126) /* ./array */;
    var menus = (0, tslib_1.__importStar)(require(344) /* ../../styles/menus.css */);
    var ContextMenu = /** @class */ (function () {
        function ContextMenu(items, options) {
            var _this = this;
            if (options === void 0) {
                options = {};
            }
            var _a, _b;
            this.items = items;
            this.el = (0, dom_1.div)();
            this._open = false;
            this._item_click = function (entry) {
                var _a;
                (_a = entry.handler) === null || _a === void 0 ? void 0 : _a.call(entry);
                _this.hide();
            };
            this._on_mousedown = function (event) {
                var _a;
                var target = event.target;
                if (target instanceof Node && _this.el.contains(target))
                    return;
                if ((_a = _this.prevent_hide) === null || _a === void 0 ? void 0 : _a.call(_this, event))
                    return;
                _this.hide();
            };
            this._on_keydown = function (event) {
                if (event.keyCode == dom_1.Keys.Esc)
                    _this.hide();
            };
            this._on_blur = function () {
                _this.hide();
            };
            this.orientation = (_a = options.orientation) !== null && _a !== void 0 ? _a : "vertical";
            this.reversed = (_b = options.reversed) !== null && _b !== void 0 ? _b : false;
            this.prevent_hide = options.prevent_hide;
            (0, dom_1.undisplay)(this.el);
        }
        Object.defineProperty(ContextMenu.prototype, "is_open", {
            get: function () {
                return this._open;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ContextMenu.prototype, "can_open", {
            get: function () {
                return this.items.length != 0;
            },
            enumerable: false,
            configurable: true
        });
        ContextMenu.prototype.remove = function () {
            (0, dom_1.remove)(this.el);
            this._unlisten();
        };
        ContextMenu.prototype._listen = function () {
            document.addEventListener("mousedown", this._on_mousedown);
            document.addEventListener("keydown", this._on_keydown);
            window.addEventListener("blur", this._on_blur);
        };
        ContextMenu.prototype._unlisten = function () {
            document.removeEventListener("mousedown", this._on_mousedown);
            document.removeEventListener("keydown", this._on_keydown);
            window.removeEventListener("blur", this._on_blur);
        };
        ContextMenu.prototype._position = function (at) {
            var parent_el = this.el.parentElement;
            if (parent_el != null) {
                var pos = (function () {
                    if ("left_of" in at) {
                        var _a = at.left_of.getBoundingClientRect(), left = _a.left, top = _a.top;
                        return { right: left, top: top };
                    }
                    if ("right_of" in at) {
                        var _b = at.right_of.getBoundingClientRect(), top = _b.top, right = _b.right;
                        return { left: right, top: top };
                    }
                    if ("below" in at) {
                        var _c = at.below.getBoundingClientRect(), left = _c.left, bottom = _c.bottom;
                        return { left: left, top: bottom };
                    }
                    if ("above" in at) {
                        var _d = at.above.getBoundingClientRect(), left = _d.left, top = _d.top;
                        return { left: left, bottom: top };
                    }
                    return at;
                })();
                var parent = parent_el.getBoundingClientRect();
                this.el.style.left = pos.left != null ? pos.left - parent.left + "px" : "";
                this.el.style.top = pos.top != null ? pos.top - parent.top + "px" : "";
                this.el.style.right = pos.right != null ? parent.right - pos.right + "px" : "";
                this.el.style.bottom = pos.bottom != null ? parent.bottom - pos.bottom + "px" : "";
            }
        };
        /*
        override styles(): string[] {
          return [...super.styles(), menus_css]
        }
        */
        ContextMenu.prototype.render = function () {
            var e_1, _a;
            var _this = this;
            var _b;
            (0, dom_1.empty)(this.el, true);
            (0, dom_1.classes)(this.el).add("bk-context-menu", "bk-" + this.orientation);
            var items = this.reversed ? (0, array_1.reversed)(this.items) : this.items;
            var _loop_1 = function (item) {
                var el = void 0;
                if (item == null) {
                    el = (0, dom_1.div)({ class: menus.divider });
                }
                else if (item.if != null && !item.if()) {
                    return "continue";
                }
                else if (item.content != null) {
                    el = item.content;
                }
                else {
                    var icon = item.icon != null ? (0, dom_1.div)({ class: ["bk-menu-icon", item.icon] }) : null;
                    var classes_1 = [((_b = item.active) === null || _b === void 0 ? void 0 : _b.call(item)) ? "bk-active" : null, item.class];
                    el = (0, dom_1.div)({ class: classes_1, title: item.tooltip, tabIndex: 0 }, icon, item.label, item.content);
                    el.addEventListener("click", function () {
                        _this._item_click(item);
                    });
                    el.addEventListener("keydown", function (event) {
                        if (event.keyCode == dom_1.Keys.Enter) {
                            _this._item_click(item);
                        }
                    });
                }
                this_1.el.appendChild(el);
            };
            var this_1 = this;
            try {
                for (var items_1 = (0, tslib_1.__values)(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
                    var item = items_1_1.value;
                    _loop_1(item);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (items_1_1 && !items_1_1.done && (_a = items_1.return))
                        _a.call(items_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        ContextMenu.prototype.show = function (at) {
            if (this.items.length == 0)
                return;
            if (!this._open) {
                this.render();
                if (this.el.children.length == 0)
                    return;
                this._position(at !== null && at !== void 0 ? at : { left: 0, top: 0 });
                (0, dom_1.display)(this.el);
                this._listen();
                this._open = true;
            }
        };
        ContextMenu.prototype.hide = function () {
            if (this._open) {
                this._open = false;
                this._unlisten();
                (0, dom_1.undisplay)(this.el);
            }
        };
        ContextMenu.prototype.toggle = function (at) {
            this._open ? this.hide() : this.show(at);
        };
        return ContextMenu;
    }());
    exports.ContextMenu = ContextMenu;
    ContextMenu.__name__ = "ContextMenu";
},
/* models/tools/on_off_button.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var button_tool_1 = require(339) /* ./button_tool */;
    var toolbars = (0, tslib_1.__importStar)(require(342) /* ../../styles/toolbar.css */);
    var dom_1 = require(158) /* ../../core/dom */;
    var OnOffButtonView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(OnOffButtonView, _super);
        function OnOffButtonView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        OnOffButtonView.prototype.render = function () {
            _super.prototype.render.call(this);
            (0, dom_1.classes)(this.el).toggle(toolbars.active, this.model.active);
        };
        OnOffButtonView.prototype._clicked = function () {
            var active = this.model.active;
            this.model.active = !active;
        };
        return OnOffButtonView;
    }(button_tool_1.ButtonToolButtonView));
    exports.OnOffButtonView = OnOffButtonView;
    OnOffButtonView.__name__ = "OnOffButtonView";
},
/* models/tools/inspectors/inspect_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var button_tool_1 = require(339) /* ../button_tool */;
    var on_off_button_1 = require(346) /* ../on_off_button */;
    var InspectToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(InspectToolView, _super);
        function InspectToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return InspectToolView;
    }(button_tool_1.ButtonToolView));
    exports.InspectToolView = InspectToolView;
    InspectToolView.__name__ = "InspectToolView";
    var InspectTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(InspectTool, _super);
        function InspectTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.event_type = "move";
            return _this;
        }
        return InspectTool;
    }(button_tool_1.ButtonTool));
    exports.InspectTool = InspectTool;
    _a = InspectTool;
    InspectTool.__name__ = "InspectTool";
    (function () {
        _a.prototype.button_view = on_off_button_1.OnOffButtonView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                toggleable: [Boolean, true],
            });
        });
        _a.override({
            active: true,
        });
    })();
},
/* models/tools/toolbar_base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b;
    var logging_1 = require(134) /* ../../core/logging */;
    var dom_1 = require(158) /* ../../core/dom */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var dom_view_1 = require(341) /* ../../core/dom_view */;
    var enums_1 = require(135) /* ../../core/enums */;
    var array_1 = require(126) /* ../../core/util/array */;
    var iterator_1 = require(349) /* ../../core/util/iterator */;
    var object_1 = require(128) /* ../../core/util/object */;
    var types_1 = require(125) /* ../../core/util/types */;
    var canvas_1 = require(350) /* ../../core/util/canvas */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    var model_1 = require(168) /* ../../model */;
    var tool_1 = require(337) /* ./tool */;
    var gesture_tool_1 = require(338) /* ./gestures/gesture_tool */;
    var action_tool_1 = require(353) /* ./actions/action_tool */;
    var help_tool_1 = require(354) /* ./actions/help_tool */;
    var inspect_tool_1 = require(347) /* ./inspectors/inspect_tool */;
    var menus_1 = require(345) /* ../../core/util/menus */;
    var toolbar_css_1 = (0, tslib_1.__importStar)(require(342) /* ../../styles/toolbar.css */), toolbars = toolbar_css_1;
    var logo_css_1 = (0, tslib_1.__importStar)(require(355) /* ../../styles/logo.css */), logos = logo_css_1;
    var ToolbarViewModel = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolbarViewModel, _super);
        function ToolbarViewModel(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(ToolbarViewModel.prototype, "visible", {
            get: function () {
                var _c;
                return !this.autohide || ((_c = this._visible) !== null && _c !== void 0 ? _c : false);
            },
            enumerable: false,
            configurable: true
        });
        return ToolbarViewModel;
    }(model_1.Model));
    exports.ToolbarViewModel = ToolbarViewModel;
    _a = ToolbarViewModel;
    ToolbarViewModel.__name__ = "ToolbarViewModel";
    (function () {
        _a.define(function (_c) {
            var Boolean = _c.Boolean;
            return ({
                autohide: [Boolean, false],
            });
        });
        _a.internal(function (_c) {
            var Boolean = _c.Boolean, Nullable = _c.Nullable;
            return ({
                _visible: [Nullable(Boolean), null],
            });
        });
    })();
    var ToolbarBaseView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolbarBaseView, _super);
        function ToolbarBaseView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.layout = { bbox: new bbox_1.BBox() };
            return _this;
        }
        ToolbarBaseView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._tool_button_views = new Map();
            this._toolbar_view_model = new ToolbarViewModel({ autohide: this.model.autohide });
            var toolbar_location = this.model.toolbar_location;
            var reversed = toolbar_location == "left" || toolbar_location == "above";
            var orientation = this.model.horizontal ? "vertical" : "horizontal";
            this._overflow_menu = new menus_1.ContextMenu([], {
                orientation: orientation,
                reversed: reversed,
                //prevent_hide: (event) => event.target == this.el,
            });
        };
        ToolbarBaseView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_c) {
                    switch (_c.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _c.sent();
                            return [4 /*yield*/, this._build_tool_button_views()];
                        case 2:
                            _c.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        ToolbarBaseView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.tools.change, function () {
                return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                    return (0, tslib_1.__generator)(this, function (_c) {
                        switch (_c.label) {
                            case 0: return [4 /*yield*/, this._build_tool_button_views()];
                            case 1:
                                _c.sent();
                                this.render();
                                return [2 /*return*/];
                        }
                    });
                });
            });
            this.connect(this.model.properties.autohide.change, function () {
                _this._toolbar_view_model.autohide = _this.model.autohide;
                _this._on_visible_change();
            });
            this.connect(this._toolbar_view_model.properties._visible.change, function () { return _this._on_visible_change(); });
        };
        ToolbarBaseView.prototype.styles = function () {
            return (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(_super.prototype.styles.call(this)), false), [toolbar_css_1.default, logo_css_1.default], false);
        };
        ToolbarBaseView.prototype.remove = function () {
            (0, build_views_1.remove_views)(this._tool_button_views);
            _super.prototype.remove.call(this);
        };
        ToolbarBaseView.prototype._build_tool_button_views = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var tools;
                return (0, tslib_1.__generator)(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            tools = (this.model._proxied_tools != null ? this.model._proxied_tools : this.model.tools);
                            return [4 /*yield*/, (0, build_views_1.build_views)(this._tool_button_views, tools, { parent: this }, function (tool) { return tool.button_view; })];
                        case 1:
                            _c.sent(); // XXX: no ButtonToolButton model
                            return [2 /*return*/];
                    }
                });
            });
        };
        ToolbarBaseView.prototype.set_visibility = function (visible) {
            if (visible != this._toolbar_view_model._visible) {
                this._toolbar_view_model._visible = visible;
            }
        };
        ToolbarBaseView.prototype._on_visible_change = function () {
            var visible = this._toolbar_view_model.visible;
            (0, dom_1.classes)(this.el).toggle(toolbars.toolbar_hidden, !visible);
        };
        ToolbarBaseView.prototype.render = function () {
            var e_1, _c, e_2, _d, e_3, _e;
            var _this = this;
            (0, dom_1.empty)(this.el);
            this.el.classList.add(toolbars.toolbar);
            this.el.classList.add(toolbars[this.model.toolbar_location]);
            this._toolbar_view_model.autohide = this.model.autohide;
            this._on_visible_change();
            var horizontal = this.model.horizontal;
            var size = 0;
            if (this.model.logo != null) {
                var gray = this.model.logo === "grey" ? logos.grey : null;
                var logo_el = (0, dom_1.a)({ href: "https://bokeh.org/", target: "_blank", class: [logos.logo, logos.logo_small, gray] });
                this.el.appendChild(logo_el);
                var _f = logo_el.getBoundingClientRect(), width = _f.width, height = _f.height;
                size += horizontal ? width : height;
            }
            try {
                for (var _g = (0, tslib_1.__values)(this._tool_button_views), _h = _g.next(); !_h.done; _h = _g.next()) {
                    var _j = (0, tslib_1.__read)(_h.value, 2), button_view = _j[1];
                    button_view.render();
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_h && !_h.done && (_c = _g.return))
                        _c.call(_g);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            var bars = [];
            var el = function (tool) {
                return _this._tool_button_views.get(tool).el;
            };
            var gestures = this.model.gestures;
            try {
                for (var _k = (0, tslib_1.__values)((0, object_1.values)(gestures)), _l = _k.next(); !_l.done; _l = _k.next()) {
                    var gesture = _l.value;
                    bars.push(gesture.tools.map(el));
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_l && !_l.done && (_d = _k.return))
                        _d.call(_k);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            bars.push(this.model.actions.map(el));
            bars.push(this.model.inspectors.filter(function (tool) { return tool.toggleable; }).map(el));
            var non_empty = bars.filter(function (bar) { return bar.length != 0; });
            var divider = function () { return (0, dom_1.div)({ class: toolbars.divider }); };
            var bbox = this.layout.bbox;
            var overflowed = false;
            var overflow_size = 15;
            this.root.el.appendChild(this._overflow_menu.el);
            var overflow_button = (0, dom_1.div)({ class: toolbars.tool_overflow, tabIndex: 0 }, horizontal ? "⋮" : "⋯");
            var toggle_menu = function () {
                var at = (function () {
                    switch (_this.model.toolbar_location) {
                        case "right": return { left_of: overflow_button };
                        case "left": return { right_of: overflow_button };
                        case "above": return { below: overflow_button };
                        case "below": return { above: overflow_button };
                    }
                })();
                _this._overflow_menu.toggle(at);
            };
            overflow_button.addEventListener("click", function () {
                toggle_menu();
            });
            overflow_button.addEventListener("keydown", function (event) {
                if (event.keyCode == dom_1.Keys.Enter) {
                    toggle_menu();
                }
            });
            try {
                for (var _m = (0, tslib_1.__values)((0, iterator_1.join)(non_empty, divider)), _o = _m.next(); !_o.done; _o = _m.next()) {
                    var el_1 = _o.value;
                    if (overflowed) {
                        this._overflow_menu.items.push({ content: el_1, class: horizontal ? toolbars.right : toolbars.above });
                    }
                    else {
                        this.el.appendChild(el_1);
                        var _p = el_1.getBoundingClientRect(), width = _p.width, height = _p.height;
                        size += horizontal ? width : height;
                        overflowed = horizontal ? size > bbox.width - overflow_size : size > bbox.height - overflow_size;
                        if (overflowed) {
                            this.el.removeChild(el_1);
                            this.el.appendChild(overflow_button);
                            var items = this._overflow_menu.items;
                            items.splice(0, items.length);
                            items.push({ content: el_1 });
                        }
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_o && !_o.done && (_e = _m.return))
                        _e.call(_m);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
        };
        ToolbarBaseView.prototype.update_layout = function () { };
        ToolbarBaseView.prototype.update_position = function () { };
        ToolbarBaseView.prototype.after_layout = function () {
            this._has_finished = true;
        };
        ToolbarBaseView.prototype.export = function (type, hidpi) {
            if (hidpi === void 0) {
                hidpi = true;
            }
            var output_backend = type == "png" ? "canvas" : "svg";
            var canvas = new canvas_1.CanvasLayer(output_backend, hidpi);
            canvas.resize(0, 0);
            return canvas;
        };
        return ToolbarBaseView;
    }(dom_view_1.DOMView));
    exports.ToolbarBaseView = ToolbarBaseView;
    ToolbarBaseView.__name__ = "ToolbarBaseView";
    function create_gesture_map() {
        return {
            pan: { tools: [], active: null },
            scroll: { tools: [], active: null },
            pinch: { tools: [], active: null },
            tap: { tools: [], active: null },
            doubletap: { tools: [], active: null },
            press: { tools: [], active: null },
            pressup: { tools: [], active: null },
            rotate: { tools: [], active: null },
            move: { tools: [], active: null },
            multi: { tools: [], active: null },
        };
    }
    var ToolbarBase = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolbarBase, _super);
        function ToolbarBase(attrs) {
            return _super.call(this, attrs) || this;
        }
        ToolbarBase.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._init_tools();
        };
        ToolbarBase.prototype._init_tools = function () {
            var e_4, _c, e_5, _d, e_6, _e;
            var _this = this;
            // The only purpose of this function is to avoid unnecessary property churning.
            var tools_changed = function (old_tools, new_tools) {
                if (old_tools.length != new_tools.length) {
                    return true;
                }
                var new_ids = new Set(new_tools.map(function (t) { return t.id; }));
                return (0, array_1.some)(old_tools, function (t) { return !new_ids.has(t.id); });
            };
            var new_inspectors = this.tools.filter(function (t) { return t instanceof inspect_tool_1.InspectTool; });
            if (tools_changed(this.inspectors, new_inspectors)) {
                this.inspectors = new_inspectors;
            }
            var new_help = this.tools.filter(function (t) { return t instanceof help_tool_1.HelpTool; });
            if (tools_changed(this.help, new_help)) {
                this.help = new_help;
            }
            var new_actions = this.tools.filter(function (t) { return t instanceof action_tool_1.ActionTool; });
            if (tools_changed(this.actions, new_actions)) {
                this.actions = new_actions;
            }
            var check_event_type = function (et, tool) {
                if (!(et in _this.gestures)) {
                    logging_1.logger.warn("Toolbar: unknown event type '" + et + "' for tool: " + tool);
                }
            };
            var new_gestures = create_gesture_map();
            try {
                for (var _f = (0, tslib_1.__values)(this.tools), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var tool = _g.value;
                    if (tool instanceof gesture_tool_1.GestureTool && tool.event_type) {
                        if ((0, types_1.isString)(tool.event_type)) {
                            new_gestures[tool.event_type].tools.push(tool);
                            check_event_type(tool.event_type, tool);
                        }
                        else {
                            new_gestures.multi.tools.push(tool);
                            try {
                                for (var _h = (e_5 = void 0, (0, tslib_1.__values)(tool.event_type)), _j = _h.next(); !_j.done; _j = _h.next()) {
                                    var et = _j.value;
                                    check_event_type(et, tool);
                                }
                            }
                            catch (e_5_1) {
                                e_5 = { error: e_5_1 };
                            }
                            finally {
                                try {
                                    if (_j && !_j.done && (_d = _h.return))
                                        _d.call(_h);
                                }
                                finally {
                                    if (e_5)
                                        throw e_5.error;
                                }
                            }
                        }
                    }
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_c = _f.return))
                        _c.call(_f);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            var _loop_1 = function (et) {
                var gm = this_1.gestures[et];
                if (tools_changed(gm.tools, new_gestures[et].tools)) {
                    gm.tools = new_gestures[et].tools;
                }
                if (gm.active && (0, array_1.every)(gm.tools, function (t) { return t.id != gm.active.id; })) {
                    gm.active = null;
                }
            };
            var this_1 = this;
            try {
                for (var _k = (0, tslib_1.__values)(Object.keys(new_gestures)), _l = _k.next(); !_l.done; _l = _k.next()) {
                    var et = _l.value;
                    _loop_1(et);
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_l && !_l.done && (_e = _k.return))
                        _e.call(_k);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
        };
        Object.defineProperty(ToolbarBase.prototype, "horizontal", {
            get: function () {
                return this.toolbar_location === "above" || this.toolbar_location === "below";
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ToolbarBase.prototype, "vertical", {
            get: function () {
                return this.toolbar_location === "left" || this.toolbar_location === "right";
            },
            enumerable: false,
            configurable: true
        });
        ToolbarBase.prototype._active_change = function (tool) {
            var e_7, _c;
            var event_type = tool.event_type;
            if (event_type == null)
                return;
            var event_types = (0, types_1.isString)(event_type) ? [event_type] : event_type;
            try {
                for (var event_types_1 = (0, tslib_1.__values)(event_types), event_types_1_1 = event_types_1.next(); !event_types_1_1.done; event_types_1_1 = event_types_1.next()) {
                    var et = event_types_1_1.value;
                    if (tool.active) {
                        var currently_active_tool = this.gestures[et].active;
                        if (currently_active_tool != null && tool != currently_active_tool) {
                            logging_1.logger.debug("Toolbar: deactivating tool: " + currently_active_tool + " for event type '" + et + "'");
                            currently_active_tool.active = false;
                        }
                        this.gestures[et].active = tool;
                        logging_1.logger.debug("Toolbar: activating tool: " + tool + " for event type '" + et + "'");
                    }
                    else
                        this.gestures[et].active = null;
                }
            }
            catch (e_7_1) {
                e_7 = { error: e_7_1 };
            }
            finally {
                try {
                    if (event_types_1_1 && !event_types_1_1.done && (_c = event_types_1.return))
                        _c.call(event_types_1);
                }
                finally {
                    if (e_7)
                        throw e_7.error;
                }
            }
        };
        return ToolbarBase;
    }(model_1.Model));
    exports.ToolbarBase = ToolbarBase;
    _b = ToolbarBase;
    ToolbarBase.__name__ = "ToolbarBase";
    (function () {
        _b.prototype.default_view = ToolbarBaseView;
        _b.define(function (_c) {
            var Boolean = _c.Boolean, Array = _c.Array, Ref = _c.Ref, Nullable = _c.Nullable;
            return ({
                tools: [Array(Ref(tool_1.Tool)), []],
                logo: [Nullable(enums_1.Logo), "normal"],
                autohide: [Boolean, false],
            });
        });
        _b.internal(function (_c) {
            var Array = _c.Array, Struct = _c.Struct, Ref = _c.Ref, Nullable = _c.Nullable;
            var GestureEntry = Struct({
                tools: Array(Ref(gesture_tool_1.GestureTool)),
                active: Nullable(Ref(tool_1.Tool)),
            });
            var GestureMap = Struct({
                pan: GestureEntry,
                scroll: GestureEntry,
                pinch: GestureEntry,
                tap: GestureEntry,
                doubletap: GestureEntry,
                press: GestureEntry,
                pressup: GestureEntry,
                rotate: GestureEntry,
                move: GestureEntry,
                multi: GestureEntry,
            });
            return {
                gestures: [GestureMap, create_gesture_map],
                actions: [Array(Ref(action_tool_1.ActionTool)), []],
                inspectors: [Array(Ref(inspect_tool_1.InspectTool)), []],
                help: [Array(Ref(help_tool_1.HelpTool)), []],
                toolbar_location: [enums_1.Location, "right"],
            };
        });
    })();
},
/* core/util/iterator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var array_1 = require(126) /* ./array */;
    function enumerate(seq) {
        var i, seq_1, seq_1_1, item, e_1_1;
        var e_1, _a;
        return (0, tslib_1.__generator)(this, function (_b) {
            switch (_b.label) {
                case 0:
                    i = 0;
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 6, 7, 8]);
                    seq_1 = (0, tslib_1.__values)(seq), seq_1_1 = seq_1.next();
                    _b.label = 2;
                case 2:
                    if (!!seq_1_1.done)
                        return [3 /*break*/, 5];
                    item = seq_1_1.value;
                    return [4 /*yield*/, [item, i++]];
                case 3:
                    _b.sent();
                    _b.label = 4;
                case 4:
                    seq_1_1 = seq_1.next();
                    return [3 /*break*/, 2];
                case 5: return [3 /*break*/, 8];
                case 6:
                    e_1_1 = _b.sent();
                    e_1 = { error: e_1_1 };
                    return [3 /*break*/, 8];
                case 7:
                    try {
                        if (seq_1_1 && !seq_1_1.done && (_a = seq_1.return))
                            _a.call(seq_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                    return [7 /*endfinally*/];
                case 8: return [2 /*return*/];
            }
        });
    }
    exports.enumerate = enumerate;
    function join(seq, separator) {
        var first, seq_2, seq_2_1, entry, e_2_1;
        var e_2, _a;
        return (0, tslib_1.__generator)(this, function (_b) {
            switch (_b.label) {
                case 0:
                    first = true;
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, 9, 10, 11]);
                    seq_2 = (0, tslib_1.__values)(seq), seq_2_1 = seq_2.next();
                    _b.label = 2;
                case 2:
                    if (!!seq_2_1.done)
                        return [3 /*break*/, 8];
                    entry = seq_2_1.value;
                    if (!first)
                        return [3 /*break*/, 3];
                    first = false;
                    return [3 /*break*/, 5];
                case 3:
                    if (!(separator != null))
                        return [3 /*break*/, 5];
                    return [4 /*yield*/, separator()];
                case 4:
                    _b.sent();
                    _b.label = 5;
                case 5: return [5 /*yield**/, (0, tslib_1.__values)(entry)];
                case 6:
                    _b.sent();
                    _b.label = 7;
                case 7:
                    seq_2_1 = seq_2.next();
                    return [3 /*break*/, 2];
                case 8: return [3 /*break*/, 11];
                case 9:
                    e_2_1 = _b.sent();
                    e_2 = { error: e_2_1 };
                    return [3 /*break*/, 11];
                case 10:
                    try {
                        if (seq_2_1 && !seq_2_1.done && (_a = seq_2.return))
                            _a.call(seq_2);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                    return [7 /*endfinally*/];
                case 11: return [2 /*return*/];
            }
        });
    }
    exports.join = join;
    // https://docs.python.org/3.8/library/itertools.html#itertools.combinations
    function combinations(seq, r) {
        var n, indices, k, _a, _b, i, _c, _d, j;
        var e_3, _e, e_4, _f;
        return (0, tslib_1.__generator)(this, function (_g) {
            switch (_g.label) {
                case 0:
                    n = seq.length;
                    if (r > n)
                        return [2 /*return*/];
                    indices = (0, array_1.range)(r);
                    return [4 /*yield*/, indices.map(function (i) { return seq[i]; })];
                case 1:
                    _g.sent();
                    _g.label = 2;
                case 2:
                    if (!true)
                        return [3 /*break*/, 4];
                    k = void 0;
                    try {
                        for (_a = (e_3 = void 0, (0, tslib_1.__values)((0, array_1.reversed)((0, array_1.range)(r)))), _b = _a.next(); !_b.done; _b = _a.next()) {
                            i = _b.value;
                            if (indices[i] != i + n - r) {
                                k = i;
                                break;
                            }
                        }
                    }
                    catch (e_3_1) {
                        e_3 = { error: e_3_1 };
                    }
                    finally {
                        try {
                            if (_b && !_b.done && (_e = _a.return))
                                _e.call(_a);
                        }
                        finally {
                            if (e_3)
                                throw e_3.error;
                        }
                    }
                    if (k == null)
                        return [2 /*return*/];
                    indices[k] += 1;
                    try {
                        for (_c = (e_4 = void 0, (0, tslib_1.__values)((0, array_1.range)(k + 1, r))), _d = _c.next(); !_d.done; _d = _c.next()) {
                            j = _d.value;
                            indices[j] = indices[j - 1] + 1;
                        }
                    }
                    catch (e_4_1) {
                        e_4 = { error: e_4_1 };
                    }
                    finally {
                        try {
                            if (_d && !_d.done && (_f = _c.return))
                                _f.call(_c);
                        }
                        finally {
                            if (e_4)
                                throw e_4.error;
                        }
                    }
                    return [4 /*yield*/, indices.map(function (i) { return seq[i]; })];
                case 3:
                    _g.sent();
                    return [3 /*break*/, 2];
                case 4: return [2 /*return*/];
            }
        });
    }
    exports.combinations = combinations;
    function subsets(seq) {
        var _a, _b, k, e_5_1;
        var e_5, _c;
        return (0, tslib_1.__generator)(this, function (_d) {
            switch (_d.label) {
                case 0:
                    _d.trys.push([0, 5, 6, 7]);
                    _a = (0, tslib_1.__values)((0, array_1.range)(seq.length + 1)), _b = _a.next();
                    _d.label = 1;
                case 1:
                    if (!!_b.done)
                        return [3 /*break*/, 4];
                    k = _b.value;
                    return [5 /*yield**/, (0, tslib_1.__values)(combinations(seq, k))];
                case 2:
                    _d.sent();
                    _d.label = 3;
                case 3:
                    _b = _a.next();
                    return [3 /*break*/, 1];
                case 4: return [3 /*break*/, 7];
                case 5:
                    e_5_1 = _d.sent();
                    e_5 = { error: e_5_1 };
                    return [3 /*break*/, 7];
                case 6:
                    try {
                        if (_b && !_b.done && (_c = _a.return))
                            _c.call(_a);
                    }
                    finally {
                        if (e_5)
                            throw e_5.error;
                    }
                    return [7 /*endfinally*/];
                case 7: return [2 /*return*/];
            }
        });
    }
    exports.subsets = subsets;
},
/* core/util/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var svg_1 = require(351) /* ./svg */;
    var bbox_1 = require(180) /* ./bbox */;
    var dom_1 = require(158) /* ../dom */;
    function fixup_line_dash(ctx) {
        if (typeof ctx.lineDash === "undefined") {
            Object.defineProperty(ctx, "lineDash", {
                get: function () { return ctx.getLineDash(); },
                set: function (segments) { return ctx.setLineDash(segments); },
            });
        }
    }
    function fixup_image_smoothing(ctx) {
        ctx.setImageSmoothingEnabled = function (value) {
            ctx.imageSmoothingEnabled = value;
            ctx.mozImageSmoothingEnabled = value;
            ctx.oImageSmoothingEnabled = value;
            ctx.webkitImageSmoothingEnabled = value;
            ctx.msImageSmoothingEnabled = value;
        };
        ctx.getImageSmoothingEnabled = function () {
            var val = ctx.imageSmoothingEnabled;
            return val != null ? val : true;
        };
    }
    function fixup_ellipse(ctx) {
        // implementing the ctx.ellipse function with bezier curves
        // we don't implement the startAngle, endAngle and anticlockwise arguments.
        function ellipse_bezier(x, y, radiusX, radiusY, rotation, _startAngle, _endAngle, anticlockwise) {
            if (anticlockwise === void 0) {
                anticlockwise = false;
            }
            var c = 0.551784; // see http://www.tinaja.com/glib/ellipse4.pdf
            ctx.translate(x, y);
            ctx.rotate(rotation);
            var rx = radiusX;
            var ry = radiusY;
            if (anticlockwise) {
                rx = -radiusX;
                ry = -radiusY;
            }
            ctx.moveTo(-rx, 0); // start point of first curve
            ctx.bezierCurveTo(-rx, ry * c, -rx * c, ry, 0, ry);
            ctx.bezierCurveTo(rx * c, ry, rx, ry * c, rx, 0);
            ctx.bezierCurveTo(rx, -ry * c, rx * c, -ry, 0, -ry);
            ctx.bezierCurveTo(-rx * c, -ry, -rx, -ry * c, -rx, 0);
            ctx.rotate(-rotation);
            ctx.translate(-x, -y);
        }
        if (!ctx.ellipse)
            ctx.ellipse = ellipse_bezier;
    }
    function fixup_ctx(ctx) {
        fixup_line_dash(ctx);
        fixup_image_smoothing(ctx);
        fixup_ellipse(ctx);
    }
    var style = {
        position: "absolute",
        top: "0",
        left: "0",
        width: "100%",
        height: "100%",
    };
    var CanvasLayer = /** @class */ (function () {
        function CanvasLayer(backend, hidpi) {
            this.backend = backend;
            this.hidpi = hidpi;
            this.pixel_ratio = 1;
            this.bbox = new bbox_1.BBox();
            switch (backend) {
                case "webgl":
                case "canvas": {
                    this._el = this._canvas = (0, dom_1.canvas)({ style: style });
                    var ctx = this.canvas.getContext("2d");
                    if (ctx == null)
                        throw new Error("unable to obtain 2D rendering context");
                    this._ctx = ctx;
                    if (hidpi) {
                        this.pixel_ratio = devicePixelRatio;
                    }
                    break;
                }
                case "svg": {
                    var ctx = new svg_1.SVGRenderingContext2D();
                    this._ctx = ctx;
                    this._canvas = ctx.get_svg();
                    this._el = (0, dom_1.div)({ style: style }, this._canvas);
                    break;
                }
            }
            this._ctx.layer = this;
            fixup_ctx(this._ctx);
        }
        Object.defineProperty(CanvasLayer.prototype, "canvas", {
            get: function () {
                return this._canvas;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CanvasLayer.prototype, "ctx", {
            get: function () {
                return this._ctx;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CanvasLayer.prototype, "el", {
            get: function () {
                return this._el;
            },
            enumerable: false,
            configurable: true
        });
        CanvasLayer.prototype.resize = function (width, height) {
            this.bbox = new bbox_1.BBox({ left: 0, top: 0, width: width, height: height });
            var target = this._ctx instanceof svg_1.SVGRenderingContext2D ? this._ctx : this.canvas;
            target.width = width * this.pixel_ratio;
            target.height = height * this.pixel_ratio;
        };
        CanvasLayer.prototype.undo_transform = function (fn) {
            var ctx = this.ctx;
            if (typeof ctx.getTransform === "undefined") {
                // XXX: remove this when IE/legacy is dropped
                fn(ctx);
            }
            else {
                var current_transform = ctx.getTransform();
                ctx.setTransform(this._base_transform);
                try {
                    fn(ctx);
                }
                finally {
                    ctx.setTransform(current_transform);
                }
            }
        };
        CanvasLayer.prototype.prepare = function () {
            var _a = this, ctx = _a.ctx, hidpi = _a.hidpi, pixel_ratio = _a.pixel_ratio;
            ctx.save();
            if (hidpi) {
                ctx.scale(pixel_ratio, pixel_ratio);
                ctx.translate(0.5, 0.5);
            }
            if (typeof ctx.getTransform !== "undefined") { // XXX: remove this line when IE/legacy is dropped
                this._base_transform = ctx.getTransform();
            }
            this.clear();
        };
        CanvasLayer.prototype.clear = function () {
            var _a = this.bbox, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
            this.ctx.clearRect(x, y, width, height);
        };
        CanvasLayer.prototype.finish = function () {
            this.ctx.restore();
        };
        CanvasLayer.prototype.to_blob = function () {
            var _canvas = this._canvas;
            if (_canvas instanceof HTMLCanvasElement) {
                if (_canvas.msToBlob != null) {
                    return Promise.resolve(_canvas.msToBlob());
                }
                else {
                    return new Promise(function (resolve, reject) {
                        _canvas.toBlob(function (blob) { return blob != null ? resolve(blob) : reject(); }, "image/png");
                    });
                }
            }
            else {
                var ctx = this._ctx;
                var svg = ctx.get_serialized_svg(true);
                var blob = new Blob([svg], { type: "image/svg+xml" });
                return Promise.resolve(blob);
            }
        };
        return CanvasLayer;
    }());
    exports.CanvasLayer = CanvasLayer;
    CanvasLayer.__name__ = "CanvasLayer";
},
/* core/util/svg.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    /**
     * Based on https://github.com/gliffy/canvas2svg
     */
    var affine_1 = require(237) /* ./affine */;
    var types_1 = require(125) /* ./types */;
    var random_1 = require(352) /* ./random */;
    var dom_1 = require(158) /* ../dom */;
    // helper function to map named to numbered entities
    function createNamedToNumberedLookup(input, radix) {
        var lookup = new Map();
        var items = input.split(",");
        radix = radix !== null && radix !== void 0 ? radix : 10;
        // Map from named to numbered entities.
        for (var i = 0; i < items.length; i += 2) {
            var entity = "&" + items[i + 1] + ";";
            var base10 = parseInt(items[i], radix);
            lookup.set(entity, "&#" + base10 + ";");
        }
        // FF and IE need to create a regex from hex values ie &nbsp; == \xa0
        lookup.set("\\xa0", "&#160;");
        return lookup;
    }
    // helper function to map canvas-textAlign to svg-textAnchor
    function getTextAnchor(textAlign) {
        var _a;
        // TODO: support rtl languages
        var mapping = { left: "start", right: "end", center: "middle", start: "start", end: "end" };
        return (_a = mapping[textAlign]) !== null && _a !== void 0 ? _a : mapping.start;
    }
    // helper function to map canvas-textBaseline to svg-dominantBaseline
    function getDominantBaseline(textBaseline) {
        var _a;
        // INFO: not supported in all browsers
        var mapping = { alphabetic: "alphabetic", hanging: "hanging", top: "text-before-edge", bottom: "text-after-edge", middle: "central" };
        return (_a = mapping[textBaseline]) !== null && _a !== void 0 ? _a : mapping.alphabetic;
    }
    // Unpack entities lookup where the numbers are in radix 32 to reduce the size
    // entity mapping courtesy of tinymce
    var namedEntities = createNamedToNumberedLookup("50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy," +
        "5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute," +
        "5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34," +
        "5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil," +
        "68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde," +
        "6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute," +
        "6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml," +
        "75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc," +
        "7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash," +
        "7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta," +
        "sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu," +
        "st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi," +
        "t9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota," +
        "tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau," +
        "u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip," +
        "81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym," +
        "8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr," +
        "8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod," +
        "8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup," +
        "8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4," +
        "nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob," +
        "rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0," +
        "Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm," +
        "80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger," +
        "811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro", 32);
    // Some basic mappings for attributes and default values.
    var STYLES = {
        strokeStyle: {
            svgAttr: "stroke",
            canvas: "#000000",
            svg: "none",
            apply: "stroke", // apply on stroke() or fill()
        },
        fillStyle: {
            svgAttr: "fill",
            canvas: "#000000",
            svg: null,
            apply: "fill",
        },
        lineCap: {
            svgAttr: "stroke-linecap",
            canvas: "butt",
            svg: "butt",
            apply: "stroke",
        },
        lineJoin: {
            svgAttr: "stroke-linejoin",
            canvas: "miter",
            svg: "miter",
            apply: "stroke",
        },
        miterLimit: {
            svgAttr: "stroke-miterlimit",
            canvas: 10,
            svg: 4,
            apply: "stroke",
        },
        lineWidth: {
            svgAttr: "stroke-width",
            canvas: 1,
            svg: 1,
            apply: "stroke",
        },
        globalAlpha: {
            svgAttr: "opacity",
            canvas: 1,
            svg: 1,
            apply: "fill stroke",
        },
        font: {
            // font converts to multiple svg attributes, there is custom logic for this
            canvas: "10px sans-serif",
        },
        shadowColor: {
            canvas: "#000000",
        },
        shadowOffsetX: {
            canvas: 0,
        },
        shadowOffsetY: {
            canvas: 0,
        },
        shadowBlur: {
            canvas: 0,
        },
        textAlign: {
            canvas: "start",
        },
        textBaseline: {
            canvas: "alphabetic",
        },
        lineDash: {
            svgAttr: "stroke-dasharray",
            canvas: [],
            svg: null,
            apply: "stroke",
        },
        lineDashOffset: {
            svgAttr: "stroke-dashoffset",
            canvas: 0,
            svg: 0,
            apply: "stroke",
        },
    };
    var CanvasGradient = /** @class */ (function () {
        function CanvasGradient(gradientNode, ctx) {
            this.__root = gradientNode;
            this.__ctx = ctx;
        }
        /**
         * Adds a color stop to the gradient root
         */
        CanvasGradient.prototype.addColorStop = function (offset, color) {
            if (this.__root.nodeName === "linearGradient" &&
                this.__root.getAttribute("x1") === this.__root.getAttribute("x2") &&
                this.__root.getAttribute("y1") === this.__root.getAttribute("y2"))
                return;
            if (this.__root.nodeName === "radialGradient" &&
                this.__root.getAttribute("cx") === this.__root.getAttribute("fx") &&
                this.__root.getAttribute("cy") === this.__root.getAttribute("fy") &&
                this.__root.getAttribute("r") === this.__root.getAttribute("r0"))
                return;
            var stop = this.__ctx.__createElement("stop");
            stop.setAttribute("offset", "" + offset);
            if (color.indexOf("rgba") !== -1) {
                // separate alpha value, since webkit can't handle it
                var regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
                var matches = regex.exec(color);
                var _a = (0, tslib_1.__read)(matches, 5), r = _a[1], g = _a[2], b = _a[3], a = _a[4];
                stop.setAttribute("stop-color", "rgb(" + r + "," + g + "," + b + ")");
                stop.setAttribute("stop-opacity", a);
            }
            else {
                stop.setAttribute("stop-color", color);
            }
            this.__root.appendChild(stop);
        };
        return CanvasGradient;
    }());
    CanvasGradient.__name__ = "CanvasGradient";
    var CanvasPattern = /** @class */ (function () {
        function CanvasPattern(pattern, ctx) {
            this.__root = pattern;
            this.__ctx = ctx;
        }
        CanvasPattern.prototype.setTransform = function (_transform) {
            throw new Error("not implemented");
        };
        return CanvasPattern;
    }());
    CanvasPattern.__name__ = "CanvasPattern";
    var SVGRenderingContext2D = /** @class */ (function () {
        function SVGRenderingContext2D(options) {
            var _a, _b, _c;
            this.__currentPosition = null;
            this._transform = new affine_1.AffineTransform();
            this._clip_path = null;
            this.__document = (_a = options === null || options === void 0 ? void 0 : options.document) !== null && _a !== void 0 ? _a : document;
            // allow passing in an existing context to wrap around
            // if a context is passed in, we know a canvas already exist
            if (options === null || options === void 0 ? void 0 : options.ctx) {
                this.__ctx = options.ctx;
            }
            else {
                this.__canvas = this.__document.createElement("canvas");
                this.__ctx = this.__canvas.getContext("2d");
            }
            this.__setDefaultStyles();
            this.__stack = [];
            // the root svg element
            this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg");
            this.__root.setAttribute("version", "1.1");
            this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg");
            this.width = (_b = options === null || options === void 0 ? void 0 : options.width) !== null && _b !== void 0 ? _b : 500;
            this.height = (_c = options === null || options === void 0 ? void 0 : options.height) !== null && _c !== void 0 ? _c : 500;
            // make sure we don't generate the same ids in defs
            this.__ids = new Set();
            // defs tag
            this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs");
            this.__root.appendChild(this.__defs);
        }
        Object.defineProperty(SVGRenderingContext2D.prototype, "canvas", {
            get: function () {
                // XXX: point back to this instance
                return this;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SVGRenderingContext2D.prototype, "width", {
            get: function () {
                return this._width;
            },
            set: function (width) {
                this._width = width;
                this.__root.setAttribute("width", "" + width);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(SVGRenderingContext2D.prototype, "height", {
            get: function () {
                return this._height;
            },
            set: function (height) {
                this._height = height;
                this.__root.setAttribute("height", "" + height);
            },
            enumerable: false,
            configurable: true
        });
        // helper function that generates a random string
        SVGRenderingContext2D.prototype._random_string = function () {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
            var str;
            do {
                str = SVGRenderingContext2D.__random.choices(12, chars).join("");
            } while (this.__ids.has(str));
            return str;
        };
        /**
         * Creates the specified svg element
         */
        SVGRenderingContext2D.prototype.__createElement = function (elementName, properties, resetFill) {
            var e_1, _a;
            if (properties === void 0) {
                properties = {};
            }
            if (resetFill === void 0) {
                resetFill = false;
            }
            var element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName);
            if (resetFill) {
                // if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black.
                element.setAttribute("fill", "none");
                element.setAttribute("stroke", "none");
            }
            var keys = Object.keys(properties);
            try {
                for (var keys_1 = (0, tslib_1.__values)(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
                    var key = keys_1_1.value;
                    element.setAttribute(key, "" + properties[key]);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return))
                        _a.call(keys_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return element;
        };
        /**
         * Applies default canvas styles to the context
         */
        SVGRenderingContext2D.prototype.__setDefaultStyles = function () {
            // default 2d canvas context properties see:http://www.w3.org/TR/2dcontext/
            var keys = Object.keys(STYLES);
            var self = this;
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                self[key] = STYLES[key].canvas;
            }
        };
        /**
         * Applies styles on restore
         */
        SVGRenderingContext2D.prototype.__applyStyleState = function (styleState) {
            var keys = Object.keys(styleState);
            var self = this;
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                self[key] = styleState[key];
            }
        };
        /**
         * Gets the current style state
         */
        SVGRenderingContext2D.prototype.__getStyleState = function () {
            var keys = Object.keys(STYLES);
            var styleState = {};
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                styleState[key] = this[key];
            }
            return styleState;
        };
        /**
         * Apples the current styles to the current SVG element. On "ctx.fill" or "ctx.stroke"
         */
        SVGRenderingContext2D.prototype.__applyStyleToCurrentElement = function (type) {
            var e_2, _a;
            var _b;
            var currentElement = this.__currentElement;
            /*
            const currentStyleGroup = this.__currentElementsToStyle
            if (currentStyleGroup != null) {
              currentElement.setAttribute(type, "")
              currentElement = currentStyleGroup.element
              for (const node of currentStyleGroup.children) {
                node.setAttribute(type, "")
              }
            }
            */
            var keys = Object.keys(STYLES);
            for (var i = 0; i < keys.length; i++) {
                var style = STYLES[keys[i]];
                var value = this[keys[i]];
                if ((_b = style.apply) === null || _b === void 0 ? void 0 : _b.includes(type)) {
                    if (value instanceof CanvasPattern) {
                        try {
                            for (var _c = (e_2 = void 0, (0, tslib_1.__values)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(value.__ctx.__defs.childNodes), false))), _d = _c.next(); !_d.done; _d = _c.next()) {
                                var def = _d.value;
                                if (def instanceof Element) {
                                    var id_1 = def.getAttribute("id");
                                    this.__ids.add(id_1);
                                    this.__defs.appendChild(def);
                                }
                            }
                        }
                        catch (e_2_1) {
                            e_2 = { error: e_2_1 };
                        }
                        finally {
                            try {
                                if (_d && !_d.done && (_a = _c.return))
                                    _a.call(_c);
                            }
                            finally {
                                if (e_2)
                                    throw e_2.error;
                            }
                        }
                        var id = value.__root.getAttribute("id");
                        currentElement.setAttribute(style.apply, "url(#" + id + ")");
                    }
                    else if (value instanceof CanvasGradient) {
                        var id = value.__root.getAttribute("id");
                        currentElement.setAttribute(style.apply, "url(#" + id + ")");
                    }
                    else if (style.svg !== value) {
                        if ((style.svgAttr === "stroke" || style.svgAttr === "fill") && (0, types_1.isString)(value) && value.indexOf("rgba") !== -1) {
                            // separate alpha value, since illustrator can't handle it
                            var regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
                            var matches = regex.exec(value);
                            var _e = (0, tslib_1.__read)(matches, 5), r = _e[1], g = _e[2], b = _e[3], a = _e[4];
                            currentElement.setAttribute(style.svgAttr, "rgb(" + r + "," + g + "," + b + ")");
                            // should take globalAlpha here
                            var opacity = parseFloat(a);
                            var globalAlpha = this.globalAlpha;
                            if (globalAlpha != null) {
                                opacity *= globalAlpha;
                            }
                            currentElement.setAttribute(style.svgAttr + "-opacity", "" + opacity);
                        }
                        else {
                            var attr = style.svgAttr;
                            if (keys[i] === "globalAlpha") {
                                attr = type + "-" + style.svgAttr;
                                if (currentElement.getAttribute(attr)) {
                                    // fill-opacity or stroke-opacity has already been set by stroke or fill.
                                    continue;
                                }
                            }
                            // otherwise only update attribute if right type, and not svg default
                            currentElement.setAttribute(attr, "" + value);
                        }
                    }
                }
            }
        };
        /**
          * Returns the serialized value of the svg so far
          * @param fixNamedEntities - Standalone SVG doesn't support named entities, which document.createTextNode encodes.
          *                           If true, we attempt to find all named entities and encode it as a numeric entity.
          * @return serialized svg
          */
        SVGRenderingContext2D.prototype.get_serialized_svg = function (fixNamedEntities) {
            var e_3, _a;
            if (fixNamedEntities === void 0) {
                fixNamedEntities = false;
            }
            var serialized = new XMLSerializer().serializeToString(this.__root);
            if (fixNamedEntities) {
                try {
                    // loop over each named entity and replace with the proper equivalent.
                    for (var namedEntities_1 = (0, tslib_1.__values)(namedEntities), namedEntities_1_1 = namedEntities_1.next(); !namedEntities_1_1.done; namedEntities_1_1 = namedEntities_1.next()) {
                        var _b = (0, tslib_1.__read)(namedEntities_1_1.value, 2), key = _b[0], value = _b[1];
                        var regexp = new RegExp(key, "gi");
                        if (regexp.test(serialized)) {
                            serialized = serialized.replace(regexp, value);
                        }
                    }
                }
                catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                }
                finally {
                    try {
                        if (namedEntities_1_1 && !namedEntities_1_1.done && (_a = namedEntities_1.return))
                            _a.call(namedEntities_1);
                    }
                    finally {
                        if (e_3)
                            throw e_3.error;
                    }
                }
            }
            return serialized;
        };
        SVGRenderingContext2D.prototype.get_svg = function () {
            return this.__root;
        };
        /**
          * Will generate a group tag.
          */
        SVGRenderingContext2D.prototype.save = function () {
            this.__stack.push({
                transform: this._transform,
                clip_path: this._clip_path,
                attributes: this.__getStyleState(),
            });
            this._transform = this._transform.clone();
        };
        /**
          * Sets current element to parent, or just root if already root
          */
        SVGRenderingContext2D.prototype.restore = function () {
            if (this.__stack.length == 0)
                return;
            var _a = this.__stack.pop(), transform = _a.transform, clip_path = _a.clip_path, attributes = _a.attributes;
            this._transform = transform;
            this._clip_path = clip_path;
            this.__applyStyleState(attributes);
        };
        SVGRenderingContext2D.prototype._apply_transform = function (element, transform) {
            if (transform === void 0) {
                transform = this._transform;
            }
            if (!transform.is_identity) {
                element.setAttribute("transform", transform.toString());
            }
        };
        /**
          *  scales the current element
          */
        SVGRenderingContext2D.prototype.scale = function (x, y) {
            if (!isFinite(x) || (y != null && !isFinite(y)))
                return;
            this._transform.scale(x, y !== null && y !== void 0 ? y : x);
        };
        /**
          * rotates the current element
          */
        SVGRenderingContext2D.prototype.rotate = function (angle) {
            if (!isFinite(angle))
                return;
            this._transform.rotate(angle);
        };
        /**
          * translates the current element
          */
        SVGRenderingContext2D.prototype.translate = function (x, y) {
            if (!isFinite(x + y))
                return;
            this._transform.translate(x, y);
        };
        /**
          * applies a transform to the current element
          */
        SVGRenderingContext2D.prototype.transform = function (a, b, c, d, e, f) {
            if (!isFinite(a + b + c + d + e + f))
                return;
            this._transform.transform(a, b, c, d, e, f);
        };
        /**
          * Create a new Path Element
          */
        SVGRenderingContext2D.prototype.beginPath = function () {
            // Note that there is only one current default path, it is not part of the drawing state.
            // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path
            this.__currentDefaultPath = "";
            this.__currentPosition = null;
            this.__init_element();
        };
        SVGRenderingContext2D.prototype.__init_element = function () {
            var path = this.__createElement("path", {}, true);
            this.__root.appendChild(path);
            this.__currentElement = path;
        };
        /**
          * Helper function to apply currentDefaultPath to current path element
          */
        SVGRenderingContext2D.prototype.__applyCurrentDefaultPath = function () {
            var currentElement = this.__currentElement;
            if (currentElement.nodeName === "path") {
                currentElement.setAttribute("d", this.__currentDefaultPath);
            }
            else {
                console.error("Attempted to apply path command to node", currentElement.nodeName);
            }
        };
        /**
          * Helper function to add path command
          */
        SVGRenderingContext2D.prototype.__addPathCommand = function (x, y, path) {
            var separator = !this.__currentDefaultPath ? "" : " ";
            this.__currentDefaultPath += separator + path;
            this.__currentPosition = { x: x, y: y };
        };
        Object.defineProperty(SVGRenderingContext2D.prototype, "_hasCurrentDefaultPath", {
            get: function () {
                return !!this.__currentDefaultPath;
            },
            enumerable: false,
            configurable: true
        });
        /**
          * Adds the move command to the current path element,
          * if the currentPathElement is not empty create a new path element
          */
        SVGRenderingContext2D.prototype.moveTo = function (x, y) {
            if (!isFinite(x + y))
                return;
            var el = this.__currentElement;
            if (!el || el.nodeName !== "path") {
                this.beginPath();
            }
            // creates a new subpath with the given point
            var _a = (0, tslib_1.__read)(this._transform.apply(x, y), 2), tx = _a[0], ty = _a[1];
            this.__addPathCommand(tx, ty, "M " + tx + " " + ty);
        };
        /**
          * Closes the current path
          */
        SVGRenderingContext2D.prototype.closePath = function () {
            if (this._hasCurrentDefaultPath) {
                this.__addPathCommand(NaN, NaN, "Z");
            }
        };
        /**
          * Adds a line to command
          */
        SVGRenderingContext2D.prototype.lineTo = function (x, y) {
            if (!isFinite(x + y))
                return;
            if (!this._hasCurrentDefaultPath)
                this.moveTo(x, y);
            else {
                var _a = (0, tslib_1.__read)(this._transform.apply(x, y), 2), tx = _a[0], ty = _a[1];
                this.__addPathCommand(tx, ty, "L " + tx + " " + ty);
            }
        };
        /**
          * Add a bezier command
          */
        SVGRenderingContext2D.prototype.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
            if (!isFinite(cp1x + cp1y + cp2x + cp2y + x + y))
                return;
            var _a = (0, tslib_1.__read)(this._transform.apply(x, y), 2), tx = _a[0], ty = _a[1];
            var _b = (0, tslib_1.__read)(this._transform.apply(cp1x, cp1y), 2), tcp1x = _b[0], tcp1y = _b[1];
            var _c = (0, tslib_1.__read)(this._transform.apply(cp2x, cp2y), 2), tcp2x = _c[0], tcp2y = _c[1];
            this.__addPathCommand(tx, ty, "C " + tcp1x + " " + tcp1y + " " + tcp2x + " " + tcp2y + " " + tx + " " + ty);
        };
        /**
          * Adds a quadratic curve to command
          */
        SVGRenderingContext2D.prototype.quadraticCurveTo = function (cpx, cpy, x, y) {
            if (!isFinite(cpx + cpy + x + y))
                return;
            var _a = (0, tslib_1.__read)(this._transform.apply(x, y), 2), tx = _a[0], ty = _a[1];
            var _b = (0, tslib_1.__read)(this._transform.apply(cpx, cpy), 2), tcpx = _b[0], tcpy = _b[1];
            this.__addPathCommand(tx, ty, "Q " + tcpx + " " + tcpy + " " + tx + " " + ty);
        };
        /**
          * Adds the arcTo to the current path
          *
          * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto
          */
        SVGRenderingContext2D.prototype.arcTo = function (x1, y1, x2, y2, radius) {
            if (!isFinite(x1 + y1 + x2 + y2 + radius))
                return;
            // Let the point (x0, y0) be the last point in the subpath.
            if (this.__currentPosition == null)
                return;
            var x0 = this.__currentPosition.x;
            var y0 = this.__currentPosition.y;
            // Negative values for radius must cause the implementation to throw an IndexSizeError exception.
            if (radius < 0) {
                throw new Error("IndexSizeError: The radius provided (" + radius + ") is negative.");
            }
            // If the point (x0, y0) is equal to the point (x1, y1),
            // or if the point (x1, y1) is equal to the point (x2, y2),
            // or if the radius radius is zero,
            // then the method must add the point (x1, y1) to the subpath,
            // and connect that point to the previous point (x0, y0) by a straight line.
            if (((x0 === x1) && (y0 === y1)) || ((x1 === x2) && (y1 === y2)) || (radius === 0)) {
                this.lineTo(x1, y1);
                return;
            }
            function normalize(_a) {
                var _b = (0, tslib_1.__read)(_a, 2), x = _b[0], y = _b[1];
                var len = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
                return [x / len, y / len];
            }
            // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line,
            // then the method must add the point (x1, y1) to the subpath,
            // and connect that point to the previous point (x0, y0) by a straight line.
            var unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]);
            var unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]);
            if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) {
                this.lineTo(x1, y1);
                return;
            }
            // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius,
            // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1),
            // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1), and crosses the point (x2, y2).
            // The points at which this circle touches these two lines are called the start and end tangent points respectively.
            // note that both vectors are unit vectors, so the length is 1
            var cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]);
            var theta = Math.acos(Math.abs(cos));
            // Calculate origin
            var unit_vec_p1_origin = normalize([
                unit_vec_p1_p0[0] + unit_vec_p1_p2[0],
                unit_vec_p1_p0[1] + unit_vec_p1_p2[1],
            ]);
            var len_p1_origin = radius / Math.sin(theta / 2);
            var x = x1 + len_p1_origin * unit_vec_p1_origin[0];
            var y = y1 + len_p1_origin * unit_vec_p1_origin[1];
            // Calculate start angle and end angle
            // rotate 90deg clockwise (note that y axis points to its down)
            var unit_vec_origin_start_tangent = [
                -unit_vec_p1_p0[1],
                unit_vec_p1_p0[0],
            ];
            // rotate 90deg counter clockwise (note that y axis points to its down)
            var unit_vec_origin_end_tangent = [
                unit_vec_p1_p2[1],
                -unit_vec_p1_p2[0],
            ];
            function getAngle(vector) {
                // get angle (clockwise) between vector and (1, 0)
                var x = vector[0];
                var y = vector[1];
                if (y >= 0) { // note that y axis points to its down
                    return Math.acos(x);
                }
                else {
                    return -Math.acos(x);
                }
            }
            var startAngle = getAngle(unit_vec_origin_start_tangent);
            var endAngle = getAngle(unit_vec_origin_end_tangent);
            // Connect the point (x0, y0) to the start tangent point by a straight line
            this.lineTo(x + unit_vec_origin_start_tangent[0] * radius, y + unit_vec_origin_start_tangent[1] * radius);
            // Connect the start tangent point to the end tangent point by arc
            // and adding the end tangent point to the subpath.
            this.arc(x, y, radius, startAngle, endAngle);
        };
        /**
          * Sets the stroke property on the current element
          */
        SVGRenderingContext2D.prototype.stroke = function () {
            if (this.__currentElement.nodeName === "path") {
                this.__currentElement.setAttribute("paint-order", "fill");
            }
            this.__applyCurrentDefaultPath();
            this.__applyStyleToCurrentElement("stroke");
            if (this._clip_path != null) {
                this.__currentElement.setAttribute("clip-path", this._clip_path);
            }
        };
        SVGRenderingContext2D.prototype.fill = function (path_or_fill_rule, fill_rule) {
            var path = null;
            if (path_or_fill_rule instanceof Path2D)
                path = path_or_fill_rule;
            else if ((path_or_fill_rule == "evenodd" || path_or_fill_rule == "nonzero" || path_or_fill_rule == null) && fill_rule == null)
                fill_rule = path_or_fill_rule;
            else
                throw new Error("invalid arguments");
            if (path != null)
                throw new Error("not implemented");
            // XXX: hack (?) to allow fill and hatch visuals on same canvas path
            if (this.__currentElement.getAttribute("fill") != "none") {
                this.__init_element();
            }
            if (this.__currentElement.nodeName === "path") {
                this.__currentElement.setAttribute("paint-order", "stroke");
            }
            this.__applyCurrentDefaultPath();
            this.__applyStyleToCurrentElement("fill");
            if (fill_rule != null) {
                this.__currentElement.setAttribute("fill-rule", fill_rule);
            }
            if (this._clip_path != null) {
                this.__currentElement.setAttribute("clip-path", this._clip_path);
            }
        };
        /**
          *  Adds a rectangle to the path.
          */
        SVGRenderingContext2D.prototype.rect = function (x, y, width, height) {
            if (!isFinite(x + y + width + height))
                return;
            this.moveTo(x, y);
            this.lineTo(x + width, y);
            this.lineTo(x + width, y + height);
            this.lineTo(x, y + height);
            this.lineTo(x, y);
        };
        /**
          * adds a rectangle element
          */
        SVGRenderingContext2D.prototype.fillRect = function (x, y, width, height) {
            if (!isFinite(x + y + width + height))
                return;
            this.beginPath();
            this.rect(x, y, width, height);
            this.fill();
        };
        /**
          * Draws a rectangle with no fill
          * @param x
          * @param y
          * @param width
          * @param height
          */
        SVGRenderingContext2D.prototype.strokeRect = function (x, y, width, height) {
            if (!isFinite(x + y + width + height))
                return;
            this.beginPath();
            this.rect(x, y, width, height);
            this.stroke();
        };
        /**
          * Clear entire canvas:
          * 1. save current transforms
          * 2. remove all the childNodes of the root g element
          */
        SVGRenderingContext2D.prototype.__clearCanvas = function () {
            (0, dom_1.empty)(this.__defs);
            (0, dom_1.empty)(this.__root);
            this.__root.appendChild(this.__defs);
            this.__currentElement = this.__root;
        };
        /**
          * "Clears" a canvas by just drawing a white rectangle in the current group.
          */
        SVGRenderingContext2D.prototype.clearRect = function (x, y, width, height) {
            if (!isFinite(x + y + width + height))
                return;
            if (x === 0 && y === 0 && width === this.width && height === this.height) {
                this.__clearCanvas();
                return;
            }
            var rect = this.__createElement("rect", { x: x, y: y, width: width, height: height, fill: "#FFFFFF" }, true);
            this._apply_transform(rect);
            this.__root.appendChild(rect);
        };
        /**
          * Adds a linear gradient to a defs tag.
          * Returns a canvas gradient object that has a reference to it's parent def
          */
        SVGRenderingContext2D.prototype.createLinearGradient = function (x1, y1, x2, y2) {
            if (!isFinite(x1 + y1 + x2 + y2))
                throw new Error("The provided double value is non-finite");
            var _a = (0, tslib_1.__read)(this._transform.apply(x1, y1), 2), tx1 = _a[0], ty1 = _a[1];
            var _b = (0, tslib_1.__read)(this._transform.apply(x2, y2), 2), tx2 = _b[0], ty2 = _b[1];
            var grad = this.__createElement("linearGradient", {
                id: this._random_string(),
                x1: tx1 + "px",
                x2: tx2 + "px",
                y1: ty1 + "px",
                y2: ty2 + "px",
                gradientUnits: "userSpaceOnUse",
            }, false);
            this.__defs.appendChild(grad);
            return new CanvasGradient(grad, this);
        };
        /**
          * Adds a radial gradient to a defs tag.
          * Returns a canvas gradient object that has a reference to it's parent def
          */
        SVGRenderingContext2D.prototype.createRadialGradient = function (x0, y0, r0, x1, y1, r1) {
            if (!isFinite(x0 + y0 + r0 + x1 + y1 + r1))
                throw new Error("The provided double value is non-finite");
            var _a = (0, tslib_1.__read)(this._transform.apply(x0, y0), 2), tx0 = _a[0], ty0 = _a[1];
            var _b = (0, tslib_1.__read)(this._transform.apply(x1, y1), 2), tx1 = _b[0], ty1 = _b[1];
            var grad = this.__createElement("radialGradient", {
                id: this._random_string(),
                cx: tx1 + "px",
                cy: ty1 + "px",
                r: r1 + "px",
                r0: r0 + "px",
                fx: tx0 + "px",
                fy: ty0 + "px",
                gradientUnits: "userSpaceOnUse",
            }, false);
            this.__defs.appendChild(grad);
            return new CanvasGradient(grad, this);
        };
        /**
          * Parses the font string and returns svg mapping
          */
        SVGRenderingContext2D.prototype.__parseFont = function () {
            var _a, _b, _c, _d, _e;
            var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z0-9]+?)\s*$/i;
            var fontPart = regex.exec(this.font);
            var data = {
                style: (_a = fontPart[1]) !== null && _a !== void 0 ? _a : "normal",
                size: (_b = fontPart[4]) !== null && _b !== void 0 ? _b : "10px",
                family: (_c = fontPart[6]) !== null && _c !== void 0 ? _c : "sans-serif",
                weight: (_d = fontPart[3]) !== null && _d !== void 0 ? _d : "normal",
                decoration: (_e = fontPart[2]) !== null && _e !== void 0 ? _e : "normal",
            };
            return data;
        };
        /**
          * Fills or strokes text
          */
        SVGRenderingContext2D.prototype.__applyText = function (text, x, y, action) {
            var _this = this;
            var font = this.__parseFont();
            var text_el = this.__createElement("text", {
                "font-family": font.family,
                "font-size": font.size,
                "font-style": font.style,
                "font-weight": font.weight,
                "text-decoration": font.decoration,
                x: x,
                y: y,
                "text-anchor": getTextAnchor(this.textAlign),
                "dominant-baseline": getDominantBaseline(this.textBaseline),
            }, true);
            text_el.appendChild(this.__document.createTextNode(text));
            this._apply_transform(text_el);
            this.__currentElement = text_el;
            this.__applyStyleToCurrentElement(action);
            var el = (function () {
                if (_this._clip_path != null) {
                    var g = _this.__createElement("g");
                    g.setAttribute("clip-path", _this._clip_path);
                    g.appendChild(text_el);
                    return g;
                }
                else
                    return text_el;
            })();
            this.__root.appendChild(el);
        };
        /**
          * Creates a text element, in position x,y
          */
        SVGRenderingContext2D.prototype.fillText = function (text, x, y) {
            if (text == null || !isFinite(x + y))
                return;
            this.__applyText(text, x, y, "fill");
        };
        /**
          * Strokes text
          */
        SVGRenderingContext2D.prototype.strokeText = function (text, x, y) {
            if (text == null || !isFinite(x + y))
                return;
            this.__applyText(text, x, y, "stroke");
        };
        /**
          * No need to implement this for svg.
          */
        SVGRenderingContext2D.prototype.measureText = function (text) {
            this.__ctx.font = this.font;
            return this.__ctx.measureText(text);
        };
        SVGRenderingContext2D.prototype.arc = function (x, y, radius, start_angle, end_angle, counterclockwise) {
            if (counterclockwise === void 0) {
                counterclockwise = false;
            }
            this.ellipse(x, y, radius, radius, 0, start_angle, end_angle, counterclockwise);
        };
        SVGRenderingContext2D.prototype.ellipse = function (x, y, radius_x, radius_y, rotation, start_angle, end_angle, counterclockwise) {
            if (counterclockwise === void 0) {
                counterclockwise = false;
            }
            if (!isFinite(x + y + radius_x + radius_y + rotation + start_angle + end_angle))
                return;
            if (radius_x < 0 || radius_y < 0)
                throw new DOMException("IndexSizeError, radius can't be negative");
            start_angle = start_angle % (2 * Math.PI);
            end_angle = end_angle % (2 * Math.PI);
            if (start_angle === end_angle) {
                // circle time! subtract some of the angle so svg is happy (svg elliptical arc can't draw a full circle)
                end_angle = ((end_angle + (2 * Math.PI)) - 0.001 * (counterclockwise ? -1 : 1)) % (2 * Math.PI);
            }
            var end_x = x + radius_x * Math.cos(end_angle);
            var end_y = y + radius_y * Math.sin(end_angle);
            var start_x = x + radius_x * Math.cos(start_angle);
            var start_y = y + radius_y * Math.sin(start_angle);
            var sweep_flag = counterclockwise ? 0 : 1;
            var large_arc_flag = 0;
            var diff = end_angle - start_angle;
            // https://github.com/gliffy/canvas2svg/issues/4
            if (diff < 0) {
                diff += 2 * Math.PI;
            }
            if (counterclockwise) {
                large_arc_flag = diff > Math.PI ? 0 : 1;
            }
            else {
                large_arc_flag = diff > Math.PI ? 1 : 0;
            }
            this.lineTo(start_x, start_y);
            var _a = (0, tslib_1.__read)(this._transform.apply(end_x, end_y), 2), tend_x = _a[0], tend_y = _a[1];
            // Canvas ellipse defines rotation in radians and SVG elliptical arc is defined in degrees
            var rotation_in_degrees = rotation * 180 / Math.PI;
            this.__addPathCommand(tend_x, tend_y, "A " + radius_x + " " + radius_y + " " + rotation_in_degrees + " " + large_arc_flag + " " + sweep_flag + " " + tend_x + " " + tend_y);
        };
        /**
          * Generates a ClipPath from the clip command.
          */
        SVGRenderingContext2D.prototype.clip = function () {
            var clip_path = this.__createElement("clipPath");
            var id = this._random_string();
            this.__applyCurrentDefaultPath();
            clip_path.setAttribute("id", id);
            clip_path.appendChild(this.__currentElement);
            this.__defs.appendChild(clip_path);
            this._clip_path = "url(#" + id + ")";
        };
        /**
          * Draws a canvas, image or mock context to this canvas.
          * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support.
          * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage
          */
        SVGRenderingContext2D.prototype.drawImage = function (image) {
            var _a, _b, _c, e_4, _d, e_5, _e;
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            var dx, dy;
            var dw, dh;
            var sx, sy;
            var sw, sh;
            if (args.length == 2) {
                _a = (0, tslib_1.__read)(args, 2), dx = _a[0], dy = _a[1];
                if (!isFinite(dx + dy))
                    return;
                sx = 0;
                sy = 0;
                sw = image.width;
                sh = image.height;
                dw = sw;
                dh = sh;
            }
            else if (args.length == 4) {
                _b = (0, tslib_1.__read)(args, 4), dx = _b[0], dy = _b[1], dw = _b[2], dh = _b[3];
                if (!isFinite(dx + dy + dw + dh))
                    return;
                sx = 0;
                sy = 0;
                sw = image.width;
                sh = image.height;
            }
            else if (args.length === 8) {
                _c = (0, tslib_1.__read)(args, 8), sx = _c[0], sy = _c[1], sw = _c[2], sh = _c[3], dx = _c[4], dy = _c[5], dw = _c[6], dh = _c[7];
                if (!isFinite(sx + sy + sw + sh + dx + dy + dw + dh))
                    return;
            }
            else {
                throw new Error("Inavlid number of arguments passed to drawImage: " + arguments.length);
            }
            // parent, svg, defs, group, currentElement, svgImage, canvas, context, id
            var parent = this.__root;
            var transform = this._transform.clone().translate(dx, dy);
            if (image instanceof SVGRenderingContext2D || image instanceof SVGSVGElement) {
                // In the future we may want to clone nodes instead.
                // also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context.
                var svg_node = image instanceof SVGSVGElement ? image : image.get_svg();
                var svg = svg_node.cloneNode(true);
                var scope = void 0;
                if (transform.is_identity && this.globalAlpha == 1.0 && this._clip_path == null)
                    scope = parent;
                else {
                    scope = this.__createElement("g");
                    if (!transform.is_identity)
                        this._apply_transform(scope, transform);
                    if (this.globalAlpha != 1.0)
                        scope.setAttribute("opacity", "" + this.globalAlpha);
                    if (this._clip_path != null)
                        scope.setAttribute("clip-path", this._clip_path);
                    parent.appendChild(scope);
                }
                try {
                    for (var _f = (0, tslib_1.__values)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(svg.childNodes), false)), _g = _f.next(); !_g.done; _g = _f.next()) {
                        var child = _g.value;
                        if (child instanceof SVGDefsElement) {
                            try {
                                for (var _h = (e_5 = void 0, (0, tslib_1.__values)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(child.childNodes), false))), _j = _h.next(); !_j.done; _j = _h.next()) {
                                    var def = _j.value;
                                    if (def instanceof Element) {
                                        var id = def.getAttribute("id");
                                        this.__ids.add(id);
                                        this.__defs.appendChild(def.cloneNode(true));
                                    }
                                }
                            }
                            catch (e_5_1) {
                                e_5 = { error: e_5_1 };
                            }
                            finally {
                                try {
                                    if (_j && !_j.done && (_e = _h.return))
                                        _e.call(_h);
                                }
                                finally {
                                    if (e_5)
                                        throw e_5.error;
                                }
                            }
                        }
                        else {
                            scope.appendChild(child.cloneNode(true));
                        }
                    }
                }
                catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                }
                finally {
                    try {
                        if (_g && !_g.done && (_d = _f.return))
                            _d.call(_f);
                    }
                    finally {
                        if (e_4)
                            throw e_4.error;
                    }
                }
            }
            else if (image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                var svgImage = this.__createElement("image");
                svgImage.setAttribute("width", "" + dw);
                svgImage.setAttribute("height", "" + dh);
                svgImage.setAttribute("preserveAspectRatio", "none");
                if (this.globalAlpha != 1.0)
                    svgImage.setAttribute("opacity", "" + this.globalAlpha);
                if (sx || sy || sw !== image.width || sh !== image.height) {
                    // crop the image using a temporary canvas
                    var canvas = this.__document.createElement("canvas");
                    canvas.width = dw;
                    canvas.height = dh;
                    var context = canvas.getContext("2d");
                    context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh);
                    image = canvas;
                }
                this._apply_transform(svgImage, transform);
                var url = image instanceof HTMLCanvasElement ? image.toDataURL() : image.getAttribute("src");
                svgImage.setAttribute("href", url);
                if (this._clip_path != null) {
                    var scope = this.__createElement("g");
                    scope.setAttribute("clip-path", this._clip_path);
                    scope.appendChild(svgImage);
                    parent.appendChild(scope);
                }
                else
                    parent.appendChild(svgImage);
            }
            else if (image instanceof HTMLCanvasElement) {
                var svgImage = this.__createElement("image");
                svgImage.setAttribute("width", "" + dw);
                svgImage.setAttribute("height", "" + dh);
                svgImage.setAttribute("preserveAspectRatio", "none");
                if (this.globalAlpha != 1.0)
                    svgImage.setAttribute("opacity", "" + this.globalAlpha);
                // draw canvas onto temporary canvas so that smoothing can be handled
                var canvas = this.__document.createElement("canvas");
                canvas.width = dw;
                canvas.height = dh;
                var context = canvas.getContext("2d");
                context.imageSmoothingEnabled = false;
                context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh);
                image = canvas;
                this._apply_transform(svgImage, transform);
                svgImage.setAttribute("href", image.toDataURL());
                if (this._clip_path != null) {
                    var scope = this.__createElement("g");
                    scope.setAttribute("clip-path", this._clip_path);
                    scope.appendChild(svgImage);
                    parent.appendChild(scope);
                }
                else
                    parent.appendChild(svgImage);
            }
        };
        /**
          * Generates a pattern tag
          */
        SVGRenderingContext2D.prototype.createPattern = function (image, _repetition) {
            var e_6, _a, e_7, _b;
            var pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern");
            var id = this._random_string();
            pattern.setAttribute("id", id);
            pattern.setAttribute("width", "" + this._to_number(image.width));
            pattern.setAttribute("height", "" + this._to_number(image.height));
            pattern.setAttribute("patternUnits", "userSpaceOnUse");
            if (image instanceof HTMLCanvasElement || image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                var img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image");
                var url = image instanceof HTMLCanvasElement ? image.toDataURL() : image.getAttribute("src");
                img.setAttribute("href", url);
                pattern.appendChild(img);
                this.__defs.appendChild(pattern);
            }
            else if (image instanceof SVGRenderingContext2D) {
                try {
                    for (var _c = (0, tslib_1.__values)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(image.__root.childNodes), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var child = _d.value;
                        if (!(child instanceof SVGDefsElement)) {
                            pattern.appendChild(child.cloneNode(true));
                        }
                    }
                }
                catch (e_6_1) {
                    e_6 = { error: e_6_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_a = _c.return))
                            _a.call(_c);
                    }
                    finally {
                        if (e_6)
                            throw e_6.error;
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else if (image instanceof SVGSVGElement) {
                try {
                    for (var _e = (0, tslib_1.__values)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(image.childNodes), false)), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var child = _f.value;
                        if (!(child instanceof SVGDefsElement)) {
                            pattern.appendChild(child.cloneNode(true));
                        }
                    }
                }
                catch (e_7_1) {
                    e_7 = { error: e_7_1 };
                }
                finally {
                    try {
                        if (_f && !_f.done && (_b = _e.return))
                            _b.call(_e);
                    }
                    finally {
                        if (e_7)
                            throw e_7.error;
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else {
                throw new Error("unsupported");
            }
            return new CanvasPattern(pattern, this);
        };
        SVGRenderingContext2D.prototype.getLineDash = function () {
            var lineDash = this.lineDash;
            if ((0, types_1.isString)(lineDash))
                return lineDash.split(",").map(function (v) { return parseInt(v); });
            else if (lineDash == null)
                return [];
            else
                return lineDash;
        };
        SVGRenderingContext2D.prototype.setLineDash = function (segments) {
            if (segments && segments.length > 0)
                this.lineDash = segments.join(",");
            else
                this.lineDash = null;
        };
        SVGRenderingContext2D.prototype._to_number = function (val) {
            return (0, types_1.isNumber)(val) ? val : val.baseVal.value;
        };
        SVGRenderingContext2D.prototype.getTransform = function () {
            return this._transform.to_DOMMatrix();
        };
        SVGRenderingContext2D.prototype.setTransform = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            var matrix;
            if ((0, types_1.isNumber)(args[0]))
                matrix = new DOMMatrix(args);
            else if (args[0] instanceof DOMMatrix)
                matrix = args[0];
            else
                matrix = new DOMMatrix(Object.values(!args[0]));
            this._transform = affine_1.AffineTransform.from_DOMMatrix(matrix);
        };
        SVGRenderingContext2D.prototype.resetTransform = function () {
            this._transform = new affine_1.AffineTransform();
        };
        SVGRenderingContext2D.prototype.isPointInPath = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
            throw new Error("not implemented");
        };
        SVGRenderingContext2D.prototype.isPointInStroke = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
            throw new Error("not implemented");
        };
        SVGRenderingContext2D.prototype.createImageData = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
            throw new Error("not implemented");
        };
        SVGRenderingContext2D.prototype.getImageData = function (_sx, _sy, _sw, _sh) {
            throw new Error("not implemented");
        };
        SVGRenderingContext2D.prototype.putImageData = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
            throw new Error("not implemented");
        };
        SVGRenderingContext2D.prototype.drawFocusIfNeeded = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
            throw new Error("not implemented");
        };
        SVGRenderingContext2D.prototype.scrollPathIntoView = function () {
            var _args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                _args[_i] = arguments[_i];
            }
            throw new Error("not implemented");
        };
        return SVGRenderingContext2D;
    }());
    exports.SVGRenderingContext2D = SVGRenderingContext2D;
    SVGRenderingContext2D.__name__ = "SVGRenderingContext2D";
    //__currentElementsToStyle: {element: SVGElement, children: SVGElement[]} | null = null
    SVGRenderingContext2D.__random = random_1.random;
},
/* core/util/random.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var MAX_INT32 = 2147483647;
    // Park-Miller LCG
    var Random = /** @class */ (function () {
        function Random(seed) {
            this.seed = seed % MAX_INT32;
            if (this.seed <= 0)
                this.seed += MAX_INT32 - 1;
        }
        Random.prototype.integer = function () {
            this.seed = (48271 * this.seed) % MAX_INT32;
            return this.seed;
        };
        Random.prototype.float = function () {
            return (this.integer() - 1) / (MAX_INT32 - 1);
        };
        Random.prototype.floats = function (n, a, b) {
            if (a === void 0) {
                a = 0;
            }
            if (b === void 0) {
                b = 1;
            }
            var result = new Array(n);
            for (var i = 0; i < n; i++) {
                result[i] = a + this.float() * (b - a);
            }
            return result;
        };
        Random.prototype.choices = function (n, items) {
            var k = items.length;
            var result = new Array(n);
            for (var i = 0; i < n; i++) {
                result[i] = items[this.integer() % k];
            }
            return result;
        };
        return Random;
    }());
    exports.Random = Random;
    Random.__name__ = "Random";
    exports.random = new Random(Date.now());
},
/* models/tools/actions/action_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var button_tool_1 = require(339) /* ../button_tool */;
    var signaling_1 = require(130) /* ../../../core/signaling */;
    var ActionToolButtonView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ActionToolButtonView, _super);
        function ActionToolButtonView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ActionToolButtonView.prototype._clicked = function () {
            this.model.do.emit(undefined);
        };
        return ActionToolButtonView;
    }(button_tool_1.ButtonToolButtonView));
    exports.ActionToolButtonView = ActionToolButtonView;
    ActionToolButtonView.__name__ = "ActionToolButtonView";
    var ActionToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ActionToolView, _super);
        function ActionToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ActionToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.do, function (arg) { return _this.doit(arg); });
        };
        return ActionToolView;
    }(button_tool_1.ButtonToolView));
    exports.ActionToolView = ActionToolView;
    ActionToolView.__name__ = "ActionToolView";
    var ActionTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ActionTool, _super);
        function ActionTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.button_view = ActionToolButtonView;
            _this.do = new signaling_1.Signal(_this, "do");
            return _this;
        }
        return ActionTool;
    }(button_tool_1.ButtonTool));
    exports.ActionTool = ActionTool;
    ActionTool.__name__ = "ActionTool";
},
/* models/tools/actions/help_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var action_tool_1 = require(353) /* ./action_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var HelpToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HelpToolView, _super);
        function HelpToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        HelpToolView.prototype.doit = function () {
            window.open(this.model.redirect);
        };
        return HelpToolView;
    }(action_tool_1.ActionToolView));
    exports.HelpToolView = HelpToolView;
    HelpToolView.__name__ = "HelpToolView";
    var HelpTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HelpTool, _super);
        function HelpTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Help";
            _this.icon = icons_css_1.tool_icon_help;
            return _this;
        }
        return HelpTool;
    }(action_tool_1.ActionTool));
    exports.HelpTool = HelpTool;
    _a = HelpTool;
    HelpTool.__name__ = "HelpTool";
    (function () {
        _a.prototype.default_view = HelpToolView;
        _a.define(function (_b) {
            var String = _b.String;
            return ({
                redirect: [String, "https://docs.bokeh.org/en/latest/docs/user_guide/tools.html"],
            });
        });
        _a.override({
            description: "Click the question mark to learn more about Bokeh plot tools.",
        });
        _a.register_alias("help", function () { return new HelpTool(); });
    })();
},
/* styles/logo.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.logo = "bk-logo";
    exports.grey = "bk-grey";
    exports.logo_small = "bk-logo-small";
    exports.logo_notebook = "bk-logo-notebook";
    exports.default = ".bk-root .bk-logo{margin:5px;position:relative;display:block;background-repeat:no-repeat;}.bk-root .bk-logo.bk-grey{filter:url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0'/></filter></svg>#grayscale\");filter:gray;-webkit-filter:grayscale(100%);}.bk-root .bk-logo-small{width:20px;height:20px;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAOkSURBVDiNjZRtaJVlGMd/1/08zzln5zjP1LWcU9N0NkN8m2CYjpgQYQXqSs0I84OLIC0hkEKoPtiH3gmKoiJDU7QpLgoLjLIQCpEsNJ1vqUOdO7ppbuec5+V+rj4ctwzd8IIbbi6u+8f1539dt3A78eXC7QizUF7gyV1fD1Yqg4JWz84yffhm0qkFqBogB9rM8tZdtwVsPUhWhGcFJngGeWrPzHm5oaMmkfEg1usvLFyc8jLRqDOMru7AyC8saQr7GG7f5fvDeH7Ej8CM66nIF+8yngt6HWaKh7k49Soy9nXurCi1o3qUbS3zWfrYeQDTB/Qj6kX6Ybhw4B+bOYoLKCC9H3Nu/leUTZ1JdRWkkn2ldcCamzrcf47KKXdAJllSlxAOkRgyHsGC/zRday5Qld9DyoM4/q/rUoy/CXh3jzOu3bHUVZeU+DEn8FInkPBFlu3+nW3Nw0mk6vCDiWg8CeJaxEwuHS3+z5RgY+YBR6V1Z1nxSOfoaPa4LASWxxdNp+VWTk7+4vzaou8v8PN+xo+KY2xsw6une2frhw05CTYOmQvsEhjhWjn0bmXPjpE1+kplmmkP3suftwTubK9Vq22qKmrBhpY4jvd5afdRA3wGjFAgcnTK2s4hY0/GPNIb0nErGMCRxWOOX64Z8RAC4oCXdklmEvcL8o0BfkNK4lUg9HTl+oPlQxdNo3Mg4Nv175e/1LDGzZen30MEjRUtmXSfiTVu1kK8W4txyV6BMKlbgk3lMwYCiusNy9fVfvvwMxv8Ynl6vxoByANLTWplvuj/nF9m2+PDtt1eiHPBr1oIfhCChQMBw6Aw0UulqTKZdfVvfG7VcfIqLG9bcldL/+pdWTLxLUy8Qq38heUIjh4XlzZxzQm19lLFlr8vdQ97rjZVOLf8nclzckbcD4wxXMidpX30sFd37Fv/GtwwhzhxGVAprjbg0gCAEeIgwCZyTV2Z1REEW8O4py0wsjeloKoMr6iCY6dP92H6Vw/oTyICIthibxjm/DfN9lVz8IqtqKYLUXfoKVMVQVVJOElGjrnnUt9T9wbgp8AyYKaGlqingHZU/uG2NTZSVqwHQTWkx9hxjkpWDaCg6Ckj5qebgBVbT3V3NNXMSiWSDdGV3hrtzla7J+duwPOToIg42ChPQOQjspnSlp1V+Gjdged7+8UN5CRAV7a5EdFNwCjEaBR27b3W890TE7g24NAP/mMDXRWrGoFPQI9ls/MWO2dWFAar/xcOIImbbpA3zgAAAABJRU5ErkJggg==);}.bk-root .bk-logo-notebook{display:inline-block;vertical-align:middle;margin-right:5px;}";
},
/* models/annotations/tooltip.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var annotation_1 = require(155) /* ./annotation */;
    var enums_1 = require(135) /* ../../core/enums */;
    var dom_1 = require(158) /* ../../core/dom */;
    var tooltips_css_1 = (0, tslib_1.__importStar)(require(357) /* ../../styles/tooltips.css */), tooltips = tooltips_css_1;
    var arrow_size = 10; // XXX: keep in sync with less
    var TooltipView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TooltipView, _super);
        function TooltipView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TooltipView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.el = (0, dom_1.div)({ class: tooltips.tooltip });
            (0, dom_1.undisplay)(this.el);
            this.plot_view.canvas_view.add_overlay(this.el);
        };
        TooltipView.prototype.remove = function () {
            (0, dom_1.remove)(this.el);
            _super.prototype.remove.call(this);
        };
        TooltipView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.content.change, function () { return _this.render(); });
            this.connect(this.model.properties.position.change, function () { return _this._reposition(); });
        };
        TooltipView.prototype.styles = function () {
            return (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(_super.prototype.styles.call(this)), false), [tooltips_css_1.default], false);
        };
        TooltipView.prototype.render = function () {
            if (!this.model.visible)
                (0, dom_1.undisplay)(this.el);
            _super.prototype.render.call(this);
        };
        TooltipView.prototype._render = function () {
            var content = this.model.content;
            if (content == null) {
                (0, dom_1.undisplay)(this.el);
                return;
            }
            (0, dom_1.empty)(this.el);
            (0, dom_1.classes)(this.el).toggle("bk-tooltip-custom", this.model.custom);
            this.el.appendChild(content);
            if (this.model.show_arrow)
                this.el.classList.add(tooltips.tooltip_arrow);
        };
        TooltipView.prototype._reposition = function () {
            var _this = this;
            var position = this.model.position;
            if (position == null) {
                (0, dom_1.undisplay)(this.el);
                return;
            }
            var _b = (0, tslib_1.__read)(position, 2), sx = _b[0], sy = _b[1];
            var side = (function () {
                var area = _this.parent.layout.bbox.relative();
                var attachment = _this.model.attachment;
                switch (attachment) {
                    case "horizontal":
                        return sx < area.hcenter ? "right" : "left";
                    case "vertical":
                        return sy < area.vcenter ? "below" : "above";
                    default:
                        return attachment;
                }
            })();
            this.el.classList.remove(tooltips.right);
            this.el.classList.remove(tooltips.left);
            this.el.classList.remove(tooltips.above);
            this.el.classList.remove(tooltips.below);
            (0, dom_1.display)(this.el); // XXX: {offset,client}Width() gives 0 when display="none"
            // slightly confusing: side "left" (for example) is relative to point that
            // is being annotated but CS class ".bk-left" is relative to the tooltip itself
            var top;
            var left = null;
            var right = null;
            switch (side) {
                case "right":
                    this.el.classList.add(tooltips.left);
                    left = sx + (this.el.offsetWidth - this.el.clientWidth) + arrow_size;
                    top = sy - this.el.offsetHeight / 2;
                    break;
                case "left":
                    this.el.classList.add(tooltips.right);
                    right = (this.plot_view.layout.bbox.width - sx) + arrow_size;
                    top = sy - this.el.offsetHeight / 2;
                    break;
                case "below":
                    this.el.classList.add(tooltips.above);
                    top = sy + (this.el.offsetHeight - this.el.clientHeight) + arrow_size;
                    left = Math.round(sx - this.el.offsetWidth / 2);
                    break;
                case "above":
                    this.el.classList.add(tooltips.below);
                    top = sy - this.el.offsetHeight - arrow_size;
                    left = Math.round(sx - this.el.offsetWidth / 2);
                    break;
            }
            this.el.style.top = top + "px";
            this.el.style.left = left != null ? left + "px" : "auto";
            this.el.style.right = right != null ? right + "px" : "auto";
        };
        return TooltipView;
    }(annotation_1.AnnotationView));
    exports.TooltipView = TooltipView;
    TooltipView.__name__ = "TooltipView";
    var Tooltip = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Tooltip, _super);
        function Tooltip(attrs) {
            return _super.call(this, attrs) || this;
        }
        Tooltip.prototype.clear = function () {
            this.position = null;
        };
        return Tooltip;
    }(annotation_1.Annotation));
    exports.Tooltip = Tooltip;
    _a = Tooltip;
    Tooltip.__name__ = "Tooltip";
    (function () {
        _a.prototype.default_view = TooltipView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                attachment: [enums_1.TooltipAttachment, "horizontal"],
                inner_only: [Boolean, true],
                show_arrow: [Boolean, true],
            });
        });
        _a.internal(function (_b) {
            var Boolean = _b.Boolean, Number = _b.Number, Tuple = _b.Tuple, Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                position: [Nullable(Tuple(Number, Number)), null],
                content: [Ref(HTMLElement), function () { return (0, dom_1.div)(); }],
                custom: [Boolean],
            });
        });
        _a.override({
            level: "overlay",
        });
    })();
},
/* styles/tooltips.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tooltip = "bk-tooltip";
    exports.left = "bk-left";
    exports.tooltip_arrow = "bk-tooltip-arrow";
    exports.right = "bk-right";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.tooltip_row_label = "bk-tooltip-row-label";
    exports.tooltip_row_value = "bk-tooltip-row-value";
    exports.tooltip_color_block = "bk-tooltip-color-block";
    exports.default = ".bk-root{}.bk-root .bk-tooltip{font-weight:300;font-size:12px;position:absolute;padding:5px;border:1px solid #e5e5e5;color:#2f2f2f;background-color:white;pointer-events:none;opacity:0.95;z-index:100;}.bk-root .bk-tooltip > div:not(:first-child){margin-top:5px;border-top:#e5e5e5 1px dashed;}.bk-root .bk-tooltip.bk-left.bk-tooltip-arrow::before{position:absolute;margin:-7px 0 0 0;top:50%;width:0;height:0;border-style:solid;border-width:7px 0 7px 0;border-color:transparent;content:\" \";display:block;left:-10px;border-right-width:10px;border-right-color:#909599;}.bk-root .bk-tooltip.bk-left::before{left:-10px;border-right-width:10px;border-right-color:#909599;}.bk-root .bk-tooltip.bk-right.bk-tooltip-arrow::after{position:absolute;margin:-7px 0 0 0;top:50%;width:0;height:0;border-style:solid;border-width:7px 0 7px 0;border-color:transparent;content:\" \";display:block;right:-10px;border-left-width:10px;border-left-color:#909599;}.bk-root .bk-tooltip.bk-right::after{right:-10px;border-left-width:10px;border-left-color:#909599;}.bk-root .bk-tooltip.bk-above::before{position:absolute;margin:0 0 0 -7px;left:50%;width:0;height:0;border-style:solid;border-width:0 7px 0 7px;border-color:transparent;content:\" \";display:block;top:-10px;border-bottom-width:10px;border-bottom-color:#909599;}.bk-root .bk-tooltip.bk-below::after{position:absolute;margin:0 0 0 -7px;left:50%;width:0;height:0;border-style:solid;border-width:0 7px 0 7px;border-color:transparent;content:\" \";display:block;bottom:-10px;border-top-width:10px;border-top-color:#909599;}.bk-root .bk-tooltip-row-label{text-align:right;color:#26aae1;}.bk-root .bk-tooltip-row-value{color:default;}.bk-root .bk-tooltip-color-block{width:12px;height:12px;margin-left:5px;margin-right:5px;outline:#dddddd solid 1px;display:inline-block;}";
},
/* models/annotations/whisker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var upper_lower_1 = require(230) /* ./upper_lower */;
    var arrow_head_1 = require(227) /* ./arrow_head */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var WhiskerView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WhiskerView, _super);
        function WhiskerView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        WhiskerView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var _b, lower_head, upper_head, _c, _d;
                return (0, tslib_1.__generator)(this, function (_e) {
                    switch (_e.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _e.sent();
                            _b = this.model, lower_head = _b.lower_head, upper_head = _b.upper_head;
                            if (!(lower_head != null))
                                return [3 /*break*/, 3];
                            _c = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(lower_head, { parent: this })];
                        case 2:
                            _c.lower_head = _e.sent();
                            _e.label = 3;
                        case 3:
                            if (!(upper_head != null))
                                return [3 /*break*/, 5];
                            _d = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(upper_head, { parent: this })];
                        case 4:
                            _d.upper_head = _e.sent();
                            _e.label = 5;
                        case 5: return [2 /*return*/];
                    }
                });
            });
        };
        WhiskerView.prototype.set_data = function (source) {
            var _b, _c;
            _super.prototype.set_data.call(this, source);
            (_b = this.lower_head) === null || _b === void 0 ? void 0 : _b.set_data(source);
            (_c = this.upper_head) === null || _c === void 0 ? void 0 : _c.set_data(source);
        };
        WhiskerView.prototype.paint = function (ctx) {
            if (this.visuals.line.doit) {
                for (var i = 0, end = this._lower_sx.length; i < end; i++) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.beginPath();
                    ctx.moveTo(this._lower_sx[i], this._lower_sy[i]);
                    ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
                    ctx.stroke();
                }
            }
            var angle = this.model.dimension == "height" ? 0 : Math.PI / 2;
            if (this.lower_head != null) {
                for (var i = 0, end = this._lower_sx.length; i < end; i++) {
                    ctx.save();
                    ctx.translate(this._lower_sx[i], this._lower_sy[i]);
                    ctx.rotate(angle + Math.PI);
                    this.lower_head.render(ctx, i);
                    ctx.restore();
                }
            }
            if (this.upper_head != null) {
                for (var i = 0, end = this._upper_sx.length; i < end; i++) {
                    ctx.save();
                    ctx.translate(this._upper_sx[i], this._upper_sy[i]);
                    ctx.rotate(angle);
                    this.upper_head.render(ctx, i);
                    ctx.restore();
                }
            }
        };
        return WhiskerView;
    }(upper_lower_1.UpperLowerView));
    exports.WhiskerView = WhiskerView;
    WhiskerView.__name__ = "WhiskerView";
    var Whisker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Whisker, _super);
        function Whisker(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Whisker;
    }(upper_lower_1.UpperLower));
    exports.Whisker = Whisker;
    _a = Whisker;
    Whisker.__name__ = "Whisker";
    (function () {
        _a.prototype.default_view = WhiskerView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(function (_b) {
            var Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                lower_head: [Nullable(Ref(arrow_head_1.ArrowHead)), function () { return new arrow_head_1.TeeHead({ size: 10 }); }],
                upper_head: [Nullable(Ref(arrow_head_1.ArrowHead)), function () { return new arrow_head_1.TeeHead({ size: 10 }); }],
            });
        });
        _a.override({
            level: "underlay",
        });
    })();
},
/* models/callbacks/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_1 = require(360) /* ./customjs */;
    __esExport("CustomJS", customjs_1.CustomJS);
    var open_url_1 = require(362) /* ./open_url */;
    __esExport("OpenURL", open_url_1.OpenURL);
},
/* models/callbacks/customjs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var callback_1 = require(361) /* ./callback */;
    var object_1 = require(128) /* ../../core/util/object */;
    var string_1 = require(149) /* ../../core/util/string */;
    var CustomJS = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomJS, _super);
        function CustomJS(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CustomJS.prototype, "names", {
            get: function () {
                return (0, object_1.keys)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomJS.prototype, "values", {
            get: function () {
                return (0, object_1.values)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomJS.prototype, "func", {
            get: function () {
                var code = (0, string_1.use_strict)(this.code);
                return new (Function.bind.apply(Function, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([void 0], (0, tslib_1.__read)(this.names), false), ["cb_obj", "cb_data", code], false)))();
            },
            enumerable: false,
            configurable: true
        });
        CustomJS.prototype.execute = function (cb_obj, cb_data) {
            if (cb_data === void 0) {
                cb_data = {};
            }
            return this.func.apply(cb_obj, this.values.concat(cb_obj, cb_data));
        };
        return CustomJS;
    }(callback_1.Callback));
    exports.CustomJS = CustomJS;
    _a = CustomJS;
    CustomJS.__name__ = "CustomJS";
    (function () {
        _a.define(function (_b) {
            var Unknown = _b.Unknown, String = _b.String, Dict = _b.Dict;
            return ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            });
        });
    })();
},
/* models/callbacks/callback.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../../model */;
    var Callback = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Callback, _super);
        function Callback(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Callback;
    }(model_1.Model));
    exports.Callback = Callback;
    Callback.__name__ = "Callback";
},
/* models/callbacks/open_url.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var callback_1 = require(361) /* ./callback */;
    var templating_1 = require(267) /* ../../core/util/templating */;
    var types_1 = require(125) /* ../../core/util/types */;
    var OpenURL = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(OpenURL, _super);
        function OpenURL(attrs) {
            return _super.call(this, attrs) || this;
        }
        OpenURL.prototype.navigate = function (url) {
            if (this.same_tab)
                window.location.href = url;
            else
                window.open(url);
        };
        OpenURL.prototype.execute = function (_cb_obj, _b) {
            var e_1, _c, e_2, _d;
            var _this = this;
            var source = _b.source;
            var open_url = function (i) {
                var url = (0, templating_1.replace_placeholders)(_this.url, source, i, undefined, undefined, encodeURI);
                if (!(0, types_1.isString)(url))
                    throw new Error("HTML output is not supported in this context");
                _this.navigate(url);
            };
            var selected = source.selected;
            try {
                for (var _e = (0, tslib_1.__values)(selected.indices), _f = _e.next(); !_f.done; _f = _e.next()) {
                    var i = _f.value;
                    open_url(i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_f && !_f.done && (_c = _e.return))
                        _c.call(_e);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            try {
                for (var _g = (0, tslib_1.__values)(selected.line_indices), _h = _g.next(); !_h.done; _h = _g.next()) {
                    var i = _h.value;
                    open_url(i);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_h && !_h.done && (_d = _g.return))
                        _d.call(_g);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            // TODO: multiline_indices: {[key: string]: number[]}
        };
        return OpenURL;
    }(callback_1.Callback));
    exports.OpenURL = OpenURL;
    _a = OpenURL;
    OpenURL.__name__ = "OpenURL";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, String = _b.String;
            return ({
                url: [String, "http://"],
                same_tab: [Boolean, false],
            });
        });
    })();
},
/* models/canvas/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var canvas_1 = require(364) /* ./canvas */;
    __esExport("Canvas", canvas_1.Canvas);
    var cartesian_frame_1 = require(241) /* ./cartesian_frame */;
    __esExport("CartesianFrame", cartesian_frame_1.CartesianFrame);
    var coordinates_1 = require(169) /* ./coordinates */;
    __esExport("CoordinateMapping", coordinates_1.CoordinateMapping);
},
/* models/canvas/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var has_props_1 = require(129) /* ../../core/has_props */;
    var dom_view_1 = require(341) /* ../../core/dom_view */;
    var logging_1 = require(134) /* ../../core/logging */;
    var dom_1 = require(158) /* ../../core/dom */;
    var enums_1 = require(135) /* ../../core/enums */;
    var object_1 = require(128) /* ../../core/util/object */;
    var ui_events_1 = require(365) /* ../../core/ui_events */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    var modules_1 = require(253) /* ../../core/util/modules */;
    var canvas_1 = require(350) /* ../../core/util/canvas */;
    function init_webgl() {
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var canvas, gl, webgl, regl_wrapper;
            return (0, tslib_1.__generator)(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        canvas = document.createElement("canvas");
                        gl = canvas.getContext("webgl", { premultipliedAlpha: true });
                        if (!(gl != null))
                            return [3 /*break*/, 2];
                        return [4 /*yield*/, (0, modules_1.load_module)(Promise.resolve().then(function () { return (0, tslib_1.__importStar)(require(525) /* ../glyphs/webgl */); }))];
                    case 1:
                        webgl = _b.sent();
                        if (webgl != null) {
                            regl_wrapper = webgl.get_regl(gl);
                            if (regl_wrapper.has_webgl) {
                                return [2 /*return*/, { canvas: canvas, regl_wrapper: regl_wrapper }];
                            }
                            else {
                                logging_1.logger.trace("WebGL is supported, but not the required extensions");
                            }
                        }
                        else {
                            logging_1.logger.trace("WebGL is supported, but bokehjs(.min).js bundle is not available");
                        }
                        return [3 /*break*/, 3];
                    case 2:
                        logging_1.logger.trace("WebGL is not supported");
                        _b.label = 3;
                    case 3: return [2 /*return*/, null];
                }
            });
        });
    }
    var global_webgl = (function () {
        var _global_webgl;
        return function () {
            return (0, tslib_1.__awaiter)(void 0, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!(_global_webgl !== undefined))
                                return [3 /*break*/, 1];
                            return [2 /*return*/, _global_webgl];
                        case 1: return [4 /*yield*/, init_webgl()];
                        case 2: return [2 /*return*/, _global_webgl = _b.sent()];
                    }
                });
            });
        };
    })();
    var style = {
        position: "absolute",
        top: "0",
        left: "0",
        width: "100%",
        height: "100%",
    };
    var CanvasView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CanvasView, _super);
        function CanvasView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.bbox = new bbox_1.BBox();
            _this.webgl = null;
            return _this;
        }
        CanvasView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.underlays_el = (0, dom_1.div)({ style: style });
            this.primary = this.create_layer();
            this.overlays = this.create_layer();
            this.overlays_el = (0, dom_1.div)({ style: style });
            this.events_el = (0, dom_1.div)({ class: "bk-canvas-events", style: style });
            var elements = [
                this.underlays_el,
                this.primary.el,
                this.overlays.el,
                this.overlays_el,
                this.events_el,
            ];
            (0, object_1.extend)(this.el.style, style);
            dom_1.append.apply(void 0, (0, tslib_1.__spreadArray)([this.el], (0, tslib_1.__read)(elements), false));
            this.ui_event_bus = new ui_events_1.UIEventBus(this);
        };
        CanvasView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var _b;
                return (0, tslib_1.__generator)(this, function (_c) {
                    switch (_c.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _c.sent();
                            if (!(this.model.output_backend == "webgl"))
                                return [3 /*break*/, 3];
                            _b = this;
                            return [4 /*yield*/, global_webgl()];
                        case 2:
                            _b.webgl = _c.sent();
                            _c.label = 3;
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        CanvasView.prototype.remove = function () {
            this.ui_event_bus.destroy();
            _super.prototype.remove.call(this);
        };
        CanvasView.prototype.add_underlay = function (el) {
            this.underlays_el.appendChild(el);
        };
        CanvasView.prototype.add_overlay = function (el) {
            this.overlays_el.appendChild(el);
        };
        CanvasView.prototype.add_event = function (el) {
            this.events_el.appendChild(el);
        };
        Object.defineProperty(CanvasView.prototype, "pixel_ratio", {
            get: function () {
                return this.primary.pixel_ratio; // XXX: primary
            },
            enumerable: false,
            configurable: true
        });
        CanvasView.prototype.resize = function (width, height) {
            this.bbox = new bbox_1.BBox({ left: 0, top: 0, width: width, height: height });
            this.primary.resize(width, height);
            this.overlays.resize(width, height);
        };
        CanvasView.prototype.prepare_webgl = function (frame_box) {
            // Prepare WebGL for a drawing pass
            var webgl = this.webgl;
            if (webgl != null) {
                // Sync canvas size
                var _b = this.bbox, width = _b.width, height = _b.height;
                webgl.canvas.width = this.pixel_ratio * width;
                webgl.canvas.height = this.pixel_ratio * height;
                var _c = (0, tslib_1.__read)(frame_box, 4), sx = _c[0], sy = _c[1], w = _c[2], h = _c[3];
                var _d = this.bbox, xview = _d.xview, yview = _d.yview;
                var vx = xview.compute(sx);
                var vy = yview.compute(sy + h);
                var ratio = this.pixel_ratio;
                webgl.regl_wrapper.set_scissor(ratio * vx, ratio * vy, ratio * w, ratio * h);
                this._clear_webgl();
            }
        };
        CanvasView.prototype.blit_webgl = function (ctx) {
            // This should be called when the ctx has no state except the HIDPI transform
            var webgl = this.webgl;
            if (webgl != null) {
                // Blit gl canvas into the 2D canvas. To do 1-on-1 blitting, we need
                // to remove the hidpi transform, then blit, then restore.
                // ctx.globalCompositeOperation = "source-over"  -> OK; is the default
                logging_1.logger.debug("Blitting WebGL canvas");
                ctx.restore();
                ctx.drawImage(webgl.canvas, 0, 0);
                // Set back hidpi transform
                ctx.save();
                if (this.model.hidpi) {
                    var ratio = this.pixel_ratio;
                    ctx.scale(ratio, ratio);
                    ctx.translate(0.5, 0.5);
                }
                this._clear_webgl();
            }
        };
        CanvasView.prototype._clear_webgl = function () {
            var webgl = this.webgl;
            if (webgl != null) {
                // Prepare GL for drawing
                var regl_wrapper = webgl.regl_wrapper, canvas = webgl.canvas;
                regl_wrapper.clear(canvas.width, canvas.height);
            }
        };
        CanvasView.prototype.compose = function () {
            var composite = this.create_layer();
            var _b = this.bbox, width = _b.width, height = _b.height;
            composite.resize(width, height);
            composite.ctx.drawImage(this.primary.canvas, 0, 0);
            composite.ctx.drawImage(this.overlays.canvas, 0, 0);
            return composite;
        };
        CanvasView.prototype.create_layer = function () {
            var _b = this.model, output_backend = _b.output_backend, hidpi = _b.hidpi;
            return new canvas_1.CanvasLayer(output_backend, hidpi);
        };
        CanvasView.prototype.to_blob = function () {
            return this.compose().to_blob();
        };
        return CanvasView;
    }(dom_view_1.DOMView));
    exports.CanvasView = CanvasView;
    CanvasView.__name__ = "CanvasView";
    var Canvas = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Canvas, _super);
        function Canvas(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Canvas;
    }(has_props_1.HasProps));
    exports.Canvas = Canvas;
    _a = Canvas;
    Canvas.__name__ = "Canvas";
    (function () {
        _a.prototype.default_view = CanvasView;
        _a.internal(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                hidpi: [Boolean, true],
                output_backend: [enums_1.OutputBackend, "canvas"],
            });
        });
    })();
},
/* core/ui_events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var hammerjs_1 = (0, tslib_1.__importDefault)(require(340) /* hammerjs */);
    var signaling_1 = require(130) /* ./signaling */;
    var logging_1 = require(134) /* ./logging */;
    var dom_1 = require(158) /* ./dom */;
    var events = (0, tslib_1.__importStar)(require(366) /* ./bokeh_events */);
    var wheel_1 = require(367) /* ./util/wheel */;
    var array_1 = require(126) /* ./util/array */;
    var types_1 = require(125) /* ./util/types */;
    var platform_1 = require(142) /* ./util/platform */;
    var menus_1 = require(345) /* ./util/menus */;
    function is_touch(event) {
        return typeof TouchEvent !== "undefined" && event instanceof TouchEvent;
    }
    var UIEventBus = /** @class */ (function () {
        function UIEventBus(canvas_view) {
            var _this = this;
            this.canvas_view = canvas_view;
            this.pan_start = new signaling_1.Signal(this, "pan:start");
            this.pan = new signaling_1.Signal(this, "pan");
            this.pan_end = new signaling_1.Signal(this, "pan:end");
            this.pinch_start = new signaling_1.Signal(this, "pinch:start");
            this.pinch = new signaling_1.Signal(this, "pinch");
            this.pinch_end = new signaling_1.Signal(this, "pinch:end");
            this.rotate_start = new signaling_1.Signal(this, "rotate:start");
            this.rotate = new signaling_1.Signal(this, "rotate");
            this.rotate_end = new signaling_1.Signal(this, "rotate:end");
            this.tap = new signaling_1.Signal(this, "tap");
            this.doubletap = new signaling_1.Signal(this, "doubletap");
            this.press = new signaling_1.Signal(this, "press");
            this.pressup = new signaling_1.Signal(this, "pressup");
            this.move_enter = new signaling_1.Signal(this, "move:enter");
            this.move = new signaling_1.Signal(this, "move");
            this.move_exit = new signaling_1.Signal(this, "move:exit");
            this.scroll = new signaling_1.Signal(this, "scroll");
            this.keydown = new signaling_1.Signal(this, "keydown");
            this.keyup = new signaling_1.Signal(this, "keyup");
            this.hammer = new hammerjs_1.default(this.hit_area, {
                touchAction: "auto",
                inputClass: hammerjs_1.default.TouchMouseInput, // https://github.com/bokeh/bokeh/issues/9187
            });
            this._prev_move = null;
            this._curr_pan = null;
            this._curr_pinch = null;
            this._curr_rotate = null;
            this._configure_hammerjs();
            // Mouse & keyboard events not handled through hammerjs
            // We can 'add and forget' these event listeners because this.hit_area is a DOM element
            // that will be thrown away when the view is removed
            this.hit_area.addEventListener("mousemove", function (e) { return _this._mouse_move(e); });
            this.hit_area.addEventListener("mouseenter", function (e) { return _this._mouse_enter(e); });
            this.hit_area.addEventListener("mouseleave", function (e) { return _this._mouse_exit(e); });
            this.hit_area.addEventListener("contextmenu", function (e) { return _this._context_menu(e); });
            this.hit_area.addEventListener("wheel", function (e) { return _this._mouse_wheel(e); });
            // But we MUST remove listeners registered on document or we'll leak memory: register
            // 'this' as the listener (it implements the event listener interface, i.e. handleEvent)
            // instead of an anonymous function so we can easily refer back to it for removing
            document.addEventListener("keydown", this);
            document.addEventListener("keyup", this);
            this.menu = new menus_1.ContextMenu([], {
                prevent_hide: function (event) { return event.button == 2 && event.target == _this.hit_area; },
            });
            this.hit_area.appendChild(this.menu.el);
        }
        Object.defineProperty(UIEventBus.prototype, "hit_area", {
            get: function () {
                return this.canvas_view.events_el;
            },
            enumerable: false,
            configurable: true
        });
        UIEventBus.prototype.destroy = function () {
            this.menu.remove();
            this.hammer.destroy();
            document.removeEventListener("keydown", this);
            document.removeEventListener("keyup", this);
        };
        UIEventBus.prototype.handleEvent = function (e) {
            if (e.type == "keydown")
                this._key_down(e);
            else if (e.type == "keyup")
                this._key_up(e);
        };
        UIEventBus.prototype._configure_hammerjs = function () {
            var _this = this;
            // This is to be able to distinguish double taps from single taps
            this.hammer.get("doubletap").recognizeWith("tap");
            this.hammer.get("tap").requireFailure("doubletap");
            this.hammer.get("doubletap").dropRequireFailure("tap");
            this.hammer.on("doubletap", function (e) { return _this._doubletap(e); });
            this.hammer.on("tap", function (e) { return _this._tap(e); });
            this.hammer.on("press", function (e) { return _this._press(e); });
            this.hammer.on("pressup", function (e) { return _this._pressup(e); });
            this.hammer.get("pan").set({ direction: hammerjs_1.default.DIRECTION_ALL });
            this.hammer.on("panstart", function (e) { return _this._pan_start(e); });
            this.hammer.on("pan", function (e) { return _this._pan(e); });
            this.hammer.on("panend", function (e) { return _this._pan_end(e); });
            this.hammer.get("pinch").set({ enable: true });
            this.hammer.on("pinchstart", function (e) { return _this._pinch_start(e); });
            this.hammer.on("pinch", function (e) { return _this._pinch(e); });
            this.hammer.on("pinchend", function (e) { return _this._pinch_end(e); });
            this.hammer.get("rotate").set({ enable: true });
            this.hammer.on("rotatestart", function (e) { return _this._rotate_start(e); });
            this.hammer.on("rotate", function (e) { return _this._rotate(e); });
            this.hammer.on("rotateend", function (e) { return _this._rotate_end(e); });
        };
        UIEventBus.prototype.register_tool = function (tool_view) {
            var _this = this;
            var et = tool_view.model.event_type;
            if (et != null) {
                if ((0, types_1.isString)(et))
                    this._register_tool(tool_view, et);
                else {
                    // Multi-tools should only registered shared events once
                    et.forEach(function (e, index) { return _this._register_tool(tool_view, e, index < 1); });
                }
            }
        };
        UIEventBus.prototype._register_tool = function (tool_view, et, shared) {
            if (shared === void 0) {
                shared = true;
            }
            var v = tool_view;
            var id = v.model.id;
            var conditionally = function (fn) {
                return function (arg) {
                    if (arg.id == id)
                        fn(arg.e);
                };
            };
            var unconditionally = function (fn) {
                return function (arg) {
                    fn(arg.e);
                };
            };
            switch (et) {
                case "pan": {
                    if (v._pan_start != null)
                        v.connect(this.pan_start, conditionally(v._pan_start.bind(v)));
                    if (v._pan != null)
                        v.connect(this.pan, conditionally(v._pan.bind(v)));
                    if (v._pan_end != null)
                        v.connect(this.pan_end, conditionally(v._pan_end.bind(v)));
                    break;
                }
                case "pinch": {
                    if (v._pinch_start != null)
                        v.connect(this.pinch_start, conditionally(v._pinch_start.bind(v)));
                    if (v._pinch != null)
                        v.connect(this.pinch, conditionally(v._pinch.bind(v)));
                    if (v._pinch_end != null)
                        v.connect(this.pinch_end, conditionally(v._pinch_end.bind(v)));
                    break;
                }
                case "rotate": {
                    if (v._rotate_start != null)
                        v.connect(this.rotate_start, conditionally(v._rotate_start.bind(v)));
                    if (v._rotate != null)
                        v.connect(this.rotate, conditionally(v._rotate.bind(v)));
                    if (v._rotate_end != null)
                        v.connect(this.rotate_end, conditionally(v._rotate_end.bind(v)));
                    break;
                }
                case "move": {
                    if (v._move_enter != null)
                        v.connect(this.move_enter, conditionally(v._move_enter.bind(v)));
                    if (v._move != null)
                        v.connect(this.move, conditionally(v._move.bind(v)));
                    if (v._move_exit != null)
                        v.connect(this.move_exit, conditionally(v._move_exit.bind(v)));
                    break;
                }
                case "tap": {
                    if (v._tap != null)
                        v.connect(this.tap, conditionally(v._tap.bind(v)));
                    if (v._doubletap != null)
                        v.connect(this.doubletap, conditionally(v._doubletap.bind(v)));
                    break;
                }
                case "press": {
                    if (v._press != null)
                        v.connect(this.press, conditionally(v._press.bind(v)));
                    if (v._pressup != null)
                        v.connect(this.pressup, conditionally(v._pressup.bind(v)));
                    break;
                }
                case "scroll": {
                    if (v._scroll != null)
                        v.connect(this.scroll, conditionally(v._scroll.bind(v)));
                    break;
                }
                default:
                    throw new Error("unsupported event_type: " + et);
            }
            // Skip shared events if registering multi-tool
            if (!shared)
                return;
            if (v._keydown != null)
                v.connect(this.keydown, unconditionally(v._keydown.bind(v)));
            if (v._keyup != null)
                v.connect(this.keyup, unconditionally(v._keyup.bind(v)));
            // Dual touch hack part 1/2
            // This is a hack for laptops with touch screen who may be pinching or scrolling
            // in order to use the wheel zoom tool. If it's a touch screen the WheelZoomTool event
            // will be linked to pinch. But we also want to trigger in the case of a scroll.
            if (platform_1.is_mobile && v._scroll != null && et == "pinch") {
                logging_1.logger.debug("Registering scroll on touch screen");
                v.connect(this.scroll, conditionally(v._scroll.bind(v)));
            }
        };
        UIEventBus.prototype._hit_test_renderers = function (plot_view, sx, sy) {
            var e_1, _a;
            var _b;
            var views = plot_view.get_renderer_views();
            try {
                for (var _c = (0, tslib_1.__values)((0, array_1.reversed)(views)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var view = _d.value;
                    if ((_b = view.interactive_hit) === null || _b === void 0 ? void 0 : _b.call(view, sx, sy))
                        return view;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return))
                        _a.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return null;
        };
        UIEventBus.prototype.set_cursor = function (cursor) {
            if (cursor === void 0) {
                cursor = "default";
            }
            this.hit_area.style.cursor = cursor;
        };
        UIEventBus.prototype._hit_test_frame = function (plot_view, sx, sy) {
            return plot_view.frame.bbox.contains(sx, sy);
        };
        UIEventBus.prototype._hit_test_canvas = function (plot_view, sx, sy) {
            return plot_view.layout.bbox.contains(sx, sy);
        };
        UIEventBus.prototype._hit_test_plot = function (sx, sy) {
            var e_2, _a;
            try {
                // TODO: z-index
                for (var _b = (0, tslib_1.__values)(this.canvas_view.plot_views), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var plot_view = _c.value;
                    if (plot_view.layout.bbox.relative() /*XXX*/.contains(sx, sy))
                        return plot_view;
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return null;
        };
        UIEventBus.prototype._trigger = function (signal, e, srcEvent) {
            var _a;
            var sx = e.sx, sy = e.sy;
            var plot_view = this._hit_test_plot(sx, sy);
            var curr_view = plot_view;
            var relativize_event = function (_plot_view) {
                var _a = (0, tslib_1.__read)([sx, sy], 2), rel_sx = _a[0], rel_sy = _a[1]; // plot_view.layout.bbox.relativize(sx, sy)
                return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, e), { sx: rel_sx, sy: rel_sy });
            };
            if (e.type == "panstart" || e.type == "pan" || e.type == "panend") {
                var pan_view = void 0;
                if (e.type == "panstart" && curr_view != null) {
                    this._curr_pan = { plot_view: curr_view };
                    pan_view = curr_view;
                }
                else if (e.type == "pan" && this._curr_pan != null) {
                    pan_view = this._curr_pan.plot_view;
                }
                else if (e.type == "panend" && this._curr_pan != null) {
                    pan_view = this._curr_pan.plot_view;
                    this._curr_pan = null;
                }
                else {
                    pan_view = null;
                }
                if (pan_view != null) {
                    var event = relativize_event(pan_view);
                    this.__trigger(pan_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "pinchstart" || e.type == "pinch" || e.type == "pinchend") {
                var pinch_view = void 0;
                if (e.type == "pinchstart" && curr_view != null) {
                    this._curr_pinch = { plot_view: curr_view };
                    pinch_view = curr_view;
                }
                else if (e.type == "pinch" && this._curr_pinch != null) {
                    pinch_view = this._curr_pinch.plot_view;
                }
                else if (e.type == "pinchend" && this._curr_pinch != null) {
                    pinch_view = this._curr_pinch.plot_view;
                    this._curr_pinch = null;
                }
                else {
                    pinch_view = null;
                }
                if (pinch_view != null) {
                    var event = relativize_event(pinch_view);
                    this.__trigger(pinch_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "rotatestart" || e.type == "rotate" || e.type == "rotateend") {
                var rotate_view = void 0;
                if (e.type == "rotatestart" && curr_view != null) {
                    this._curr_rotate = { plot_view: curr_view };
                    rotate_view = curr_view;
                }
                else if (e.type == "rotate" && this._curr_rotate != null) {
                    rotate_view = this._curr_rotate.plot_view;
                }
                else if (e.type == "rotateend" && this._curr_rotate != null) {
                    rotate_view = this._curr_rotate.plot_view;
                    this._curr_rotate = null;
                }
                else {
                    rotate_view = null;
                }
                if (rotate_view != null) {
                    var event = relativize_event(rotate_view);
                    this.__trigger(rotate_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "mouseenter" || e.type == "mousemove" || e.type == "mouseleave") {
                var prev_view = (_a = this._prev_move) === null || _a === void 0 ? void 0 : _a.plot_view;
                if (prev_view != null && (e.type == "mouseleave" || prev_view != curr_view)) {
                    var _b = relativize_event(prev_view), sx_1 = _b.sx, sy_1 = _b.sy;
                    this.__trigger(prev_view, this.move_exit, { type: "mouseleave", sx: sx_1, sy: sy_1, shiftKey: false, ctrlKey: false }, srcEvent);
                }
                if (curr_view != null && (e.type == "mouseenter" || prev_view != curr_view)) {
                    var _c = relativize_event(curr_view), sx_2 = _c.sx, sy_2 = _c.sy;
                    this.__trigger(curr_view, this.move_enter, { type: "mouseenter", sx: sx_2, sy: sy_2, shiftKey: false, ctrlKey: false }, srcEvent);
                }
                if (curr_view != null && e.type == "mousemove") {
                    var event = relativize_event(curr_view);
                    this.__trigger(curr_view, signal, event, srcEvent);
                }
                this._prev_move = { sx: sx, sy: sy, plot_view: curr_view };
            }
            else {
                if (curr_view != null) {
                    var event = relativize_event(curr_view);
                    this.__trigger(curr_view, signal, event, srcEvent);
                }
            }
        };
        UIEventBus.prototype.__trigger = function (plot_view, signal, e, srcEvent) {
            var _this = this;
            var _a, _b;
            var gestures = plot_view.model.toolbar.gestures;
            var event_type = signal.name;
            var base_type = event_type.split(":")[0];
            var view = this._hit_test_renderers(plot_view, e.sx, e.sy);
            var on_canvas = this._hit_test_canvas(plot_view, e.sx, e.sy);
            switch (base_type) {
                case "move": {
                    var active_gesture = gestures[base_type].active;
                    if (active_gesture != null)
                        this.trigger(signal, e, active_gesture.id);
                    var active_inspectors = plot_view.model.toolbar.inspectors.filter(function (t) { return t.active; });
                    var cursor = "default";
                    // the event happened on a renderer
                    if (view != null) {
                        cursor = (_a = view.cursor(e.sx, e.sy)) !== null && _a !== void 0 ? _a : cursor;
                        if (!(0, array_1.is_empty)(active_inspectors)) {
                            // override event_type to cause inspectors to clear overlays
                            signal = this.move_exit; // XXX
                        }
                        // the event happened on the plot frame but off a renderer
                    }
                    else if (this._hit_test_frame(plot_view, e.sx, e.sy)) {
                        if (!(0, array_1.is_empty)(active_inspectors)) {
                            cursor = "crosshair";
                        }
                    }
                    this.set_cursor(cursor);
                    plot_view.set_toolbar_visibility(on_canvas);
                    active_inspectors.map(function (inspector) { return _this.trigger(signal, e, inspector.id); });
                    break;
                }
                case "tap": {
                    var target = srcEvent.target;
                    if (target != null && target != this.hit_area)
                        return; // don't trigger bokeh events
                    if (view != null && view.on_hit != null)
                        view.on_hit(e.sx, e.sy);
                    var active_gesture = gestures[base_type].active;
                    if (active_gesture != null)
                        this.trigger(signal, e, active_gesture.id);
                    break;
                }
                case "doubletap": {
                    var active_gesture = (_b = gestures.doubletap.active) !== null && _b !== void 0 ? _b : gestures.tap.active;
                    if (active_gesture != null)
                        this.trigger(signal, e, active_gesture.id);
                    break;
                }
                case "scroll": {
                    // Dual touch hack part 2/2
                    // This is a hack for laptops with touch screen who may be pinching or scrolling
                    // in order to use the wheel zoom tool. If it's a touch screen the WheelZoomTool event
                    // will be linked to pinch. But we also want to trigger in the case of a scroll.
                    var base = platform_1.is_mobile ? "pinch" : "scroll";
                    var active_gesture = gestures[base].active;
                    if (active_gesture != null) {
                        srcEvent.preventDefault();
                        srcEvent.stopPropagation();
                        this.trigger(signal, e, active_gesture.id);
                    }
                    break;
                }
                case "pan": {
                    var active_gesture = gestures[base_type].active;
                    if (active_gesture != null) {
                        srcEvent.preventDefault();
                        this.trigger(signal, e, active_gesture.id);
                    }
                    break;
                }
                default: {
                    var active_gesture = gestures[base_type].active;
                    if (active_gesture != null)
                        this.trigger(signal, e, active_gesture.id);
                }
            }
            this._trigger_bokeh_event(plot_view, e);
        };
        UIEventBus.prototype.trigger = function (signal, e, id) {
            if (id === void 0) {
                id = null;
            }
            signal.emit({ id: id, e: e });
        };
        /*protected*/ UIEventBus.prototype._trigger_bokeh_event = function (plot_view, e) {
            var ev = (function () {
                var sx = e.sx, sy = e.sy;
                var x = plot_view.frame.x_scale.invert(sx);
                var y = plot_view.frame.y_scale.invert(sy);
                switch (e.type) {
                    case "wheel":
                        return new events.MouseWheel(sx, sy, x, y, e.delta);
                    case "mousemove":
                        return new events.MouseMove(sx, sy, x, y);
                    case "mouseenter":
                        return new events.MouseEnter(sx, sy, x, y);
                    case "mouseleave":
                        return new events.MouseLeave(sx, sy, x, y);
                    case "tap":
                        return new events.Tap(sx, sy, x, y);
                    case "doubletap":
                        return new events.DoubleTap(sx, sy, x, y);
                    case "press":
                        return new events.Press(sx, sy, x, y);
                    case "pressup":
                        return new events.PressUp(sx, sy, x, y);
                    case "pan":
                        return new events.Pan(sx, sy, x, y, e.deltaX, e.deltaY);
                    case "panstart":
                        return new events.PanStart(sx, sy, x, y);
                    case "panend":
                        return new events.PanEnd(sx, sy, x, y);
                    case "pinch":
                        return new events.Pinch(sx, sy, x, y, e.scale);
                    case "pinchstart":
                        return new events.PinchStart(sx, sy, x, y);
                    case "pinchend":
                        return new events.PinchEnd(sx, sy, x, y);
                    case "rotate":
                        return new events.Rotate(sx, sy, x, y, e.rotation);
                    case "rotatestart":
                        return new events.RotateStart(sx, sy, x, y);
                    case "rotateend":
                        return new events.RotateEnd(sx, sy, x, y);
                    default:
                        return undefined;
                }
            })();
            if (ev != null)
                plot_view.model.trigger_event(ev);
        };
        /*private*/ UIEventBus.prototype._get_sxy = function (event) {
            var _a = is_touch(event) ? (event.touches.length != 0 ? event.touches : event.changedTouches)[0] : event, pageX = _a.pageX, pageY = _a.pageY;
            var _b = (0, dom_1.offset)(this.hit_area), left = _b.left, top = _b.top;
            return {
                sx: pageX - left,
                sy: pageY - top,
            };
        };
        /*private*/ UIEventBus.prototype._pan_event = function (e) {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({ type: e.type }, this._get_sxy(e.srcEvent)), { deltaX: e.deltaX, deltaY: e.deltaY, shiftKey: e.srcEvent.shiftKey, ctrlKey: e.srcEvent.ctrlKey });
        };
        /*private*/ UIEventBus.prototype._pinch_event = function (e) {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({ type: e.type }, this._get_sxy(e.srcEvent)), { scale: e.scale, shiftKey: e.srcEvent.shiftKey, ctrlKey: e.srcEvent.ctrlKey });
        };
        /*private*/ UIEventBus.prototype._rotate_event = function (e) {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({ type: e.type }, this._get_sxy(e.srcEvent)), { rotation: e.rotation, shiftKey: e.srcEvent.shiftKey, ctrlKey: e.srcEvent.ctrlKey });
        };
        /*private*/ UIEventBus.prototype._tap_event = function (e) {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({ type: e.type }, this._get_sxy(e.srcEvent)), { shiftKey: e.srcEvent.shiftKey, ctrlKey: e.srcEvent.ctrlKey });
        };
        /*private*/ UIEventBus.prototype._move_event = function (e) {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({ type: e.type }, this._get_sxy(e)), { shiftKey: e.shiftKey, ctrlKey: e.ctrlKey });
        };
        /*private*/ UIEventBus.prototype._scroll_event = function (e) {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({ type: e.type }, this._get_sxy(e)), { delta: (0, wheel_1.getDeltaY)(e), shiftKey: e.shiftKey, ctrlKey: e.ctrlKey });
        };
        /*private*/ UIEventBus.prototype._key_event = function (e) {
            return {
                type: e.type,
                keyCode: e.keyCode,
            };
        };
        /*private*/ UIEventBus.prototype._pan_start = function (e) {
            var ev = this._pan_event(e);
            // back out delta to get original center point
            ev.sx -= e.deltaX;
            ev.sy -= e.deltaY;
            this._trigger(this.pan_start, ev, e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._pan = function (e) {
            this._trigger(this.pan, this._pan_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._pan_end = function (e) {
            this._trigger(this.pan_end, this._pan_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._pinch_start = function (e) {
            this._trigger(this.pinch_start, this._pinch_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._pinch = function (e) {
            this._trigger(this.pinch, this._pinch_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._pinch_end = function (e) {
            this._trigger(this.pinch_end, this._pinch_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._rotate_start = function (e) {
            this._trigger(this.rotate_start, this._rotate_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._rotate = function (e) {
            this._trigger(this.rotate, this._rotate_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._rotate_end = function (e) {
            this._trigger(this.rotate_end, this._rotate_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._tap = function (e) {
            this._trigger(this.tap, this._tap_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._doubletap = function (e) {
            this._trigger(this.doubletap, this._tap_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._press = function (e) {
            this._trigger(this.press, this._tap_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._pressup = function (e) {
            this._trigger(this.pressup, this._tap_event(e), e.srcEvent);
        };
        /*private*/ UIEventBus.prototype._mouse_enter = function (e) {
            this._trigger(this.move_enter, this._move_event(e), e);
        };
        /*private*/ UIEventBus.prototype._mouse_move = function (e) {
            this._trigger(this.move, this._move_event(e), e);
        };
        /*private*/ UIEventBus.prototype._mouse_exit = function (e) {
            this._trigger(this.move_exit, this._move_event(e), e);
        };
        /*private*/ UIEventBus.prototype._mouse_wheel = function (e) {
            this._trigger(this.scroll, this._scroll_event(e), e);
        };
        /*private*/ UIEventBus.prototype._context_menu = function (e) {
            if (!this.menu.is_open && this.menu.can_open) {
                e.preventDefault();
            }
            var _a = this._get_sxy(e), sx = _a.sx, sy = _a.sy;
            this.menu.toggle({ left: sx, top: sy });
        };
        /*private*/ UIEventBus.prototype._key_down = function (e) {
            // NOTE: keyup event triggered unconditionally
            this.trigger(this.keydown, this._key_event(e));
        };
        /*private*/ UIEventBus.prototype._key_up = function (e) {
            // NOTE: keyup event triggered unconditionally
            this.trigger(this.keyup, this._key_event(e));
        };
        return UIEventBus;
    }());
    exports.UIEventBus = UIEventBus;
    UIEventBus.__name__ = "UIEventBus";
},
/* core/bokeh_events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    function event(event_name) {
        return function (cls) {
            cls.prototype.event_name = event_name;
        };
    }
    var BokehEvent = /** @class */ (function () {
        function BokehEvent() {
        }
        BokehEvent.prototype.to_json = function () {
            var event_name = this.event_name;
            return { event_name: event_name, event_values: this._to_json() };
        };
        return BokehEvent;
    }());
    exports.BokehEvent = BokehEvent;
    BokehEvent.__name__ = "BokehEvent";
    var ModelEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ModelEvent, _super);
        function ModelEvent() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.origin = null;
            return _this;
        }
        ModelEvent.prototype._to_json = function () {
            return { model: this.origin };
        };
        return ModelEvent;
    }(BokehEvent));
    exports.ModelEvent = ModelEvent;
    ModelEvent.__name__ = "ModelEvent";
    var DocumentReady = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DocumentReady, _super);
        function DocumentReady() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        DocumentReady.prototype._to_json = function () {
            return {};
        };
        return DocumentReady;
    }(BokehEvent));
    exports.DocumentReady = DocumentReady;
    DocumentReady.__name__ = "DocumentReady";
    exports.DocumentReady = DocumentReady = __decorate([
        event("document_ready")
    ], DocumentReady);
    var ButtonClick = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ButtonClick, _super);
        function ButtonClick() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ButtonClick;
    }(ModelEvent));
    exports.ButtonClick = ButtonClick;
    ButtonClick.__name__ = "ButtonClick";
    exports.ButtonClick = ButtonClick = __decorate([
        event("button_click")
    ], ButtonClick);
    var MenuItemClick = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MenuItemClick, _super);
        function MenuItemClick(item) {
            var _this = _super.call(this) || this;
            _this.item = item;
            return _this;
        }
        MenuItemClick.prototype._to_json = function () {
            var item = this.item;
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._to_json.call(this)), { item: item });
        };
        return MenuItemClick;
    }(ModelEvent));
    exports.MenuItemClick = MenuItemClick;
    MenuItemClick.__name__ = "MenuItemClick";
    exports.MenuItemClick = MenuItemClick = __decorate([
        event("menu_item_click")
    ], MenuItemClick);
    // A UIEvent is an event originating on a canvas this includes.
    // DOM events such as keystrokes as well as hammer, LOD, and range events.
    var UIEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UIEvent, _super);
        function UIEvent() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return UIEvent;
    }(ModelEvent));
    exports.UIEvent = UIEvent;
    UIEvent.__name__ = "UIEvent";
    var LODStart = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LODStart, _super);
        function LODStart() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LODStart;
    }(UIEvent));
    exports.LODStart = LODStart;
    LODStart.__name__ = "LODStart";
    exports.LODStart = LODStart = __decorate([
        event("lodstart")
    ], LODStart);
    var LODEnd = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LODEnd, _super);
        function LODEnd() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return LODEnd;
    }(UIEvent));
    exports.LODEnd = LODEnd;
    LODEnd.__name__ = "LODEnd";
    exports.LODEnd = LODEnd = __decorate([
        event("lodend")
    ], LODEnd);
    var RangesUpdate = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RangesUpdate, _super);
        function RangesUpdate(x0, x1, y0, y1) {
            var _this = _super.call(this) || this;
            _this.x0 = x0;
            _this.x1 = x1;
            _this.y0 = y0;
            _this.y1 = y1;
            return _this;
        }
        RangesUpdate.prototype._to_json = function () {
            var _a = this, x0 = _a.x0, x1 = _a.x1, y0 = _a.y0, y1 = _a.y1;
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._to_json.call(this)), { x0: x0, x1: x1, y0: y0, y1: y1 });
        };
        return RangesUpdate;
    }(UIEvent));
    exports.RangesUpdate = RangesUpdate;
    RangesUpdate.__name__ = "RangesUpdate";
    exports.RangesUpdate = RangesUpdate = __decorate([
        event("rangesupdate")
    ], RangesUpdate);
    var SelectionGeometry = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SelectionGeometry, _super);
        function SelectionGeometry(geometry, final) {
            var _this = _super.call(this) || this;
            _this.geometry = geometry;
            _this.final = final;
            return _this;
        }
        SelectionGeometry.prototype._to_json = function () {
            var _a = this, geometry = _a.geometry, final = _a.final;
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._to_json.call(this)), { geometry: geometry, final: final });
        };
        return SelectionGeometry;
    }(UIEvent));
    exports.SelectionGeometry = SelectionGeometry;
    SelectionGeometry.__name__ = "SelectionGeometry";
    exports.SelectionGeometry = SelectionGeometry = __decorate([
        event("selectiongeometry")
    ], SelectionGeometry);
    var Reset = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Reset, _super);
        function Reset() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Reset;
    }(UIEvent));
    exports.Reset = Reset;
    Reset.__name__ = "Reset";
    exports.Reset = Reset = __decorate([
        event("reset")
    ], Reset);
    var PointEvent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PointEvent, _super);
        function PointEvent(sx, sy, x, y) {
            var _this = _super.call(this) || this;
            _this.sx = sx;
            _this.sy = sy;
            _this.x = x;
            _this.y = y;
            return _this;
        }
        PointEvent.prototype._to_json = function () {
            var _a = this, sx = _a.sx, sy = _a.sy, x = _a.x, y = _a.y;
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._to_json.call(this)), { sx: sx, sy: sy, x: x, y: y });
        };
        return PointEvent;
    }(UIEvent));
    exports.PointEvent = PointEvent;
    PointEvent.__name__ = "PointEvent";
    var Pan = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Pan, _super);
        /* TODO: direction: -1 | 1 */
        function Pan(sx, sy, x, y, delta_x, delta_y) {
            var _this = _super.call(this, sx, sy, x, y) || this;
            _this.delta_x = delta_x;
            _this.delta_y = delta_y;
            return _this;
        }
        Pan.prototype._to_json = function () {
            var _a = this, delta_x = _a.delta_x, delta_y = _a.delta_y /*, direction*/;
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._to_json.call(this)), { delta_x: delta_x, delta_y: delta_y /*, direction*/ });
        };
        return Pan;
    }(PointEvent));
    exports.Pan = Pan;
    Pan.__name__ = "Pan";
    exports.Pan = Pan = __decorate([
        event("pan")
    ], Pan);
    var Pinch = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Pinch, _super);
        function Pinch(sx, sy, x, y, scale) {
            var _this = _super.call(this, sx, sy, x, y) || this;
            _this.scale = scale;
            return _this;
        }
        Pinch.prototype._to_json = function () {
            var scale = this.scale;
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._to_json.call(this)), { scale: scale });
        };
        return Pinch;
    }(PointEvent));
    exports.Pinch = Pinch;
    Pinch.__name__ = "Pinch";
    exports.Pinch = Pinch = __decorate([
        event("pinch")
    ], Pinch);
    var Rotate = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Rotate, _super);
        function Rotate(sx, sy, x, y, rotation) {
            var _this = _super.call(this, sx, sy, x, y) || this;
            _this.rotation = rotation;
            return _this;
        }
        Rotate.prototype._to_json = function () {
            var rotation = this.rotation;
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._to_json.call(this)), { rotation: rotation });
        };
        return Rotate;
    }(PointEvent));
    exports.Rotate = Rotate;
    Rotate.__name__ = "Rotate";
    exports.Rotate = Rotate = __decorate([
        event("rotate")
    ], Rotate);
    var MouseWheel = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MouseWheel, _super);
        function MouseWheel(sx, sy, x, y, delta) {
            var _this = _super.call(this, sx, sy, x, y) || this;
            _this.delta = delta;
            return _this;
        }
        MouseWheel.prototype._to_json = function () {
            var delta = this.delta;
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype._to_json.call(this)), { delta: delta });
        };
        return MouseWheel;
    }(PointEvent));
    exports.MouseWheel = MouseWheel;
    MouseWheel.__name__ = "MouseWheel";
    exports.MouseWheel = MouseWheel = __decorate([
        event("wheel")
    ], MouseWheel);
    var MouseMove = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MouseMove, _super);
        function MouseMove() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return MouseMove;
    }(PointEvent));
    exports.MouseMove = MouseMove;
    MouseMove.__name__ = "MouseMove";
    exports.MouseMove = MouseMove = __decorate([
        event("mousemove")
    ], MouseMove);
    var MouseEnter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MouseEnter, _super);
        function MouseEnter() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return MouseEnter;
    }(PointEvent));
    exports.MouseEnter = MouseEnter;
    MouseEnter.__name__ = "MouseEnter";
    exports.MouseEnter = MouseEnter = __decorate([
        event("mouseenter")
    ], MouseEnter);
    var MouseLeave = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MouseLeave, _super);
        function MouseLeave() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return MouseLeave;
    }(PointEvent));
    exports.MouseLeave = MouseLeave;
    MouseLeave.__name__ = "MouseLeave";
    exports.MouseLeave = MouseLeave = __decorate([
        event("mouseleave")
    ], MouseLeave);
    var Tap = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Tap, _super);
        function Tap() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Tap;
    }(PointEvent));
    exports.Tap = Tap;
    Tap.__name__ = "Tap";
    exports.Tap = Tap = __decorate([
        event("tap")
    ], Tap);
    var DoubleTap = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DoubleTap, _super);
        function DoubleTap() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return DoubleTap;
    }(PointEvent));
    exports.DoubleTap = DoubleTap;
    DoubleTap.__name__ = "DoubleTap";
    exports.DoubleTap = DoubleTap = __decorate([
        event("doubletap")
    ], DoubleTap);
    var Press = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Press, _super);
        function Press() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Press;
    }(PointEvent));
    exports.Press = Press;
    Press.__name__ = "Press";
    exports.Press = Press = __decorate([
        event("press")
    ], Press);
    var PressUp = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PressUp, _super);
        function PressUp() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return PressUp;
    }(PointEvent));
    exports.PressUp = PressUp;
    PressUp.__name__ = "PressUp";
    exports.PressUp = PressUp = __decorate([
        event("pressup")
    ], PressUp);
    var PanStart = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PanStart, _super);
        function PanStart() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return PanStart;
    }(PointEvent));
    exports.PanStart = PanStart;
    PanStart.__name__ = "PanStart";
    exports.PanStart = PanStart = __decorate([
        event("panstart")
    ], PanStart);
    var PanEnd = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PanEnd, _super);
        function PanEnd() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return PanEnd;
    }(PointEvent));
    exports.PanEnd = PanEnd;
    PanEnd.__name__ = "PanEnd";
    exports.PanEnd = PanEnd = __decorate([
        event("panend")
    ], PanEnd);
    var PinchStart = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PinchStart, _super);
        function PinchStart() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return PinchStart;
    }(PointEvent));
    exports.PinchStart = PinchStart;
    PinchStart.__name__ = "PinchStart";
    exports.PinchStart = PinchStart = __decorate([
        event("pinchstart")
    ], PinchStart);
    var PinchEnd = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PinchEnd, _super);
        function PinchEnd() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return PinchEnd;
    }(PointEvent));
    exports.PinchEnd = PinchEnd;
    PinchEnd.__name__ = "PinchEnd";
    exports.PinchEnd = PinchEnd = __decorate([
        event("pinchend")
    ], PinchEnd);
    var RotateStart = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RotateStart, _super);
        function RotateStart() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return RotateStart;
    }(PointEvent));
    exports.RotateStart = RotateStart;
    RotateStart.__name__ = "RotateStart";
    exports.RotateStart = RotateStart = __decorate([
        event("rotatestart")
    ], RotateStart);
    var RotateEnd = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RotateEnd, _super);
        function RotateEnd() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return RotateEnd;
    }(PointEvent));
    exports.RotateEnd = RotateEnd;
    RotateEnd.__name__ = "RotateEnd";
    exports.RotateEnd = RotateEnd = __decorate([
        event("rotateend")
    ], RotateEnd);
},
/* core/util/wheel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    /*!
     * jQuery Mousewheel 3.1.13
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license
     * http://jquery.org/license
     */
    function fontSize(element) {
        var value = getComputedStyle(element).fontSize;
        if (value != null)
            return parseInt(value, 10);
        return null;
    }
    function lineHeight(element) {
        var _a, _b, _c;
        var parent = (_a = element.offsetParent) !== null && _a !== void 0 ? _a : document.body;
        return (_c = (_b = fontSize(parent)) !== null && _b !== void 0 ? _b : fontSize(element)) !== null && _c !== void 0 ? _c : 16;
    }
    function pageHeight(element) {
        return element.clientHeight; // XXX: should be content height?
    }
    function getDeltaY(event) {
        var deltaY = -event.deltaY;
        if (event.target instanceof HTMLElement) {
            switch (event.deltaMode) {
                case event.DOM_DELTA_LINE:
                    deltaY *= lineHeight(event.target);
                    break;
                case event.DOM_DELTA_PAGE:
                    deltaY *= pageHeight(event.target);
                    break;
            }
        }
        return deltaY;
    }
    exports.getDeltaY = getDeltaY;
},
/* models/expressions/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var expression_1 = require(369) /* ./expression */;
    __esExport("Expression", expression_1.Expression);
    var customjs_expr_1 = require(370) /* ./customjs_expr */;
    __esExport("CustomJSExpr", customjs_expr_1.CustomJSExpr);
    var stack_1 = require(371) /* ./stack */;
    __esExport("Stack", stack_1.Stack);
    var cumsum_1 = require(372) /* ./cumsum */;
    __esExport("CumSum", cumsum_1.CumSum);
    var expression_2 = require(369) /* ./expression */;
    __esExport("ScalarExpression", expression_2.ScalarExpression);
    var minimum_1 = require(373) /* ./minimum */;
    __esExport("Minimum", minimum_1.Minimum);
    var maximum_1 = require(374) /* ./maximum */;
    __esExport("Maximum", maximum_1.Maximum);
    var coordinate_transform_1 = require(375) /* ./coordinate_transform */;
    __esExport("XComponent", coordinate_transform_1.XComponent);
    __esExport("YComponent", coordinate_transform_1.YComponent);
    var polar_1 = require(376) /* ./polar */;
    __esExport("PolarTransform", polar_1.PolarTransform);
},
/* models/expressions/expression.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../../model */;
    var Expression = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Expression, _super);
        function Expression(attrs) {
            return _super.call(this, attrs) || this;
        }
        Expression.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._result = new Map();
        };
        Expression.prototype.v_compute = function (source) {
            var result = this._result.get(source);
            if (result === undefined || source.changed_for(this)) {
                result = this._v_compute(source);
                this._result.set(source, result);
            }
            return result;
        };
        return Expression;
    }(model_1.Model));
    exports.Expression = Expression;
    Expression.__name__ = "Expression";
    var ScalarExpression = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ScalarExpression, _super);
        function ScalarExpression(attrs) {
            return _super.call(this, attrs) || this;
        }
        ScalarExpression.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._result = new Map();
        };
        ScalarExpression.prototype.compute = function (source) {
            var result = this._result.get(source);
            if (result === undefined || source.changed_for(this)) {
                result = this._compute(source);
                this._result.set(source, result);
            }
            return result;
        };
        return ScalarExpression;
    }(model_1.Model));
    exports.ScalarExpression = ScalarExpression;
    ScalarExpression.__name__ = "ScalarExpression";
},
/* models/expressions/customjs_expr.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var has_props_1 = require(129) /* ../../core/has_props */;
    var expression_1 = require(369) /* ./expression */;
    var types_1 = require(139) /* ../../core/types */;
    var array_1 = require(126) /* ../../core/util/array */;
    var object_1 = require(128) /* ../../core/util/object */;
    var string_1 = require(149) /* ../../core/util/string */;
    var types_2 = require(125) /* ../../core/util/types */;
    var CustomJSExpr = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomJSExpr, _super);
        function CustomJSExpr(attrs) {
            return _super.call(this, attrs) || this;
        }
        CustomJSExpr.prototype.connect_signals = function () {
            var e_1, _b;
            var _this = this;
            _super.prototype.connect_signals.call(this);
            try {
                for (var _c = (0, tslib_1.__values)((0, object_1.values)(this.args)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var value = _d.value;
                    if (value instanceof has_props_1.HasProps) {
                        value.change.connect(function () {
                            _this._result.clear();
                            _this.change.emit();
                        });
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        Object.defineProperty(CustomJSExpr.prototype, "names", {
            get: function () {
                return (0, object_1.keys)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomJSExpr.prototype, "values", {
            get: function () {
                return (0, object_1.values)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomJSExpr.prototype, "func", {
            get: function () {
                var code = (0, string_1.use_strict)(this.code);
                return new (types_1.GeneratorFunction.bind.apply(types_1.GeneratorFunction, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([void 0], (0, tslib_1.__read)(this.names), false), [code], false)))();
            },
            enumerable: false,
            configurable: true
        });
        CustomJSExpr.prototype._v_compute = function (source) {
            var generator = this.func.apply(source, this.values);
            var result = generator.next();
            if (result.done && result.value !== undefined) {
                var value = result.value;
                if ((0, types_2.isArray)(value) || (0, types_2.isTypedArray)(value))
                    return value;
                else if ((0, types_2.isIterable)(value))
                    return (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(value), false);
                else
                    return (0, array_1.repeat)(value, source.length);
            }
            else {
                var array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!result.done);
                return array;
            }
        };
        return CustomJSExpr;
    }(expression_1.Expression));
    exports.CustomJSExpr = CustomJSExpr;
    _a = CustomJSExpr;
    CustomJSExpr.__name__ = "CustomJSExpr";
    (function () {
        _a.define(function (_b) {
            var Unknown = _b.Unknown, String = _b.String, Dict = _b.Dict;
            return ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            });
        });
    })();
},
/* models/expressions/stack.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var expression_1 = require(369) /* ./expression */;
    var Stack = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Stack, _super);
        function Stack(attrs) {
            return _super.call(this, attrs) || this;
        }
        Stack.prototype._v_compute = function (source) {
            var e_1, _b;
            var _c;
            var n = (_c = source.get_length()) !== null && _c !== void 0 ? _c : 0;
            var result = new Float64Array(n);
            try {
                for (var _d = (0, tslib_1.__values)(this.fields), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var f = _e.value;
                    var column = source.data[f];
                    if (column != null) {
                        var k = Math.min(n, column.length);
                        for (var i = 0; i < k; i++) {
                            result[i] += column[i];
                        }
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return result;
        };
        return Stack;
    }(expression_1.Expression));
    exports.Stack = Stack;
    _a = Stack;
    Stack.__name__ = "Stack";
    (function () {
        _a.define(function (_b) {
            var String = _b.String, Array = _b.Array;
            return ({
                fields: [Array(String), []],
            });
        });
    })();
},
/* models/expressions/cumsum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var expression_1 = require(369) /* ./expression */;
    var CumSum = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CumSum, _super);
        function CumSum(attrs) {
            return _super.call(this, attrs) || this;
        }
        CumSum.prototype._v_compute = function (source) {
            var _b;
            var result = new Float64Array((_b = source.get_length()) !== null && _b !== void 0 ? _b : 0);
            var col = source.data[this.field];
            var offset = this.include_zero ? 1 : 0;
            result[0] = this.include_zero ? 0 : col[0];
            for (var i = 1; i < result.length; i++) {
                result[i] = result[i - 1] + col[i - offset];
            }
            return result;
        };
        return CumSum;
    }(expression_1.Expression));
    exports.CumSum = CumSum;
    _a = CumSum;
    CumSum.__name__ = "CumSum";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, String = _b.String;
            return ({
                field: [String],
                include_zero: [Boolean, false],
            });
        });
    })();
},
/* models/expressions/minimum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var expression_1 = require(369) /* ./expression */;
    var array_1 = require(126) /* ../../core/util/array */;
    var Minimum = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Minimum, _super);
        function Minimum(attrs) {
            return _super.call(this, attrs) || this;
        }
        Minimum.prototype._compute = function (source) {
            var _b, _c;
            var column = (_b = source.data[this.field]) !== null && _b !== void 0 ? _b : [];
            return Math.min((_c = this.initial) !== null && _c !== void 0 ? _c : Infinity, (0, array_1.min)(column));
        };
        return Minimum;
    }(expression_1.ScalarExpression));
    exports.Minimum = Minimum;
    _a = Minimum;
    Minimum.__name__ = "Minimum";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, String = _b.String, Nullable = _b.Nullable;
            return ({
                field: [String],
                initial: [Nullable(Number), null], // TODO: Infinity
            });
        });
    })();
},
/* models/expressions/maximum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var expression_1 = require(369) /* ./expression */;
    var array_1 = require(126) /* ../../core/util/array */;
    var Maximum = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Maximum, _super);
        function Maximum(attrs) {
            return _super.call(this, attrs) || this;
        }
        Maximum.prototype._compute = function (source) {
            var _b, _c;
            var column = (_b = source.data[this.field]) !== null && _b !== void 0 ? _b : [];
            return Math.max((_c = this.initial) !== null && _c !== void 0 ? _c : -Infinity, (0, array_1.max)(column));
        };
        return Maximum;
    }(expression_1.ScalarExpression));
    exports.Maximum = Maximum;
    _a = Maximum;
    Maximum.__name__ = "Maximum";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, String = _b.String, Nullable = _b.Nullable;
            return ({
                field: [String],
                initial: [Nullable(Number), null], // TODO: -Infinity
            });
        });
    })();
},
/* models/expressions/coordinate_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var expression_1 = require(369) /* ../expressions/expression */;
    var CoordinateTransform = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CoordinateTransform, _super);
        function CoordinateTransform(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CoordinateTransform.prototype, "x", {
            get: function () {
                return new XComponent({ transform: this });
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CoordinateTransform.prototype, "y", {
            get: function () {
                return new YComponent({ transform: this });
            },
            enumerable: false,
            configurable: true
        });
        return CoordinateTransform;
    }(expression_1.Expression));
    exports.CoordinateTransform = CoordinateTransform;
    CoordinateTransform.__name__ = "CoordinateTransform";
    var XYComponent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(XYComponent, _super);
        function XYComponent(attrs) {
            return _super.call(this, attrs) || this;
        }
        return XYComponent;
    }(expression_1.Expression));
    exports.XYComponent = XYComponent;
    _a = XYComponent;
    XYComponent.__name__ = "XYComponent";
    (function () {
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                transform: [Ref(CoordinateTransform)],
            });
        });
    })();
    var XComponent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(XComponent, _super);
        function XComponent(attrs) {
            return _super.call(this, attrs) || this;
        }
        XComponent.prototype._v_compute = function (source) {
            return this.transform.v_compute(source).x;
        };
        return XComponent;
    }(XYComponent));
    exports.XComponent = XComponent;
    XComponent.__name__ = "XComponent";
    var YComponent = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(YComponent, _super);
        function YComponent(attrs) {
            return _super.call(this, attrs) || this;
        }
        YComponent.prototype._v_compute = function (source) {
            return this.transform.v_compute(source).y;
        };
        return YComponent;
    }(XYComponent));
    exports.YComponent = YComponent;
    YComponent.__name__ = "YComponent";
},
/* models/expressions/polar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var coordinate_transform_1 = require(375) /* ../expressions/coordinate_transform */;
    var enums_1 = require(135) /* ../../core/enums */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var PolarTransform = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolarTransform, _super);
        function PolarTransform(attrs) {
            return _super.call(this, attrs) || this;
        }
        PolarTransform.prototype._v_compute = function (source) {
            var radius = this.properties.radius.uniform(source);
            var angle = this.properties.angle.uniform(source);
            var coeff = this.direction == "anticlock" ? -1 : 1;
            var n = Math.min(radius.length, angle.length);
            var x = new Float64Array(n);
            var y = new Float64Array(n);
            for (var i = 0; i < n; i++) {
                var radius_i = radius.get(i);
                var angle_i = angle.get(i) * coeff;
                x[i] = radius_i * Math.cos(angle_i);
                y[i] = radius_i * Math.sin(angle_i);
            }
            return { x: x, y: y };
        };
        return PolarTransform;
    }(coordinate_transform_1.CoordinateTransform));
    exports.PolarTransform = PolarTransform;
    _a = PolarTransform;
    PolarTransform.__name__ = "PolarTransform";
    (function () {
        _a.define(function (_b) {
            return ({
                radius: [p.DistanceSpec, { field: "radius" }],
                angle: [p.AngleSpec, { field: "angle" }],
                direction: [enums_1.Direction, "anticlock"],
            });
        });
    })();
},
/* models/filters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var boolean_filter_1 = require(378) /* ./boolean_filter */;
    __esExport("BooleanFilter", boolean_filter_1.BooleanFilter);
    var customjs_filter_1 = require(379) /* ./customjs_filter */;
    __esExport("CustomJSFilter", customjs_filter_1.CustomJSFilter);
    var filter_1 = require(306) /* ./filter */;
    __esExport("Filter", filter_1.Filter);
    var group_filter_1 = require(380) /* ./group_filter */;
    __esExport("GroupFilter", group_filter_1.GroupFilter);
    var index_filter_1 = require(381) /* ./index_filter */;
    __esExport("IndexFilter", index_filter_1.IndexFilter);
},
/* models/filters/boolean_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var filter_1 = require(306) /* ./filter */;
    var types_1 = require(139) /* ../../core/types */;
    var BooleanFilter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BooleanFilter, _super);
        function BooleanFilter(attrs) {
            return _super.call(this, attrs) || this;
        }
        BooleanFilter.prototype.compute_indices = function (source) {
            var size = source.length;
            var booleans = this.booleans;
            if (booleans == null) {
                return types_1.Indices.all_set(size);
            }
            else {
                return types_1.Indices.from_booleans(size, booleans);
            }
        };
        return BooleanFilter;
    }(filter_1.Filter));
    exports.BooleanFilter = BooleanFilter;
    _a = BooleanFilter;
    BooleanFilter.__name__ = "BooleanFilter";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Array = _b.Array, Nullable = _b.Nullable;
            return ({
                booleans: [Nullable(Array(Boolean)), null],
            });
        });
    })();
},
/* models/filters/customjs_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var filter_1 = require(306) /* ./filter */;
    var types_1 = require(139) /* ../../core/types */;
    var object_1 = require(128) /* ../../core/util/object */;
    var types_2 = require(125) /* ../../core/util/types */;
    var string_1 = require(149) /* ../../core/util/string */;
    var CustomJSFilter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomJSFilter, _super);
        function CustomJSFilter(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CustomJSFilter.prototype, "names", {
            get: function () {
                return (0, object_1.keys)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomJSFilter.prototype, "values", {
            get: function () {
                return (0, object_1.values)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomJSFilter.prototype, "func", {
            get: function () {
                var code = (0, string_1.use_strict)(this.code);
                return new (Function.bind.apply(Function, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([void 0], (0, tslib_1.__read)(this.names), false), ["source", code], false)))();
            },
            enumerable: false,
            configurable: true
        });
        CustomJSFilter.prototype.compute_indices = function (source) {
            var size = source.length;
            var filter = this.func.apply(this, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.values), false), [source], false));
            if (filter == null)
                return types_1.Indices.all_set(size);
            else if ((0, types_2.isArrayOf)(filter, types_2.isInteger))
                return types_1.Indices.from_indices(size, filter);
            else if ((0, types_2.isArrayOf)(filter, types_2.isBoolean))
                return types_1.Indices.from_booleans(size, filter);
            else
                throw new Error("expect an array of integers or booleans, or null, got " + filter);
        };
        return CustomJSFilter;
    }(filter_1.Filter));
    exports.CustomJSFilter = CustomJSFilter;
    _a = CustomJSFilter;
    CustomJSFilter.__name__ = "CustomJSFilter";
    (function () {
        _a.define(function (_b) {
            var Unknown = _b.Unknown, String = _b.String, Dict = _b.Dict;
            return ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            });
        });
    })();
},
/* models/filters/group_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var filter_1 = require(306) /* ./filter */;
    var types_1 = require(139) /* ../../core/types */;
    var logging_1 = require(134) /* ../../core/logging */;
    var GroupFilter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GroupFilter, _super);
        function GroupFilter(attrs) {
            return _super.call(this, attrs) || this;
        }
        GroupFilter.prototype.compute_indices = function (source) {
            var column = source.get_column(this.column_name);
            if (column == null) {
                logging_1.logger.warn(this + ": groupby column '" + this.column_name + "' not found in the data source");
                return new types_1.Indices(source.length, 1);
            }
            else {
                var indices = new types_1.Indices(source.length);
                for (var i = 0; i < indices.size; i++) {
                    if (column[i] === this.group)
                        indices.set(i);
                }
                return indices;
            }
        };
        return GroupFilter;
    }(filter_1.Filter));
    exports.GroupFilter = GroupFilter;
    _a = GroupFilter;
    GroupFilter.__name__ = "GroupFilter";
    (function () {
        _a.define(function (_b) {
            var String = _b.String;
            return ({
                column_name: [String],
                group: [String],
            });
        });
    })();
},
/* models/filters/index_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var filter_1 = require(306) /* ./filter */;
    var types_1 = require(139) /* ../../core/types */;
    var IndexFilter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(IndexFilter, _super);
        function IndexFilter(attrs) {
            return _super.call(this, attrs) || this;
        }
        IndexFilter.prototype.compute_indices = function (source) {
            var size = source.length;
            var indices = this.indices;
            if (indices == null) {
                return types_1.Indices.all_set(size);
            }
            else {
                return types_1.Indices.from_indices(size, indices);
            }
        };
        return IndexFilter;
    }(filter_1.Filter));
    exports.IndexFilter = IndexFilter;
    _a = IndexFilter;
    IndexFilter.__name__ = "IndexFilter";
    (function () {
        _a.define(function (_b) {
            var Int = _b.Int, Array = _b.Array, Nullable = _b.Nullable;
            return ({
                indices: [Nullable(Array(Int)), null],
            });
        });
    })();
},
/* models/glyphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var annular_wedge_1 = require(383) /* ./annular_wedge */;
    __esExport("AnnularWedge", annular_wedge_1.AnnularWedge);
    var annulus_1 = require(384) /* ./annulus */;
    __esExport("Annulus", annulus_1.Annulus);
    var arc_1 = require(385) /* ./arc */;
    __esExport("Arc", arc_1.Arc);
    var bezier_1 = require(386) /* ./bezier */;
    __esExport("Bezier", bezier_1.Bezier);
    var circle_1 = require(387) /* ./circle */;
    __esExport("Circle", circle_1.Circle);
    var ellipse_1 = require(388) /* ./ellipse */;
    __esExport("Ellipse", ellipse_1.Ellipse);
    var ellipse_oval_1 = require(389) /* ./ellipse_oval */;
    __esExport("EllipseOval", ellipse_oval_1.EllipseOval);
    var glyph_1 = require(294) /* ./glyph */;
    __esExport("Glyph", glyph_1.Glyph);
    var harea_1 = require(302) /* ./harea */;
    __esExport("HArea", harea_1.HArea);
    var hbar_1 = require(391) /* ./hbar */;
    __esExport("HBar", hbar_1.HBar);
    var hex_tile_1 = require(393) /* ./hex_tile */;
    __esExport("HexTile", hex_tile_1.HexTile);
    var image_1 = require(394) /* ./image */;
    __esExport("Image", image_1.Image);
    var image_rgba_1 = require(396) /* ./image_rgba */;
    __esExport("ImageRGBA", image_rgba_1.ImageRGBA);
    var image_url_1 = require(397) /* ./image_url */;
    __esExport("ImageURL", image_url_1.ImageURL);
    var line_1 = require(292) /* ./line */;
    __esExport("Line", line_1.Line);
    var multi_line_1 = require(398) /* ./multi_line */;
    __esExport("MultiLine", multi_line_1.MultiLine);
    var multi_polygons_1 = require(399) /* ./multi_polygons */;
    __esExport("MultiPolygons", multi_polygons_1.MultiPolygons);
    var oval_1 = require(400) /* ./oval */;
    __esExport("Oval", oval_1.Oval);
    var patch_1 = require(301) /* ./patch */;
    __esExport("Patch", patch_1.Patch);
    var patches_1 = require(401) /* ./patches */;
    __esExport("Patches", patches_1.Patches);
    var quad_1 = require(402) /* ./quad */;
    __esExport("Quad", quad_1.Quad);
    var quadratic_1 = require(403) /* ./quadratic */;
    __esExport("Quadratic", quadratic_1.Quadratic);
    var ray_1 = require(404) /* ./ray */;
    __esExport("Ray", ray_1.Ray);
    var rect_1 = require(405) /* ./rect */;
    __esExport("Rect", rect_1.Rect);
    var scatter_1 = require(406) /* ./scatter */;
    __esExport("Scatter", scatter_1.Scatter);
    var segment_1 = require(409) /* ./segment */;
    __esExport("Segment", segment_1.Segment);
    var spline_1 = require(410) /* ./spline */;
    __esExport("Spline", spline_1.Spline);
    var step_1 = require(412) /* ./step */;
    __esExport("Step", step_1.Step);
    var text_1 = require(413) /* ./text */;
    __esExport("Text", text_1.Text);
    var varea_1 = require(304) /* ./varea */;
    __esExport("VArea", varea_1.VArea);
    var vbar_1 = require(414) /* ./vbar */;
    __esExport("VBar", vbar_1.VBar);
    var wedge_1 = require(415) /* ./wedge */;
    __esExport("Wedge", wedge_1.Wedge);
},
/* models/glyphs/annular_wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var utils_1 = require(299) /* ./utils */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var types_1 = require(139) /* ../../core/types */;
    var enums_1 = require(135) /* ../../core/enums */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var math_1 = require(117) /* ../../core/util/math */;
    var selection_1 = require(187) /* ../selections/selection */;
    var AnnularWedgeView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AnnularWedgeView, _super);
        function AnnularWedgeView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AnnularWedgeView.prototype._map_data = function () {
            if (this.model.properties.inner_radius.units == "data")
                this.sinner_radius = this.sdist(this.renderer.xscale, this._x, this.inner_radius);
            else
                this.sinner_radius = (0, types_1.to_screen)(this.inner_radius);
            if (this.model.properties.outer_radius.units == "data")
                this.souter_radius = this.sdist(this.renderer.xscale, this._x, this.outer_radius);
            else
                this.souter_radius = (0, types_1.to_screen)(this.outer_radius);
        };
        AnnularWedgeView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, start_angle = _c.start_angle, end_angle = _c.end_angle, sinner_radius = _c.sinner_radius, souter_radius = _c.souter_radius;
            var anticlock = this.model.direction == "anticlock";
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var sinner_radius_i = sinner_radius[i];
                    var souter_radius_i = souter_radius[i];
                    var start_angle_i = start_angle.get(i);
                    var end_angle_i = end_angle.get(i);
                    if (!isFinite(sx_i + sy_i + sinner_radius_i + souter_radius_i + start_angle_i + end_angle_i))
                        continue;
                    var angle_i = end_angle_i - start_angle_i;
                    ctx.translate(sx_i, sy_i);
                    ctx.rotate(start_angle_i);
                    ctx.beginPath();
                    ctx.moveTo(souter_radius_i, 0);
                    ctx.arc(0, 0, souter_radius_i, 0, angle_i, anticlock);
                    ctx.rotate(angle_i);
                    ctx.lineTo(sinner_radius_i, 0);
                    ctx.arc(0, 0, sinner_radius_i, 0, -angle_i, !anticlock);
                    ctx.closePath();
                    ctx.rotate(-angle_i - start_angle_i);
                    ctx.translate(-sx_i, -sy_i);
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        AnnularWedgeView.prototype._hit_point = function (geometry) {
            var _b, _c, e_2, _d, e_3, _e;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            // check radius first
            var x0, y0;
            var x1, y1;
            if (this.model.properties.outer_radius.units == "data") {
                x0 = x - this.max_outer_radius;
                x1 = x + this.max_outer_radius;
                y0 = y - this.max_outer_radius;
                y1 = y + this.max_outer_radius;
            }
            else {
                var sx0 = sx - this.max_outer_radius;
                var sx1 = sx + this.max_outer_radius;
                _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
                var sy0 = sy - this.max_outer_radius;
                var sy1 = sy + this.max_outer_radius;
                _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _c[0], y1 = _c[1];
            }
            var candidates = [];
            try {
                for (var _f = (0, tslib_1.__values)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var i = _g.value;
                    var or2 = Math.pow(this.souter_radius[i], 2);
                    var ir2 = Math.pow(this.sinner_radius[i], 2);
                    var _h = (0, tslib_1.__read)(this.renderer.xscale.r_compute(x, this._x[i]), 2), sx0 = _h[0], sx1 = _h[1];
                    var _j = (0, tslib_1.__read)(this.renderer.yscale.r_compute(y, this._y[i]), 2), sy0 = _j[0], sy1 = _j[1];
                    var dist = Math.pow((sx0 - sx1), 2) + Math.pow((sy0 - sy1), 2);
                    if (dist <= or2 && dist >= ir2)
                        candidates.push(i);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_d = _f.return))
                        _d.call(_f);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            var anticlock = this.model.direction == "anticlock";
            var indices = [];
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var i = candidates_1_1.value;
                    // NOTE: minus the angle because JS uses non-mathy convention for angles
                    var angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
                    if ((0, math_1.angle_between)(-angle, -this.start_angle.get(i), -this.end_angle.get(i), anticlock)) {
                        indices.push(i);
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_e = candidates_1.return))
                        _e.call(candidates_1);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        AnnularWedgeView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        };
        AnnularWedgeView.prototype.scenterxy = function (i) {
            var r = (this.sinner_radius[i] + this.souter_radius[i]) / 2;
            var a = (this.start_angle.get(i) + this.end_angle.get(i)) / 2;
            var scx = this.sx[i] + r * Math.cos(a);
            var scy = this.sy[i] + r * Math.sin(a);
            return [scx, scy];
        };
        return AnnularWedgeView;
    }(xy_glyph_1.XYGlyphView));
    exports.AnnularWedgeView = AnnularWedgeView;
    AnnularWedgeView.__name__ = "AnnularWedgeView";
    var AnnularWedge = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AnnularWedge, _super);
        function AnnularWedge(attrs) {
            return _super.call(this, attrs) || this;
        }
        return AnnularWedge;
    }(xy_glyph_1.XYGlyph));
    exports.AnnularWedge = AnnularWedge;
    _a = AnnularWedge;
    AnnularWedge.__name__ = "AnnularWedge";
    (function () {
        _a.prototype.default_view = AnnularWedgeView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(function (_b) {
            return ({
                direction: [enums_1.Direction, "anticlock"],
                inner_radius: [p.DistanceSpec, { field: "inner_radius" }],
                outer_radius: [p.DistanceSpec, { field: "outer_radius" }],
                start_angle: [p.AngleSpec, { field: "start_angle" }],
                end_angle: [p.AngleSpec, { field: "end_angle" }],
            });
        });
    })();
},
/* models/glyphs/annulus.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var types_1 = require(139) /* ../../core/types */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var platform_1 = require(142) /* ../../core/util/platform */;
    var selection_1 = require(187) /* ../selections/selection */;
    var AnnulusView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AnnulusView, _super);
        function AnnulusView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AnnulusView.prototype._map_data = function () {
            if (this.model.properties.inner_radius.units == "data")
                this.sinner_radius = this.sdist(this.renderer.xscale, this._x, this.inner_radius);
            else
                this.sinner_radius = (0, types_1.to_screen)(this.inner_radius);
            if (this.model.properties.outer_radius.units == "data")
                this.souter_radius = this.sdist(this.renderer.xscale, this._x, this.outer_radius);
            else
                this.souter_radius = (0, types_1.to_screen)(this.outer_radius);
        };
        AnnulusView.prototype._render = function (ctx, indices, data) {
            var e_1, _b, e_2, _c;
            var _d = data !== null && data !== void 0 ? data : this, sx = _d.sx, sy = _d.sy, sinner_radius = _d.sinner_radius, souter_radius = _d.souter_radius;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var sinner_radius_i = sinner_radius[i];
                    var souter_radius_i = souter_radius[i];
                    if (!isFinite(sx_i + sy_i + sinner_radius_i + souter_radius_i))
                        continue;
                    // Because this visual has a whole in it, it proved "challenging"
                    // for some browsers to render if drawn in one go --- i.e. it did not
                    // work on IE. If we render in two parts (upper and lower part),
                    // it is unambiguous what part should be filled. The line is
                    // better drawn in one go though, otherwise the part where the pieces
                    // meet will not be fully closed due to aa.
                    ctx.beginPath();
                    if (platform_1.is_ie) {
                        try {
                            // Draw two halves of the donut. Works on IE, but causes an aa line on Safari.
                            for (var _e = (e_2 = void 0, (0, tslib_1.__values)([false, true])), _f = _e.next(); !_f.done; _f = _e.next()) {
                                var clockwise = _f.value;
                                ctx.moveTo(sx_i, sy_i);
                                ctx.arc(sx_i, sy_i, sinner_radius_i, 0, Math.PI, clockwise);
                                ctx.moveTo(sx_i + souter_radius_i, sy_i);
                                ctx.arc(sx_i, sy_i, souter_radius_i, Math.PI, 0, !clockwise);
                            }
                        }
                        catch (e_2_1) {
                            e_2 = { error: e_2_1 };
                        }
                        finally {
                            try {
                                if (_f && !_f.done && (_c = _e.return))
                                    _c.call(_e);
                            }
                            finally {
                                if (e_2)
                                    throw e_2.error;
                            }
                        }
                    }
                    else {
                        // Draw donut in one go. Does not work on iE.
                        ctx.arc(sx_i, sy_i, sinner_radius_i, 0, 2 * Math.PI, true);
                        ctx.moveTo(sx_i + souter_radius_i, sy_i);
                        ctx.arc(sx_i, sy_i, souter_radius_i, 2 * Math.PI, 0, false);
                    }
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        AnnulusView.prototype._hit_point = function (geometry) {
            var _b, _c, e_3, _d;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            var x0, y0;
            var x1, y1;
            if (this.model.properties.outer_radius.units == "data") {
                x0 = x - this.max_outer_radius;
                x1 = x + this.max_outer_radius;
                y0 = y - this.max_outer_radius;
                y1 = y + this.max_outer_radius;
            }
            else {
                var sx0 = sx - this.max_outer_radius;
                var sx1 = sx + this.max_outer_radius;
                _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
                var sy0 = sy - this.max_outer_radius;
                var sy1 = sy + this.max_outer_radius;
                _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _c[0], y1 = _c[1];
            }
            var indices = [];
            try {
                for (var _e = (0, tslib_1.__values)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), _f = _e.next(); !_f.done; _f = _e.next()) {
                    var i = _f.value;
                    var or2 = Math.pow(this.souter_radius[i], 2);
                    var ir2 = Math.pow(this.sinner_radius[i], 2);
                    var _g = (0, tslib_1.__read)(this.renderer.xscale.r_compute(x, this._x[i]), 2), sx0 = _g[0], sx1 = _g[1];
                    var _h = (0, tslib_1.__read)(this.renderer.yscale.r_compute(y, this._y[i]), 2), sy0 = _h[0], sy1 = _h[1];
                    var dist = Math.pow((sx0 - sx1), 2) + Math.pow((sy0 - sy1), 2);
                    if (dist <= or2 && dist >= ir2)
                        indices.push(i);
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_f && !_f.done && (_d = _e.return))
                        _d.call(_e);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        AnnulusView.prototype.draw_legend_for_index = function (ctx, _b, index) {
            var x0 = _b.x0, y0 = _b.y0, x1 = _b.x1, y1 = _b.y1;
            var len = index + 1;
            var sx = new Array(len);
            sx[index] = (x0 + x1) / 2;
            var sy = new Array(len);
            sy[index] = (y0 + y1) / 2;
            var r = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.5;
            var sinner_radius = new Array(len);
            sinner_radius[index] = r * 0.4;
            var souter_radius = new Array(len);
            souter_radius[index] = r * 0.8;
            this._render(ctx, [index], { sx: sx, sy: sy, sinner_radius: sinner_radius, souter_radius: souter_radius }); // XXX
        };
        return AnnulusView;
    }(xy_glyph_1.XYGlyphView));
    exports.AnnulusView = AnnulusView;
    AnnulusView.__name__ = "AnnulusView";
    var Annulus = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Annulus, _super);
        function Annulus(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Annulus;
    }(xy_glyph_1.XYGlyph));
    exports.Annulus = Annulus;
    _a = Annulus;
    Annulus.__name__ = "Annulus";
    (function () {
        _a.prototype.default_view = AnnulusView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(function (_b) {
            return ({
                inner_radius: [p.DistanceSpec, { field: "inner_radius" }],
                outer_radius: [p.DistanceSpec, { field: "outer_radius" }],
            });
        });
    })();
},
/* models/glyphs/arc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var utils_1 = require(299) /* ./utils */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var types_1 = require(139) /* ../../core/types */;
    var enums_1 = require(135) /* ../../core/enums */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var ArcView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ArcView, _super);
        function ArcView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ArcView.prototype._map_data = function () {
            if (this.model.properties.radius.units == "data")
                this.sradius = this.sdist(this.renderer.xscale, this._x, this.radius);
            else
                this.sradius = (0, types_1.to_screen)(this.radius);
        };
        ArcView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            if (this.visuals.line.doit) {
                var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, sradius = _c.sradius, start_angle = _c.start_angle, end_angle = _c.end_angle;
                var anticlock = this.model.direction == "anticlock";
                try {
                    for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                        var i = indices_1_1.value;
                        var sx_i = sx[i];
                        var sy_i = sy[i];
                        var sradius_i = sradius[i];
                        var start_angle_i = start_angle.get(i);
                        var end_angle_i = end_angle.get(i);
                        if (!isFinite(sx_i + sy_i + sradius_i + start_angle_i + end_angle_i))
                            continue;
                        ctx.beginPath();
                        ctx.arc(sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                        this.visuals.line.set_vectorize(ctx, i);
                        ctx.stroke();
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                            _b.call(indices_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
        };
        ArcView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        };
        return ArcView;
    }(xy_glyph_1.XYGlyphView));
    exports.ArcView = ArcView;
    ArcView.__name__ = "ArcView";
    var Arc = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Arc, _super);
        function Arc(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Arc;
    }(xy_glyph_1.XYGlyph));
    exports.Arc = Arc;
    _a = Arc;
    Arc.__name__ = "Arc";
    (function () {
        _a.prototype.default_view = ArcView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(function (_b) {
            return ({
                direction: [enums_1.Direction, "anticlock"],
                radius: [p.DistanceSpec, { field: "radius" }],
                start_angle: [p.AngleSpec, { field: "start_angle" }],
                end_angle: [p.AngleSpec, { field: "end_angle" }],
            });
        });
    })();
},
/* models/glyphs/bezier.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var glyph_1 = require(294) /* ./glyph */;
    var utils_1 = require(299) /* ./utils */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    // algorithm adapted from http://stackoverflow.com/a/14429749/3406693
    function _cbb(x0, y0, x1, y1, x2, y2, x3, y3) {
        var tvalues = [];
        var bounds = [[], []];
        for (var i = 0; i <= 2; i++) {
            var a = void 0, b = void 0, c = void 0;
            if (i === 0) {
                b = ((6 * x0) - (12 * x1)) + (6 * x2);
                a = (((-3 * x0) + (9 * x1)) - (9 * x2)) + (3 * x3);
                c = (3 * x1) - (3 * x0);
            }
            else {
                b = ((6 * y0) - (12 * y1)) + (6 * y2);
                a = (((-3 * y0) + (9 * y1)) - (9 * y2)) + (3 * y3);
                c = (3 * y1) - (3 * y0);
            }
            if (Math.abs(a) < 1e-12) { // Numerical robustness
                if (Math.abs(b) < 1e-12) // Numerical robustness
                    continue;
                var t = -c / b;
                if (0 < t && t < 1)
                    tvalues.push(t);
                continue;
            }
            var b2ac = (b * b) - (4 * c * a);
            var sqrtb2ac = Math.sqrt(b2ac);
            if (b2ac < 0)
                continue;
            var t1 = (-b + sqrtb2ac) / (2 * a);
            if (0 < t1 && t1 < 1)
                tvalues.push(t1);
            var t2 = (-b - sqrtb2ac) / (2 * a);
            if (0 < t2 && t2 < 1)
                tvalues.push(t2);
        }
        var j = tvalues.length;
        var jlen = j;
        while (j--) {
            var t = tvalues[j];
            var mt = 1 - t;
            var x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
            bounds[0][j] = x;
            var y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
            bounds[1][j] = y;
        }
        bounds[0][jlen] = x0;
        bounds[1][jlen] = y0;
        bounds[0][jlen + 1] = x3;
        bounds[1][jlen + 1] = y3;
        return [
            Math.min.apply(Math, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(bounds[0]), false)),
            Math.max.apply(Math, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(bounds[1]), false)),
            Math.max.apply(Math, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(bounds[0]), false)),
            Math.min.apply(Math, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(bounds[1]), false)),
        ];
    }
    var BezierView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BezierView, _super);
        function BezierView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BezierView.prototype._project_data = function () {
            projections_1.inplace.project_xy(this._x0, this._y0);
            projections_1.inplace.project_xy(this._x1, this._y1);
        };
        BezierView.prototype._index_data = function (index) {
            var _b = this, data_size = _b.data_size, _x0 = _b._x0, _y0 = _b._y0, _x1 = _b._x1, _y1 = _b._y1, _cx0 = _b._cx0, _cy0 = _b._cy0, _cx1 = _b._cx1, _cy1 = _b._cy1;
            for (var i = 0; i < data_size; i++) {
                var x0_i = _x0[i];
                var y0_i = _y0[i];
                var x1_i = _x1[i];
                var y1_i = _y1[i];
                var cx0_i = _cx0[i];
                var cy0_i = _cy0[i];
                var cx1_i = _cx1[i];
                var cy1_i = _cy1[i];
                if (!isFinite(x0_i + x1_i + y0_i + y1_i + cx0_i + cy0_i + cx1_i + cy1_i))
                    index.add_empty();
                else {
                    var _c = (0, tslib_1.__read)(_cbb(x0_i, y0_i, x1_i, y1_i, cx0_i, cy0_i, cx1_i, cy1_i), 4), x0 = _c[0], y0 = _c[1], x1 = _c[2], y1 = _c[3];
                    index.add_rect(x0, y0, x1, y1);
                }
            }
        };
        BezierView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            if (this.visuals.line.doit) {
                var _c = data !== null && data !== void 0 ? data : this, sx0 = _c.sx0, sy0 = _c.sy0, sx1 = _c.sx1, sy1 = _c.sy1, scx0 = _c.scx0, scy0 = _c.scy0, scx1 = _c.scx1, scy1 = _c.scy1;
                try {
                    for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                        var i = indices_1_1.value;
                        var sx0_i = sx0[i];
                        var sy0_i = sy0[i];
                        var sx1_i = sx1[i];
                        var sy1_i = sy1[i];
                        var scx0_i = scx0[i];
                        var scy0_i = scy0[i];
                        var scx1_i = scx1[i];
                        var scy1_i = scy1[i];
                        if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i + scx0_i + scy0_i + scx1_i + scy1_i))
                            continue;
                        ctx.beginPath();
                        ctx.moveTo(sx0_i, sy0_i);
                        ctx.bezierCurveTo(scx0_i, scy0_i, scx1_i, scy1_i, sx1_i, sy1_i);
                        this.visuals.line.set_vectorize(ctx, i);
                        ctx.stroke();
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                            _b.call(indices_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
        };
        BezierView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        };
        BezierView.prototype.scenterxy = function () {
            throw new Error(this + ".scenterxy() is not implemented");
        };
        return BezierView;
    }(glyph_1.GlyphView));
    exports.BezierView = BezierView;
    BezierView.__name__ = "BezierView";
    var Bezier = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Bezier, _super);
        function Bezier(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Bezier;
    }(glyph_1.Glyph));
    exports.Bezier = Bezier;
    _a = Bezier;
    Bezier.__name__ = "Bezier";
    (function () {
        _a.prototype.default_view = BezierView;
        _a.define(function (_b) {
            return ({
                x0: [p.XCoordinateSpec, { field: "x0" }],
                y0: [p.YCoordinateSpec, { field: "y0" }],
                x1: [p.XCoordinateSpec, { field: "x1" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
                cx0: [p.XCoordinateSpec, { field: "cx0" }],
                cy0: [p.YCoordinateSpec, { field: "cy0" }],
                cx1: [p.XCoordinateSpec, { field: "cx1" }],
                cy1: [p.YCoordinateSpec, { field: "cy1" }],
            });
        });
        _a.mixins(property_mixins_1.LineVector);
    })();
},
/* models/glyphs/circle.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var types_1 = require(139) /* ../../core/types */;
    var enums_1 = require(135) /* ../../core/enums */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var array_1 = require(126) /* ../../core/util/array */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var selection_1 = require(187) /* ../selections/selection */;
    var CircleView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CircleView, _super);
        function CircleView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CircleView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var webgl, MarkerGL;
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _b.sent();
                            webgl = this.renderer.plot_view.canvas_view.webgl;
                            if (!(webgl === null || webgl === void 0 ? void 0 : webgl.regl_wrapper.has_webgl))
                                return [3 /*break*/, 3];
                            return [4 /*yield*/, Promise.resolve().then(function () { return (0, tslib_1.__importStar)(require(541) /* ./webgl/markers */); })];
                        case 2:
                            MarkerGL = (_b.sent()).MarkerGL;
                            this.glglyph = new MarkerGL(webgl.regl_wrapper, this, "circle");
                            _b.label = 3;
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        Object.defineProperty(CircleView.prototype, "use_radius", {
            get: function () {
                return !(this.radius.is_Scalar() && isNaN(this.radius.value));
            },
            enumerable: false,
            configurable: true
        });
        CircleView.prototype._set_data = function (indices) {
            var _this = this;
            _super.prototype._set_data.call(this, indices);
            var max_size = (function () {
                if (_this.use_radius)
                    return 2 * _this.max_radius;
                else {
                    var size = _this.size;
                    return size.is_Scalar() ? size.value : (0, arrayable_1.max)(size.array);
                }
            })();
            this._configure("max_size", { value: max_size });
        };
        CircleView.prototype._map_data = function () {
            // XXX: Order is important here: size is always present (at least
            // a default), but radius is only present if a user specifies it.
            if (this.use_radius) {
                if (this.model.properties.radius.units == "data") {
                    switch (this.model.radius_dimension) {
                        case "x": {
                            this.sradius = this.sdist(this.renderer.xscale, this._x, this.radius);
                            break;
                        }
                        case "y": {
                            this.sradius = this.sdist(this.renderer.yscale, this._y, this.radius);
                            break;
                        }
                        case "max": {
                            var sradius_x = this.sdist(this.renderer.xscale, this._x, this.radius);
                            var sradius_y_1 = this.sdist(this.renderer.yscale, this._y, this.radius);
                            this.sradius = (0, arrayable_1.map)(sradius_x, function (s, i) { return Math.max(s, sradius_y_1[i]); });
                            break;
                        }
                        case "min": {
                            var sradius_x = this.sdist(this.renderer.xscale, this._x, this.radius);
                            var sradius_y_2 = this.sdist(this.renderer.yscale, this._y, this.radius);
                            this.sradius = (0, arrayable_1.map)(sradius_x, function (s, i) { return Math.min(s, sradius_y_2[i]); });
                            break;
                        }
                    }
                }
                else
                    this.sradius = (0, types_1.to_screen)(this.radius);
            }
            else {
                var ssize = types_1.ScreenArray.from(this.size);
                this.sradius = (0, arrayable_1.map)(ssize, function (s) { return s / 2; });
            }
        };
        CircleView.prototype._mask_data = function () {
            var _this = this;
            var frame = this.renderer.plot_view.frame;
            var shr = frame.x_target;
            var svr = frame.y_target;
            var hr;
            var vr;
            if (this.use_radius && this.model.properties.radius.units == "data") {
                hr = shr.map(function (x) { return _this.renderer.xscale.invert(x); }).widen(this.max_radius);
                vr = svr.map(function (y) { return _this.renderer.yscale.invert(y); }).widen(this.max_radius);
            }
            else {
                hr = shr.widen(this.max_size).map(function (x) { return _this.renderer.xscale.invert(x); });
                vr = svr.widen(this.max_size).map(function (y) { return _this.renderer.yscale.invert(y); });
            }
            return this.index.indices({
                x0: hr.start, x1: hr.end,
                y0: vr.start, y1: vr.end,
            });
        };
        CircleView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, sradius = _c.sradius;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var sradius_i = sradius[i];
                    if (!isFinite(sx_i + sy_i + sradius_i))
                        continue;
                    ctx.beginPath();
                    ctx.arc(sx_i, sy_i, sradius_i, 0, 2 * Math.PI, false);
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        CircleView.prototype._hit_point = function (geometry) {
            var _b, _c, e_2, _d, e_3, _e;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            var hit_dilation = this.model.hit_dilation;
            var x0, x1, y0, y1;
            if (this.use_radius && this.model.properties.radius.units == "data") {
                x0 = x - this.max_radius * hit_dilation;
                x1 = x + this.max_radius * hit_dilation;
                y0 = y - this.max_radius * hit_dilation;
                y1 = y + this.max_radius * hit_dilation;
            }
            else {
                var sx0 = sx - this.max_size * hit_dilation;
                var sx1 = sx + this.max_size * hit_dilation;
                _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
                var sy0 = sy - this.max_size * hit_dilation;
                var sy1 = sy + this.max_size * hit_dilation;
                _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _c[0], y1 = _c[1];
            }
            var candidates = this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 });
            var indices = [];
            if (this.use_radius && this.model.properties.radius.units == "data") {
                try {
                    for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                        var i = candidates_1_1.value;
                        var r2 = Math.pow((this.sradius[i] * hit_dilation), 2);
                        var _f = (0, tslib_1.__read)(this.renderer.xscale.r_compute(x, this._x[i]), 2), sx0 = _f[0], sx1 = _f[1];
                        var _g = (0, tslib_1.__read)(this.renderer.yscale.r_compute(y, this._y[i]), 2), sy0 = _g[0], sy1 = _g[1];
                        var dist = Math.pow((sx0 - sx1), 2) + Math.pow((sy0 - sy1), 2);
                        if (dist <= r2) {
                            indices.push(i);
                        }
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (candidates_1_1 && !candidates_1_1.done && (_d = candidates_1.return))
                            _d.call(candidates_1);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
            }
            else {
                try {
                    for (var candidates_2 = (0, tslib_1.__values)(candidates), candidates_2_1 = candidates_2.next(); !candidates_2_1.done; candidates_2_1 = candidates_2.next()) {
                        var i = candidates_2_1.value;
                        var r2 = Math.pow((this.sradius[i] * hit_dilation), 2);
                        var dist = Math.pow((this.sx[i] - sx), 2) + Math.pow((this.sy[i] - sy), 2);
                        if (dist <= r2) {
                            indices.push(i);
                        }
                    }
                }
                catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                }
                finally {
                    try {
                        if (candidates_2_1 && !candidates_2_1.done && (_e = candidates_2.return))
                            _e.call(candidates_2);
                    }
                    finally {
                        if (e_3)
                            throw e_3.error;
                    }
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        CircleView.prototype._hit_span = function (geometry) {
            var _b, _c, _d, _e;
            var sx = geometry.sx, sy = geometry.sy;
            var bounds = this.bounds();
            var x0, x1, y0, y1;
            if (geometry.direction == "h") {
                // use circle bounds instead of current pointer y coordinates
                var sx0 = void 0, sx1 = void 0;
                y0 = bounds.y0;
                y1 = bounds.y1;
                if (this.use_radius && this.model.properties.radius.units == "data") {
                    sx0 = sx - this.max_radius;
                    sx1 = sx + this.max_radius;
                    _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
                }
                else {
                    var ms = this.max_size / 2;
                    sx0 = sx - ms;
                    sx1 = sx + ms;
                    _c = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _c[0], x1 = _c[1];
                }
            }
            else {
                // use circle bounds instead of current pointer x coordinates
                var sy0 = void 0, sy1 = void 0;
                x0 = bounds.x0;
                x1 = bounds.x1;
                if (this.use_radius && this.model.properties.radius.units == "data") {
                    sy0 = sy - this.max_radius;
                    sy1 = sy + this.max_radius;
                    _d = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _d[0], y1 = _d[1];
                }
                else {
                    var ms = this.max_size / 2;
                    sy0 = sy - ms;
                    sy1 = sy + ms;
                    _e = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _e[0], y1 = _e[1];
                }
            }
            var indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), false);
            return new selection_1.Selection({ indices: indices });
        };
        CircleView.prototype._hit_rect = function (geometry) {
            var sx0 = geometry.sx0, sx1 = geometry.sx1, sy0 = geometry.sy0, sy1 = geometry.sy1;
            var _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
            var _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _c[0], y1 = _c[1];
            var indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), false);
            return new selection_1.Selection({ indices: indices });
        };
        CircleView.prototype._hit_poly = function (geometry) {
            var sx = geometry.sx, sy = geometry.sy;
            // TODO (bev) use spatial index to pare candidate list
            var candidates = (0, array_1.range)(0, this.sx.length);
            var indices = [];
            for (var i = 0, end = candidates.length; i < end; i++) {
                var index = candidates[i];
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        // circle does not inherit from marker (since it also accepts radius) so we
        // must supply a draw_legend for it  here
        CircleView.prototype.draw_legend_for_index = function (ctx, _b, index) {
            var x0 = _b.x0, y0 = _b.y0, x1 = _b.x1, y1 = _b.y1;
            // using objects like this seems a little wonky, since the keys are coerced to
            // stings, but it works
            var len = index + 1;
            var sx = new Array(len);
            sx[index] = (x0 + x1) / 2;
            var sy = new Array(len);
            sy[index] = (y0 + y1) / 2;
            var sradius = new Array(len);
            sradius[index] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.2;
            this._render(ctx, [index], { sx: sx, sy: sy, sradius: sradius }); // XXX
        };
        return CircleView;
    }(xy_glyph_1.XYGlyphView));
    exports.CircleView = CircleView;
    CircleView.__name__ = "CircleView";
    var Circle = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Circle, _super);
        function Circle(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Circle;
    }(xy_glyph_1.XYGlyph));
    exports.Circle = Circle;
    _a = Circle;
    Circle.__name__ = "Circle";
    (function () {
        _a.prototype.default_view = CircleView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(function (_b) {
            var Number = _b.Number;
            return ({
                angle: [p.AngleSpec, 0],
                size: [p.ScreenSizeSpec, { value: 4 }],
                radius: [p.NullDistanceSpec, null],
                radius_dimension: [enums_1.RadiusDimension, "x"],
                hit_dilation: [Number, 1.0],
            });
        });
    })();
},
/* models/glyphs/ellipse.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var ellipse_oval_1 = require(389) /* ./ellipse_oval */;
    var EllipseView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EllipseView, _super);
        function EllipseView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return EllipseView;
    }(ellipse_oval_1.EllipseOvalView));
    exports.EllipseView = EllipseView;
    EllipseView.__name__ = "EllipseView";
    var Ellipse = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Ellipse, _super);
        function Ellipse(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Ellipse;
    }(ellipse_oval_1.EllipseOval));
    exports.Ellipse = Ellipse;
    _a = Ellipse;
    Ellipse.__name__ = "Ellipse";
    (function () {
        _a.prototype.default_view = EllipseView;
    })();
},
/* models/glyphs/ellipse_oval.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var center_rotatable_1 = require(390) /* ./center_rotatable */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var types_1 = require(139) /* ../../core/types */;
    var selection_1 = require(187) /* ../selections/selection */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var EllipseOvalView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EllipseOvalView, _super);
        function EllipseOvalView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        EllipseOvalView.prototype._map_data = function () {
            if (this.model.properties.width.units == "data")
                this.sw = this.sdist(this.renderer.xscale, this._x, this.width, "center");
            else
                this.sw = (0, types_1.to_screen)(this.width);
            if (this.model.properties.height.units == "data")
                this.sh = this.sdist(this.renderer.yscale, this._y, this.height, "center");
            else
                this.sh = (0, types_1.to_screen)(this.height);
        };
        EllipseOvalView.prototype._render = function (ctx, indices, data) {
            var e_1, _a;
            var _b = data !== null && data !== void 0 ? data : this, sx = _b.sx, sy = _b.sy, sw = _b.sw, sh = _b.sh, angle = _b.angle;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var sw_i = sw[i];
                    var sh_i = sh[i];
                    var angle_i = angle.get(i);
                    if (!isFinite(sx_i + sy_i + sw_i + sh_i + angle_i))
                        continue;
                    ctx.beginPath();
                    ctx.ellipse(sx_i, sy_i, sw_i / 2, sh_i / 2, angle_i, 0, 2 * Math.PI);
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_a = indices_1.return))
                        _a.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        EllipseOvalView.prototype._hit_point = function (geometry) {
            var _a, _b, e_2, _c;
            var x0, x1, y0, y1, cond, sx0, sx1, sy0, sy1;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            if (this.model.properties.width.units == "data") {
                x0 = x - this.max_width;
                x1 = x + this.max_width;
            }
            else {
                sx0 = sx - this.max_width;
                sx1 = sx + this.max_width;
                _a = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _a[0], x1 = _a[1];
            }
            if (this.model.properties.height.units == "data") {
                y0 = y - this.max_height;
                y1 = y + this.max_height;
            }
            else {
                sy0 = sy - this.max_height;
                sy1 = sy + this.max_height;
                _b = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _b[0], y1 = _b[1];
            }
            var candidates = this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 });
            var indices = [];
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var i = candidates_1_1.value;
                    cond = hittest.point_in_ellipse(sx, sy, this.angle.get(i), this.sh[i] / 2, this.sw[i] / 2, this.sx[i], this.sy[i]);
                    if (cond) {
                        indices.push(i);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_c = candidates_1.return))
                        _c.call(candidates_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        EllipseOvalView.prototype.draw_legend_for_index = function (ctx, _a, index) {
            var x0 = _a.x0, y0 = _a.y0, x1 = _a.x1, y1 = _a.y1;
            var n = index + 1;
            var sx = new Array(n);
            sx[index] = (x0 + x1) / 2;
            var sy = new Array(n);
            sy[index] = (y0 + y1) / 2;
            var scale = this.sw[index] / this.sh[index];
            var d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
            var sw = new Array(n);
            var sh = new Array(n);
            if (scale > 1) {
                sw[index] = d;
                sh[index] = d / scale;
            }
            else {
                sw[index] = d * scale;
                sh[index] = d;
            }
            var angle = new p.UniformScalar(0, n); // don't attempt to match glyph angle
            this._render(ctx, [index], { sx: sx, sy: sy, sw: sw, sh: sh, angle: angle }); // XXX
        };
        return EllipseOvalView;
    }(center_rotatable_1.CenterRotatableView));
    exports.EllipseOvalView = EllipseOvalView;
    EllipseOvalView.__name__ = "EllipseOvalView";
    var EllipseOval = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EllipseOval, _super);
        function EllipseOval(attrs) {
            return _super.call(this, attrs) || this;
        }
        return EllipseOval;
    }(center_rotatable_1.CenterRotatable));
    exports.EllipseOval = EllipseOval;
    EllipseOval.__name__ = "EllipseOval";
},
/* models/glyphs/center_rotatable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var CenterRotatableView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CenterRotatableView, _super);
        function CenterRotatableView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(CenterRotatableView.prototype, "max_w2", {
            get: function () {
                return this.model.properties.width.units == "data" ? this.max_width / 2 : 0;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CenterRotatableView.prototype, "max_h2", {
            get: function () {
                return this.model.properties.height.units == "data" ? this.max_height / 2 : 0;
            },
            enumerable: false,
            configurable: true
        });
        CenterRotatableView.prototype._bounds = function (_b) {
            var x0 = _b.x0, x1 = _b.x1, y0 = _b.y0, y1 = _b.y1;
            var _c = this, max_w2 = _c.max_w2, max_h2 = _c.max_h2;
            return {
                x0: x0 - max_w2,
                x1: x1 + max_w2,
                y0: y0 - max_h2,
                y1: y1 + max_h2,
            };
        };
        return CenterRotatableView;
    }(xy_glyph_1.XYGlyphView));
    exports.CenterRotatableView = CenterRotatableView;
    CenterRotatableView.__name__ = "CenterRotatableView";
    var CenterRotatable = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CenterRotatable, _super);
        function CenterRotatable(attrs) {
            return _super.call(this, attrs) || this;
        }
        return CenterRotatable;
    }(xy_glyph_1.XYGlyph));
    exports.CenterRotatable = CenterRotatable;
    _a = CenterRotatable;
    CenterRotatable.__name__ = "CenterRotatable";
    (function () {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(function (_b) {
            return ({
                angle: [p.AngleSpec, 0],
                width: [p.DistanceSpec, { field: "width" }],
                height: [p.DistanceSpec, { field: "height" }],
            });
        });
    })();
},
/* models/glyphs/hbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var box_1 = require(392) /* ./box */;
    var types_1 = require(139) /* ../../core/types */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var HBarView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HBarView, _super);
        function HBarView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        HBarView.prototype.scenterxy = function (i) {
            var scx = (this.sleft[i] + this.sright[i]) / 2;
            var scy = this.sy[i];
            return [scx, scy];
        };
        HBarView.prototype._lrtb = function (i) {
            var left_i = this._left[i];
            var right_i = this._right[i];
            var y_i = this._y[i];
            var half_height_i = this.height.get(i) / 2;
            var l = Math.min(left_i, right_i);
            var r = Math.max(left_i, right_i);
            var t = y_i + half_height_i;
            var b = y_i - half_height_i;
            return [l, r, t, b];
        };
        HBarView.prototype._map_data = function () {
            this.sy = this.renderer.yscale.v_compute(this._y);
            this.sh = this.sdist(this.renderer.yscale, this._y, this.height, "center");
            this.sleft = this.renderer.xscale.v_compute(this._left);
            this.sright = this.renderer.xscale.v_compute(this._right);
            var n = this.sy.length;
            this.stop = new types_1.ScreenArray(n);
            this.sbottom = new types_1.ScreenArray(n);
            for (var i = 0; i < n; i++) {
                this.stop[i] = this.sy[i] - this.sh[i] / 2;
                this.sbottom[i] = this.sy[i] + this.sh[i] / 2;
            }
            this._clamp_viewport();
        };
        return HBarView;
    }(box_1.BoxView));
    exports.HBarView = HBarView;
    HBarView.__name__ = "HBarView";
    var HBar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HBar, _super);
        function HBar(attrs) {
            return _super.call(this, attrs) || this;
        }
        return HBar;
    }(box_1.Box));
    exports.HBar = HBar;
    _a = HBar;
    HBar.__name__ = "HBar";
    (function () {
        _a.prototype.default_view = HBarView;
        _a.define(function (_b) {
            return ({
                left: [p.XCoordinateSpec, { value: 0 }],
                y: [p.YCoordinateSpec, { field: "y" }],
                height: [p.NumberSpec, { value: 1 }],
                right: [p.XCoordinateSpec, { field: "right" }],
            });
        });
    })();
},
/* models/glyphs/box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var glyph_1 = require(294) /* ./glyph */;
    var utils_1 = require(299) /* ./utils */;
    var selection_1 = require(187) /* ../selections/selection */;
    var BoxView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxView, _super);
        function BoxView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BoxView.prototype.get_anchor_point = function (anchor, i, _spt) {
            var left = Math.min(this.sleft[i], this.sright[i]);
            var right = Math.max(this.sright[i], this.sleft[i]);
            var top = Math.min(this.stop[i], this.sbottom[i]); // screen coordinates !!!
            var bottom = Math.max(this.sbottom[i], this.stop[i]); //
            switch (anchor) {
                case "top_left": return { x: left, y: top };
                case "top":
                case "top_center": return { x: (left + right) / 2, y: top };
                case "top_right": return { x: right, y: top };
                case "bottom_left": return { x: left, y: bottom };
                case "bottom":
                case "bottom_center": return { x: (left + right) / 2, y: bottom };
                case "bottom_right": return { x: right, y: bottom };
                case "left":
                case "center_left": return { x: left, y: (top + bottom) / 2 };
                case "center":
                case "center_center": return { x: (left + right) / 2, y: (top + bottom) / 2 };
                case "right":
                case "center_right": return { x: right, y: (top + bottom) / 2 };
            }
        };
        BoxView.prototype._index_data = function (index) {
            var min = Math.min, max = Math.max;
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                var _b = (0, tslib_1.__read)(this._lrtb(i), 4), l = _b[0], r = _b[1], t = _b[2], b = _b[3];
                index.add_rect(min(l, r), min(t, b), max(r, l), max(t, b));
            }
        };
        BoxView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sleft = _c.sleft, sright = _c.sright, stop = _c.stop, sbottom = _c.sbottom;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sleft_i = sleft[i];
                    var stop_i = stop[i];
                    var sright_i = sright[i];
                    var sbottom_i = sbottom[i];
                    if (!isFinite(sleft_i + stop_i + sright_i + sbottom_i))
                        continue;
                    ctx.beginPath();
                    ctx.rect(sleft_i, stop_i, sright_i - sleft_i, sbottom_i - stop_i);
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        // We need to clamp the endpoints inside the viewport, because various browser canvas
        // implementations have issues drawing rects with enpoints far outside the viewport
        BoxView.prototype._clamp_viewport = function () {
            var hr = this.renderer.plot_view.frame.bbox.h_range;
            var vr = this.renderer.plot_view.frame.bbox.v_range;
            var n = this.stop.length;
            for (var i = 0; i < n; i++) {
                this.stop[i] = Math.max(this.stop[i], vr.start);
                this.sbottom[i] = Math.min(this.sbottom[i], vr.end);
                this.sleft[i] = Math.max(this.sleft[i], hr.start);
                this.sright[i] = Math.min(this.sright[i], hr.end);
            }
        };
        BoxView.prototype._hit_rect = function (geometry) {
            return this._hit_rect_against_index(geometry);
        };
        BoxView.prototype._hit_point = function (geometry) {
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            var indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x, y0: y, x1: x, y1: y })), false);
            return new selection_1.Selection({ indices: indices });
        };
        BoxView.prototype._hit_span = function (geometry) {
            var sx = geometry.sx, sy = geometry.sy;
            var indices;
            if (geometry.direction == "v") {
                var y = this.renderer.yscale.invert(sy);
                var hr = this.renderer.plot_view.frame.bbox.h_range;
                var _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(hr.start, hr.end), 2), x0 = _b[0], x1 = _b[1];
                indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x0, y0: y, x1: x1, y1: y })), false);
            }
            else {
                var x = this.renderer.xscale.invert(sx);
                var vr = this.renderer.plot_view.frame.bbox.v_range;
                var _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(vr.start, vr.end), 2), y0 = _c[0], y1 = _c[1];
                indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x, y0: y0, x1: x, y1: y1 })), false);
            }
            return new selection_1.Selection({ indices: indices });
        };
        BoxView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        };
        return BoxView;
    }(glyph_1.GlyphView));
    exports.BoxView = BoxView;
    BoxView.__name__ = "BoxView";
    var Box = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Box, _super);
        function Box(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Box;
    }(glyph_1.Glyph));
    exports.Box = Box;
    _a = Box;
    Box.__name__ = "Box";
    (function () {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
    })();
},
/* models/glyphs/hex_tile.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var glyph_1 = require(294) /* ./glyph */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var enums_1 = require(135) /* ../../core/enums */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var utils_1 = require(299) /* ./utils */;
    var selection_1 = require(187) /* ../selections/selection */;
    var HexTileView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HexTileView, _super);
        function HexTileView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        HexTileView.prototype.scenterxy = function (i) {
            var scx = this.sx[i];
            var scy = this.sy[i];
            return [scx, scy];
        };
        HexTileView.prototype._set_data = function () {
            var _b = this.model, orientation = _b.orientation, size = _b.size, aspect_scale = _b.aspect_scale;
            var _c = this, q = _c.q, r = _c.r;
            var n = this.q.length;
            this._x = new Float64Array(n);
            this._y = new Float64Array(n);
            var _d = this, _x = _d._x, _y = _d._y;
            var sqrt3 = Math.sqrt(3);
            if (orientation == "pointytop") {
                for (var i = 0; i < n; i++) {
                    var q_i = q.get(i);
                    var r2_i = r.get(i) / 2;
                    _x[i] = size * sqrt3 * (q_i + r2_i) / aspect_scale;
                    _y[i] = -3 * size * r2_i;
                }
            }
            else {
                for (var i = 0; i < n; i++) {
                    var q2_i = q.get(i) / 2;
                    var r_i = r.get(i);
                    _x[i] = 3 * size * q2_i;
                    _y[i] = -size * sqrt3 * (r_i + q2_i) * aspect_scale;
                }
            }
        };
        HexTileView.prototype._project_data = function () {
            projections_1.inplace.project_xy(this._x, this._y);
        };
        HexTileView.prototype._index_data = function (index) {
            var _b;
            var ysize = this.model.size;
            var xsize = Math.sqrt(3) * ysize / 2;
            if (this.model.orientation == "flattop") {
                _b = (0, tslib_1.__read)([ysize, xsize], 2), xsize = _b[0], ysize = _b[1];
                ysize *= this.model.aspect_scale;
            }
            else
                xsize /= this.model.aspect_scale;
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                var x = this._x[i];
                var y = this._y[i];
                index.add_rect(x - xsize, y - ysize, x + xsize, y + ysize);
            }
        };
        // overriding map_data instead of _map_data because the default automatic mappings
        // for other glyphs (with cartesian coordinates) is not useful
        HexTileView.prototype.map_data = function () {
            var _b, _c;
            _b = (0, tslib_1.__read)(this.renderer.coordinates.map_to_screen(this._x, this._y), 2), this.sx = _b[0], this.sy = _b[1];
            _c = (0, tslib_1.__read)(this._get_unscaled_vertices(), 2), this.svx = _c[0], this.svy = _c[1];
        };
        HexTileView.prototype._get_unscaled_vertices = function () {
            var size = this.model.size;
            var aspect_scale = this.model.aspect_scale;
            if (this.model.orientation == "pointytop") {
                var rscale = this.renderer.yscale;
                var hscale = this.renderer.xscale;
                var r = Math.abs(rscale.compute(0) - rscale.compute(size)); // assumes linear scale
                var h = Math.sqrt(3) / 2 * Math.abs(hscale.compute(0) - hscale.compute(size)) / aspect_scale; // assumes linear scale
                var r2 = r / 2.0;
                var svx = [0, -h, -h, 0, h, h];
                var svy = [r, r2, -r2, -r, -r2, r2];
                return [svx, svy];
            }
            else {
                var rscale = this.renderer.xscale;
                var hscale = this.renderer.yscale;
                var r = Math.abs(rscale.compute(0) - rscale.compute(size)); // assumes linear scale
                var h = Math.sqrt(3) / 2 * Math.abs(hscale.compute(0) - hscale.compute(size)) * aspect_scale; // assumes linear scale
                var r2 = r / 2.0;
                var svx = [r, r2, -r2, -r, -r2, r2];
                var svy = [0, -h, -h, 0, h, h];
                return [svx, svy];
            }
        };
        HexTileView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, svx = _c.svx, svy = _c.svy, scale = _c.scale;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var scale_i = scale.get(i);
                    if (!isFinite(sx_i + sy_i + scale_i))
                        continue;
                    ctx.translate(sx_i, sy_i);
                    ctx.beginPath();
                    for (var j = 0; j < 6; j++) {
                        ctx.lineTo(svx[j] * scale_i, svy[j] * scale_i);
                    }
                    ctx.closePath();
                    ctx.translate(-sx_i, -sy_i);
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        HexTileView.prototype._hit_point = function (geometry) {
            var e_2, _b;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            var candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            var indices = [];
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var i = candidates_1_1.value;
                    if (hittest.point_in_poly(sx - this.sx[i], sy - this.sy[i], this.svx, this.svy)) {
                        indices.push(i);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_b = candidates_1.return))
                        _b.call(candidates_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        HexTileView.prototype._hit_span = function (geometry) {
            var sx = geometry.sx, sy = geometry.sy;
            var indices;
            if (geometry.direction == "v") {
                var y = this.renderer.yscale.invert(sy);
                var hr = this.renderer.plot_view.frame.bbox.h_range;
                var _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(hr.start, hr.end), 2), x0 = _b[0], x1 = _b[1];
                indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x0, y0: y, x1: x1, y1: y })), false);
            }
            else {
                var x = this.renderer.xscale.invert(sx);
                var vr = this.renderer.plot_view.frame.bbox.v_range;
                var _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(vr.start, vr.end), 2), y0 = _c[0], y1 = _c[1];
                indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x, y0: y0, x1: x, y1: y1 })), false);
            }
            return new selection_1.Selection({ indices: indices });
        };
        HexTileView.prototype._hit_rect = function (geometry) {
            var sx0 = geometry.sx0, sx1 = geometry.sx1, sy0 = geometry.sy0, sy1 = geometry.sy1;
            var _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
            var _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _c[0], y1 = _c[1];
            var indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), false);
            return new selection_1.Selection({ indices: indices });
        };
        HexTileView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        };
        return HexTileView;
    }(glyph_1.GlyphView));
    exports.HexTileView = HexTileView;
    HexTileView.__name__ = "HexTileView";
    var HexTile = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HexTile, _super);
        function HexTile(attrs) {
            return _super.call(this, attrs) || this;
        }
        return HexTile;
    }(glyph_1.Glyph));
    exports.HexTile = HexTile;
    _a = HexTile;
    HexTile.__name__ = "HexTile";
    (function () {
        _a.prototype.default_view = HexTileView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(function (_b) {
            var Number = _b.Number;
            return ({
                r: [p.NumberSpec, { field: "r" }],
                q: [p.NumberSpec, { field: "q" }],
                scale: [p.NumberSpec, 1.0],
                size: [Number, 1.0],
                aspect_scale: [Number, 1.0],
                orientation: [enums_1.HexTileOrientation, "pointytop"],
            });
        });
        _a.override({ line_color: null });
    })();
},
/* models/glyphs/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var image_base_1 = require(395) /* ./image_base */;
    var color_mapper_1 = require(288) /* ../mappers/color_mapper */;
    var linear_color_mapper_1 = require(316) /* ../mappers/linear_color_mapper */;
    var ImageView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ImageView, _super);
        function ImageView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ImageView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.color_mapper.change, function () { return _this._update_image(); });
        };
        ImageView.prototype._update_image = function () {
            // Only reset image_data if already initialized
            if (this.image_data != null) {
                this._set_data(null);
                this.renderer.request_render();
            }
        };
        ImageView.prototype._flat_img_to_buf8 = function (img) {
            var cmap = this.model.color_mapper.rgba_mapper;
            return cmap.v_compute(img);
        };
        return ImageView;
    }(image_base_1.ImageBaseView));
    exports.ImageView = ImageView;
    ImageView.__name__ = "ImageView";
    // NOTE: this needs to be redefined here, because palettes are located in bokeh-api.js bundle
    var Greys9 = function () { return ["#000000", "#252525", "#525252", "#737373", "#969696", "#bdbdbd", "#d9d9d9", "#f0f0f0", "#ffffff"]; };
    var Image = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Image, _super);
        function Image(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Image;
    }(image_base_1.ImageBase));
    exports.Image = Image;
    _a = Image;
    Image.__name__ = "Image";
    (function () {
        _a.prototype.default_view = ImageView;
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                color_mapper: [Ref(color_mapper_1.ColorMapper), function () { return new linear_color_mapper_1.LinearColorMapper({ palette: Greys9() }); }],
            });
        });
    })();
},
/* models/glyphs/image_base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var types_1 = require(139) /* ../../core/types */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var selection_1 = require(187) /* ../selections/selection */;
    var array_1 = require(126) /* ../../core/util/array */;
    var ndarray_1 = require(144) /* ../../core/util/ndarray */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var ImageBaseView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ImageBaseView, _super);
        function ImageBaseView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ImageBaseView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.global_alpha.change, function () { return _this.renderer.request_render(); });
        };
        ImageBaseView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, image_data = _c.image_data, sx = _c.sx, sy = _c.sy, sw = _c.sw, sh = _c.sh, global_alpha = _c.global_alpha;
            var old_smoothing = ctx.getImageSmoothingEnabled();
            ctx.setImageSmoothingEnabled(false);
            var scalar_alpha = global_alpha.is_Scalar();
            if (scalar_alpha)
                ctx.globalAlpha = global_alpha.value;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var image_data_i = image_data[i];
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var sw_i = sw[i];
                    var sh_i = sh[i];
                    var alpha_i = this.global_alpha.get(i);
                    if (image_data_i == null || !isFinite(sx_i + sy_i + sw_i + sh_i + alpha_i))
                        continue;
                    if (!scalar_alpha)
                        ctx.globalAlpha = alpha_i;
                    var y_offset = sy_i;
                    ctx.translate(0, y_offset);
                    ctx.scale(1, -1);
                    ctx.translate(0, -y_offset);
                    ctx.drawImage(image_data_i, sx_i | 0, sy_i | 0, sw_i, sh_i);
                    ctx.translate(0, y_offset);
                    ctx.scale(1, -1);
                    ctx.translate(0, -y_offset);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            ctx.setImageSmoothingEnabled(old_smoothing);
        };
        ImageBaseView.prototype._set_data = function (indices) {
            this._set_width_heigh_data();
            for (var i = 0, end = this.image.length; i < end; i++) {
                if (indices != null && indices.indexOf(i) < 0)
                    continue;
                var img = this.image.get(i);
                var flat_img = void 0;
                if ((0, ndarray_1.is_NDArray)(img)) {
                    (0, assert_1.assert)(img.dimension == 2, "expected a 2D array");
                    flat_img = img;
                    this._height[i] = img.shape[0];
                    this._width[i] = img.shape[1];
                }
                else {
                    flat_img = (0, array_1.concat)(img);
                    this._height[i] = img.length;
                    this._width[i] = img[0].length;
                }
                var buf8 = this._flat_img_to_buf8(flat_img);
                this._set_image_data_from_buffer(i, buf8);
            }
        };
        ImageBaseView.prototype._index_data = function (index) {
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                var _b = (0, tslib_1.__read)(this._lrtb(i), 4), l = _b[0], r = _b[1], t = _b[2], b = _b[3];
                index.add_rect(l, b, r, t);
            }
        };
        ImageBaseView.prototype._lrtb = function (i) {
            var dw_i = this.dw.get(i);
            var dh_i = this.dh.get(i);
            var xr = this.renderer.xscale.source_range;
            var x1 = this._x[i];
            var x2 = xr.is_reversed ? x1 - dw_i : x1 + dw_i;
            var yr = this.renderer.yscale.source_range;
            var y1 = this._y[i];
            var y2 = yr.is_reversed ? y1 - dh_i : y1 + dh_i;
            var _b = (0, tslib_1.__read)(x1 < x2 ? [x1, x2] : [x2, x1], 2), l = _b[0], r = _b[1];
            var _c = (0, tslib_1.__read)(y1 < y2 ? [y1, y2] : [y2, y1], 2), b = _c[0], t = _c[1];
            return [l, r, t, b];
        };
        ImageBaseView.prototype._set_width_heigh_data = function () {
            if (this.image_data == null || this.image_data.length != this.image.length)
                this.image_data = new Array(this.image.length);
            if (this._width == null || this._width.length != this.image.length)
                this._width = new Uint32Array(this.image.length);
            if (this._height == null || this._height.length != this.image.length)
                this._height = new Uint32Array(this.image.length);
        };
        ImageBaseView.prototype._get_or_create_canvas = function (i) {
            var _image_data = this.image_data[i];
            if (_image_data != null && _image_data.width == this._width[i] &&
                _image_data.height == this._height[i])
                return _image_data;
            else {
                var canvas = document.createElement("canvas");
                canvas.width = this._width[i];
                canvas.height = this._height[i];
                return canvas;
            }
        };
        ImageBaseView.prototype._set_image_data_from_buffer = function (i, buf8) {
            var canvas = this._get_or_create_canvas(i);
            var ctx = canvas.getContext("2d");
            var image_data = ctx.getImageData(0, 0, this._width[i], this._height[i]);
            image_data.data.set(buf8);
            ctx.putImageData(image_data, 0, 0);
            this.image_data[i] = canvas;
        };
        ImageBaseView.prototype._map_data = function () {
            if (this.model.properties.dw.units == "data")
                this.sw = this.sdist(this.renderer.xscale, this._x, this.dw, "edge", this.model.dilate);
            else
                this.sw = (0, types_1.to_screen)(this.dw);
            if (this.model.properties.dh.units == "data")
                this.sh = this.sdist(this.renderer.yscale, this._y, this.dh, "edge", this.model.dilate);
            else
                this.sh = (0, types_1.to_screen)(this.dh);
        };
        ImageBaseView.prototype._image_index = function (index, x, y) {
            var _b = (0, tslib_1.__read)(this._lrtb(index), 4), l = _b[0], r = _b[1], t = _b[2], b = _b[3];
            var width = this._width[index];
            var height = this._height[index];
            var dx = (r - l) / width;
            var dy = (t - b) / height;
            var dim1 = Math.floor((x - l) / dx);
            var dim2 = Math.floor((y - b) / dy);
            if (this.renderer.xscale.source_range.is_reversed)
                dim1 = width - dim1 - 1;
            if (this.renderer.yscale.source_range.is_reversed)
                dim2 = height - dim2 - 1;
            return { index: index, dim1: dim1, dim2: dim2, flat_index: dim2 * width + dim1 };
        };
        ImageBaseView.prototype._hit_point = function (geometry) {
            var e_2, _b;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            var candidates = this.index.indices({ x0: x, x1: x, y0: y, y1: y });
            var result = new selection_1.Selection();
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var index = candidates_1_1.value;
                    if (sx != Infinity && sy != Infinity) {
                        result.image_indices.push(this._image_index(index, x, y));
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_b = candidates_1.return))
                        _b.call(candidates_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return result;
        };
        return ImageBaseView;
    }(xy_glyph_1.XYGlyphView));
    exports.ImageBaseView = ImageBaseView;
    ImageBaseView.__name__ = "ImageBaseView";
    var ImageBase = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ImageBase, _super);
        function ImageBase(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ImageBase;
    }(xy_glyph_1.XYGlyph));
    exports.ImageBase = ImageBase;
    _a = ImageBase;
    ImageBase.__name__ = "ImageBase";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                image: [p.NDArraySpec, { field: "image" }],
                dw: [p.DistanceSpec, { field: "dw" }],
                dh: [p.DistanceSpec, { field: "dh" }],
                global_alpha: [p.NumberSpec, { value: 1.0 }],
                dilate: [Boolean, false],
            });
        });
    })();
},
/* models/glyphs/image_rgba.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var image_base_1 = require(395) /* ./image_base */;
    var types_1 = require(125) /* ../../core/util/types */;
    var ImageRGBAView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ImageRGBAView, _super);
        function ImageRGBAView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ImageRGBAView.prototype._flat_img_to_buf8 = function (img) {
            var array;
            if ((0, types_1.isArray)(img)) {
                array = new Uint32Array(img);
            }
            else {
                array = img;
            }
            return new Uint8ClampedArray(array.buffer);
        };
        return ImageRGBAView;
    }(image_base_1.ImageBaseView));
    exports.ImageRGBAView = ImageRGBAView;
    ImageRGBAView.__name__ = "ImageRGBAView";
    var ImageRGBA = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ImageRGBA, _super);
        function ImageRGBA(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ImageRGBA;
    }(image_base_1.ImageBase));
    exports.ImageRGBA = ImageRGBA;
    _a = ImageRGBA;
    ImageRGBA.__name__ = "ImageRGBA";
    (function () {
        _a.prototype.default_view = ImageRGBAView;
    })();
},
/* models/glyphs/image_url.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var types_1 = require(139) /* ../../core/types */;
    var enums_1 = require(135) /* ../../core/enums */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var image_1 = require(251) /* ../../core/util/image */;
    var ImageURLView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ImageURLView, _super);
        function ImageURLView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._images_rendered = false;
            _this._set_data_iteration = 0;
            return _this;
        }
        ImageURLView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.global_alpha.change, function () { return _this.renderer.request_render(); });
        };
        ImageURLView.prototype._index_data = function (index) {
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                // TODO: add a proper implementation (same as ImageBase?)
                index.add_empty();
            }
        };
        ImageURLView.prototype._set_data = function () {
            var _b, _c;
            var _this = this;
            // TODO: cache by url, to reuse images between iterations
            this._set_data_iteration++;
            var n_urls = this.url.length;
            this.image = new Array(n_urls);
            var _d = this.model, retry_attempts = _d.retry_attempts, retry_timeout = _d.retry_timeout;
            var _set_data_iteration = this._set_data_iteration;
            var _loop_1 = function (i) {
                var url = this_1.url.get(i);
                if (!url)
                    return "continue";
                new image_1.ImageLoader(url, {
                    loaded: function (image) {
                        if (_this._set_data_iteration == _set_data_iteration) {
                            _this.image[i] = image;
                            _this.renderer.request_render();
                        }
                    },
                    attempts: retry_attempts + 1,
                    timeout: retry_timeout,
                });
            };
            var this_1 = this;
            for (var i = 0; i < n_urls; i++) {
                _loop_1(i);
            }
            var w_data = this.model.properties.w.units == "data";
            var h_data = this.model.properties.h.units == "data";
            var n = this._x.length;
            var xs = new types_1.ScreenArray(w_data ? 2 * n : n);
            var ys = new types_1.ScreenArray(h_data ? 2 * n : n);
            var anchor = this.model.anchor;
            function x0x1(x, w) {
                switch (anchor) {
                    case "top_left":
                    case "bottom_left":
                    case "left":
                    case "center_left":
                        return [x, x + w];
                    case "top":
                    case "top_center":
                    case "bottom":
                    case "bottom_center":
                    case "center":
                    case "center_center":
                        return [x - w / 2, x + w / 2];
                    case "top_right":
                    case "bottom_right":
                    case "right":
                    case "center_right":
                        return [x - w, x];
                }
            }
            function y0y1(y, h) {
                switch (anchor) {
                    case "top_left":
                    case "top":
                    case "top_center":
                    case "top_right":
                        return [y, y - h];
                    case "bottom_left":
                    case "bottom":
                    case "bottom_center":
                    case "bottom_right":
                        return [y + h, y];
                    case "left":
                    case "center_left":
                    case "center":
                    case "center_center":
                    case "right":
                    case "center_right":
                        return [y + h / 2, y - h / 2];
                }
            }
            // if the width/height are in screen units, don't try to include them in bounds
            if (w_data) {
                for (var i = 0; i < n; i++) {
                    _b = (0, tslib_1.__read)(x0x1(this._x[i], this.w.get(i)), 2), xs[i] = _b[0], xs[n + i] = _b[1];
                }
            }
            else
                xs.set(this._x, 0);
            if (h_data) {
                for (var i = 0; i < n; i++) {
                    _c = (0, tslib_1.__read)(y0y1(this._y[i], this.h.get(i)), 2), ys[i] = _c[0], ys[n + i] = _c[1];
                }
            }
            else
                ys.set(this._y, 0);
            var _e = (0, tslib_1.__read)((0, arrayable_1.minmax)(xs), 2), x0 = _e[0], x1 = _e[1];
            var _f = (0, tslib_1.__read)((0, arrayable_1.minmax)(ys), 2), y0 = _f[0], y1 = _f[1];
            this._bounds_rect = { x0: x0, x1: x1, y0: y0, y1: y1 };
        };
        ImageURLView.prototype.has_finished = function () {
            return _super.prototype.has_finished.call(this) && this._images_rendered == true;
        };
        ImageURLView.prototype._map_data = function () {
            if (this.model.properties.w.units == "data")
                this.sw = this.sdist(this.renderer.xscale, this._x, this.w, "edge", this.model.dilate);
            else
                this.sw = (0, types_1.to_screen)(this.w);
            if (this.model.properties.h.units == "data")
                this.sh = this.sdist(this.renderer.yscale, this._y, this.h, "edge", this.model.dilate);
            else
                this.sh = (0, types_1.to_screen)(this.h);
        };
        ImageURLView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, image = _c.image, sx = _c.sx, sy = _c.sy, sw = _c.sw, sh = _c.sh, angle = _c.angle, global_alpha = _c.global_alpha;
            // TODO (bev): take actual border width into account when clipping
            var frame = this.renderer.plot_view.frame;
            ctx.beginPath();
            ctx.rect(frame.bbox.left + 1, frame.bbox.top + 1, frame.bbox.width - 2, frame.bbox.height - 2);
            ctx.clip();
            var finished = true;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    if (!isFinite(sx[i] + sy[i] + angle.get(i) + global_alpha.get(i)))
                        continue;
                    var img = image[i];
                    if (img == null) {
                        finished = false;
                        continue;
                    }
                    this._render_image(ctx, i, img, sx, sy, sw, sh, angle, global_alpha);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            if (finished && !this._images_rendered) {
                this._images_rendered = true;
                this.notify_finished();
            }
        };
        ImageURLView.prototype._final_sx_sy = function (anchor, sx, sy, sw, sh) {
            switch (anchor) {
                case "top_left": return [sx, sy];
                case "top":
                case "top_center": return [sx - (sw / 2), sy];
                case "top_right": return [sx - sw, sy];
                case "right":
                case "center_right": return [sx - sw, sy - (sh / 2)];
                case "bottom_right": return [sx - sw, sy - sh];
                case "bottom":
                case "bottom_center": return [sx - (sw / 2), sy - sh];
                case "bottom_left": return [sx, sy - sh];
                case "left":
                case "center_left": return [sx, sy - (sh / 2)];
                case "center":
                case "center_center": return [sx - (sw / 2), sy - (sh / 2)];
            }
        };
        ImageURLView.prototype._render_image = function (ctx, i, image, sx, sy, sw, sh, angle, alpha) {
            if (!isFinite(sw[i]))
                sw[i] = image.width;
            if (!isFinite(sh[i]))
                sh[i] = image.height;
            var sw_i = sw[i];
            var sh_i = sh[i];
            var anchor = this.model.anchor;
            var _b = (0, tslib_1.__read)(this._final_sx_sy(anchor, sx[i], sy[i], sw_i, sh_i), 2), sx_i = _b[0], sy_i = _b[1];
            var angle_i = angle.get(i);
            var alpha_i = alpha.get(i);
            ctx.save();
            ctx.globalAlpha = alpha_i;
            var sw2 = sw_i / 2;
            var sh2 = sh_i / 2;
            if (angle_i) {
                ctx.translate(sx_i, sy_i);
                //rotation about center of image
                ctx.translate(sw2, sh2);
                ctx.rotate(angle_i);
                ctx.translate(-sw2, -sh2);
                ctx.drawImage(image, 0, 0, sw_i, sh_i);
                ctx.translate(sw2, sh2);
                ctx.rotate(-angle_i);
                ctx.translate(-sw2, -sh2);
                ctx.translate(-sx_i, -sy_i);
            }
            else
                ctx.drawImage(image, sx_i, sy_i, sw_i, sh_i);
            ctx.restore();
        };
        ImageURLView.prototype.bounds = function () {
            return this._bounds_rect;
        };
        return ImageURLView;
    }(xy_glyph_1.XYGlyphView));
    exports.ImageURLView = ImageURLView;
    ImageURLView.__name__ = "ImageURLView";
    var ImageURL = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ImageURL, _super);
        function ImageURL(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ImageURL;
    }(xy_glyph_1.XYGlyph));
    exports.ImageURL = ImageURL;
    _a = ImageURL;
    ImageURL.__name__ = "ImageURL";
    (function () {
        _a.prototype.default_view = ImageURLView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Int = _b.Int;
            return ({
                url: [p.StringSpec, { field: "url" }],
                anchor: [enums_1.Anchor, "top_left"],
                global_alpha: [p.NumberSpec, { value: 1.0 }],
                angle: [p.AngleSpec, 0],
                w: [p.NullDistanceSpec, null],
                h: [p.NullDistanceSpec, null],
                dilate: [Boolean, false],
                retry_attempts: [Int, 0],
                retry_timeout: [Int, 0],
            });
        });
    })();
},
/* models/glyphs/multi_line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var object_1 = require(128) /* ../../core/util/object */;
    var glyph_1 = require(294) /* ./glyph */;
    var utils_1 = require(299) /* ./utils */;
    var selection_1 = require(187) /* ../selections/selection */;
    var MultiLineView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MultiLineView, _super);
        function MultiLineView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        MultiLineView.prototype._project_data = function () {
            projections_1.inplace.project_xy(this._xs.array, this._ys.array);
        };
        MultiLineView.prototype._index_data = function (index) {
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                var xsi = this._xs.get(i);
                var ysi = this._ys.get(i);
                var _b = (0, tslib_1.__read)((0, arrayable_1.minmax2)(xsi, ysi), 4), x0 = _b[0], x1 = _b[1], y0 = _b[2], y1 = _b[3];
                index.add_rect(x0, y0, x1, y1);
            }
        };
        MultiLineView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sxs = _c.sxs, sys = _c.sys;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx = sxs.get(i);
                    var sy = sys.get(i);
                    var n = Math.min(sx.length, sy.length);
                    var move = true;
                    ctx.beginPath();
                    for (var j = 0; j < n; j++) {
                        var sx_j = sx[j];
                        var sy_j = sy[j];
                        if (!isFinite(sx_j + sy_j))
                            move = true;
                        else {
                            if (move) {
                                ctx.moveTo(sx_j, sy_j);
                                move = false;
                            }
                            else
                                ctx.lineTo(sx_j, sy_j);
                        }
                    }
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        MultiLineView.prototype._hit_point = function (geometry) {
            var point = { x: geometry.sx, y: geometry.sy };
            var shortest = 9999;
            var hits = new Map();
            for (var i = 0, end = this.sxs.length; i < end; i++) {
                var threshold = Math.max(2, this.line_width.get(i) / 2);
                var sxsi = this.sxs.get(i);
                var sysi = this.sys.get(i);
                var points = null;
                for (var j = 0, endj = sxsi.length - 1; j < endj; j++) {
                    var p0 = { x: sxsi[j], y: sysi[j] };
                    var p1 = { x: sxsi[j + 1], y: sysi[j + 1] };
                    var dist = hittest.dist_to_segment(point, p0, p1);
                    if (dist < threshold && dist < shortest) {
                        shortest = dist;
                        points = [j];
                    }
                }
                if (points != null) {
                    hits.set(i, points);
                }
            }
            return new selection_1.Selection({
                indices: (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(hits.keys()), false),
                multiline_indices: (0, object_1.to_object)(hits), // TODO: remove to_object()
            });
        };
        MultiLineView.prototype._hit_span = function (geometry) {
            var sx = geometry.sx, sy = geometry.sy;
            var val;
            var vs;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                vs = this._ys;
            }
            else {
                val = this.renderer.xscale.invert(sx);
                vs = this._xs;
            }
            var hits = new Map();
            for (var i = 0, end = vs.length; i < end; i++) {
                var vsi = vs.get(i);
                var points = [];
                for (var j = 0, endj = vsi.length - 1; j < endj; j++) {
                    if (vsi[j] <= val && val <= vsi[j + 1])
                        points.push(j);
                }
                if (points.length > 0) {
                    hits.set(i, points);
                }
            }
            return new selection_1.Selection({
                indices: (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(hits.keys()), false),
                multiline_indices: (0, object_1.to_object)(hits), // TODO: remove to_object()
            });
        };
        MultiLineView.prototype.get_interpolation_hit = function (i, point_i, geometry) {
            var xsi = this._xs.get(i);
            var ysi = this._ys.get(i);
            var x2 = xsi[point_i];
            var y2 = ysi[point_i];
            var x3 = xsi[point_i + 1];
            var y3 = ysi[point_i + 1];
            return (0, utils_1.line_interpolation)(this.renderer, geometry, x2, y2, x3, y3);
        };
        MultiLineView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        };
        MultiLineView.prototype.scenterxy = function () {
            throw new Error(this + ".scenterxy() is not implemented");
        };
        return MultiLineView;
    }(glyph_1.GlyphView));
    exports.MultiLineView = MultiLineView;
    MultiLineView.__name__ = "MultiLineView";
    var MultiLine = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MultiLine, _super);
        function MultiLine(attrs) {
            return _super.call(this, attrs) || this;
        }
        return MultiLine;
    }(glyph_1.Glyph));
    exports.MultiLine = MultiLine;
    _a = MultiLine;
    MultiLine.__name__ = "MultiLine";
    (function () {
        _a.prototype.default_view = MultiLineView;
        _a.define(function (_b) {
            return ({
                xs: [p.XCoordinateSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSpec, { field: "ys" }],
            });
        });
        _a.mixins(property_mixins_1.LineVector);
    })();
},
/* models/glyphs/multi_polygons.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var spatial_1 = require(296) /* ../../core/util/spatial */;
    var glyph_1 = require(294) /* ./glyph */;
    var utils_1 = require(299) /* ./utils */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var arrayable_2 = require(116) /* ../../core/util/arrayable */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var selection_1 = require(187) /* ../selections/selection */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var MultiPolygonsView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MultiPolygonsView, _super);
        function MultiPolygonsView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        MultiPolygonsView.prototype._project_data = function () {
            // TODO
        };
        MultiPolygonsView.prototype._index_data = function (index) {
            var min = Math.min, max = Math.max;
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                var xsi = this._xs[i];
                var ysi = this._ys[i];
                if (xsi.length == 0 || ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                var xi0 = +Infinity;
                var xi1 = -Infinity;
                var yi0 = +Infinity;
                var yi1 = -Infinity;
                for (var j = 0, endj = xsi.length; j < endj; j++) {
                    var xsij = xsi[j][0]; // do not use holes
                    var ysij = ysi[j][0]; // do not use holes
                    if (xsij.length != 0 && ysij.length != 0) {
                        var _b = (0, tslib_1.__read)((0, arrayable_1.minmax)(xsij), 2), xij0 = _b[0], xij1 = _b[1];
                        var _c = (0, tslib_1.__read)((0, arrayable_1.minmax)(ysij), 2), yij0 = _c[0], yij1 = _c[1];
                        xi0 = min(xi0, xij0);
                        xi1 = max(xi1, xij1);
                        yi0 = min(yi0, yij0);
                        yi1 = max(yi1, yij1);
                    }
                }
                index.add_rect(xi0, yi0, xi1, yi1);
            }
            this._hole_index = this._index_hole_data();
        };
        MultiPolygonsView.prototype._index_hole_data = function () {
            var min = Math.min, max = Math.max;
            var data_size = this.data_size;
            var index = new spatial_1.SpatialIndex(data_size);
            for (var i = 0; i < data_size; i++) {
                var xsi = this._xs[i];
                var ysi = this._ys[i];
                if (xsi.length == 0 || ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                var xi0 = +Infinity;
                var xi1 = -Infinity;
                var yi0 = +Infinity;
                var yi1 = -Infinity;
                for (var j = 0, endj = xsi.length; j < endj; j++) {
                    var xsij = xsi[j];
                    var ysij = ysi[j];
                    if (xsij.length > 1 && ysij.length > 1) {
                        for (var k = 1, endk = xsij.length; k < endk; k++) {
                            var _b = (0, tslib_1.__read)((0, arrayable_1.minmax)(xsij[k]), 2), xij0 = _b[0], xij1 = _b[1];
                            var _c = (0, tslib_1.__read)((0, arrayable_1.minmax)(ysij[k]), 2), yij0 = _c[0], yij1 = _c[1];
                            xi0 = min(xi0, xij0);
                            xi1 = max(xi1, xij1);
                            yi0 = min(yi0, yij0);
                            yi1 = max(yi1, yij1);
                        }
                    }
                }
                index.add_rect(xi0, yi0, xi1, yi1);
            }
            index.finish();
            return index;
        };
        MultiPolygonsView.prototype._mask_data = function () {
            var _b = this.renderer.plot_view.frame, x_range = _b.x_range, y_range = _b.y_range;
            return this.index.indices({
                x0: x_range.min, x1: x_range.max,
                y0: y_range.min, y1: y_range.max,
            });
        };
        MultiPolygonsView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            if (this.visuals.fill.doit || this.visuals.line.doit) {
                var _c = data !== null && data !== void 0 ? data : this, sxs = _c.sxs, sys = _c.sys;
                try {
                    for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                        var i = indices_1_1.value;
                        ctx.beginPath();
                        var sx_i = sxs[i];
                        var sy_i = sys[i];
                        var nj = Math.min(sx_i.length, sy_i.length);
                        for (var j = 0; j < nj; j++) {
                            var sx_ij = sx_i[j];
                            var sy_ij = sy_i[j];
                            var nk = Math.min(sx_ij.length, sy_ij.length);
                            for (var k = 0; k < nk; k++) {
                                var sx_ijk = sx_ij[k];
                                var sy_ijk = sy_ij[k];
                                var nl = Math.min(sx_ijk.length, sy_ijk.length);
                                for (var l = 0; l < nl; l++) {
                                    var sx_ijkl = sx_ijk[l];
                                    var sy_ijkl = sy_ijk[l];
                                    if (l == 0)
                                        ctx.moveTo(sx_ijkl, sy_ijkl);
                                    else
                                        ctx.lineTo(sx_ijkl, sy_ijkl);
                                }
                                ctx.closePath();
                            }
                        }
                        this.visuals.fill.apply(ctx, i, "evenodd");
                        this.visuals.hatch.apply(ctx, i, "evenodd");
                        this.visuals.line.apply(ctx, i);
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                            _b.call(indices_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
        };
        MultiPolygonsView.prototype._hit_rect = function (geometry) {
            var e_2, _b;
            var sx0 = geometry.sx0, sx1 = geometry.sx1, sy0 = geometry.sy0, sy1 = geometry.sy1;
            var xs = [sx0, sx1, sx1, sx0];
            var ys = [sy0, sy0, sy1, sy1];
            var _c = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _c[0], x1 = _c[1];
            var _d = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _d[0], y1 = _d[1];
            var candidates = this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 });
            var indices = [];
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var index = candidates_1_1.value;
                    var sxss = this.sxs[index];
                    var syss = this.sys[index];
                    var hit = true;
                    for (var j = 0, endj = sxss.length; j < endj; j++) {
                        for (var k = 0, endk = sxss[j][0].length; k < endk; k++) {
                            var sx = sxss[j][0][k];
                            var sy = syss[j][0][k];
                            if (!hittest.point_in_poly(sx, sy, xs, ys)) {
                                hit = false;
                                break;
                            }
                        }
                        if (!hit)
                            break;
                    }
                    if (hit) {
                        indices.push(index);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_b = candidates_1.return))
                        _b.call(candidates_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        MultiPolygonsView.prototype._hit_point = function (geometry) {
            var e_3, _b;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            var candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            var hole_candidates = this._hole_index.indices({ x0: x, y0: y, x1: x, y1: y });
            var indices = [];
            try {
                for (var candidates_2 = (0, tslib_1.__values)(candidates), candidates_2_1 = candidates_2.next(); !candidates_2_1.done; candidates_2_1 = candidates_2.next()) {
                    var index = candidates_2_1.value;
                    var sxs = this.sxs[index];
                    var sys = this.sys[index];
                    for (var j = 0, endj = sxs.length; j < endj; j++) {
                        var nk = sxs[j].length;
                        if (hittest.point_in_poly(sx, sy, sxs[j][0], sys[j][0])) {
                            if (nk == 1) {
                                indices.push(index);
                            }
                            else if (!hole_candidates.get(index)) {
                                indices.push(index);
                            }
                            else if (nk > 1) {
                                var in_a_hole = false;
                                for (var k = 1; k < nk; k++) {
                                    var sxs_k = sxs[j][k];
                                    var sys_k = sys[j][k];
                                    if (hittest.point_in_poly(sx, sy, sxs_k, sys_k)) {
                                        in_a_hole = true;
                                        break;
                                    }
                                    else {
                                        continue;
                                    }
                                }
                                if (!in_a_hole) {
                                    indices.push(index);
                                }
                            }
                        }
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (candidates_2_1 && !candidates_2_1.done && (_b = candidates_2.return))
                        _b.call(candidates_2);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        MultiPolygonsView.prototype._get_snap_coord = function (array) {
            return (0, arrayable_2.sum)(array) / array.length;
        };
        MultiPolygonsView.prototype.scenterxy = function (i, sx, sy) {
            if (this.sxs[i].length == 1) {
                // We don't have discontinuous objects so we're ok
                var scx = this._get_snap_coord(this.sxs[i][0][0]);
                var scy = this._get_snap_coord(this.sys[i][0][0]);
                return [scx, scy];
            }
            else {
                // We have discontinuous objects, so we need to find which
                // one we're in, we can use point_in_poly again
                var sxs = this.sxs[i];
                var sys = this.sys[i];
                for (var j = 0, end = sxs.length; j < end; j++) {
                    if (hittest.point_in_poly(sx, sy, sxs[j][0], sys[j][0])) {
                        var scx = this._get_snap_coord(sxs[j][0]);
                        var scy = this._get_snap_coord(sys[j][0]);
                        return [scx, scy];
                    }
                }
            }
            (0, assert_1.unreachable)();
        };
        MultiPolygonsView.prototype.map_data = function () {
            var n_i = this._xs.length;
            this.sxs = new Array(n_i);
            this.sys = new Array(n_i);
            for (var i = 0; i < n_i; i++) {
                var n_j = this._xs[i].length;
                this.sxs[i] = new Array(n_j);
                this.sys[i] = new Array(n_j);
                for (var j = 0; j < n_j; j++) {
                    var n_k = this._xs[i][j].length;
                    this.sxs[i][j] = new Array(n_k);
                    this.sys[i][j] = new Array(n_k);
                    for (var k = 0; k < n_k; k++) {
                        var _b = (0, tslib_1.__read)(this.renderer.coordinates.map_to_screen(this._xs[i][j][k], this._ys[i][j][k]), 2), sx = _b[0], sy = _b[1];
                        this.sxs[i][j][k] = sx;
                        this.sys[i][j][k] = sy;
                    }
                }
            }
        };
        MultiPolygonsView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        };
        return MultiPolygonsView;
    }(glyph_1.GlyphView));
    exports.MultiPolygonsView = MultiPolygonsView;
    MultiPolygonsView.__name__ = "MultiPolygonsView";
    var MultiPolygons = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MultiPolygons, _super);
        function MultiPolygons(attrs) {
            return _super.call(this, attrs) || this;
        }
        return MultiPolygons;
    }(glyph_1.Glyph));
    exports.MultiPolygons = MultiPolygons;
    _a = MultiPolygons;
    MultiPolygons.__name__ = "MultiPolygons";
    (function () {
        _a.prototype.default_view = MultiPolygonsView;
        _a.define(function (_b) {
            return ({
                xs: [p.XCoordinateSeqSeqSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSeqSeqSpec, { field: "ys" }],
            });
        });
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
    })();
},
/* models/glyphs/oval.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var ellipse_oval_1 = require(389) /* ./ellipse_oval */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var OvalView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(OvalView, _super);
        function OvalView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        OvalView.prototype._map_data = function () {
            _super.prototype._map_data.call(this);
            (0, arrayable_1.mul)(this.sw, 0.75); // oval drawn from bezier curves = ellipse with width reduced by 3/4
        };
        return OvalView;
    }(ellipse_oval_1.EllipseOvalView));
    exports.OvalView = OvalView;
    OvalView.__name__ = "OvalView";
    var Oval = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Oval, _super);
        function Oval(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Oval;
    }(ellipse_oval_1.EllipseOval));
    exports.Oval = Oval;
    _a = Oval;
    Oval.__name__ = "Oval";
    (function () {
        _a.prototype.default_view = OvalView;
    })();
},
/* models/glyphs/patches.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var glyph_1 = require(294) /* ./glyph */;
    var utils_1 = require(299) /* ./utils */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var selection_1 = require(187) /* ../selections/selection */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var PatchesView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PatchesView, _super);
        function PatchesView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PatchesView.prototype._project_data = function () {
            projections_1.inplace.project_xy(this._xs.array, this._ys.array);
        };
        PatchesView.prototype._index_data = function (index) {
            var data_size = this.data_size;
            for (var i = 0; i < data_size; i++) {
                var xsi = this._xs.get(i);
                var ysi = this._ys.get(i);
                var _b = (0, tslib_1.__read)((0, arrayable_1.minmax2)(xsi, ysi), 4), x0 = _b[0], x1 = _b[1], y0 = _b[2], y1 = _b[3];
                index.add_rect(x0, y0, x1, y1);
            }
        };
        PatchesView.prototype._mask_data = function () {
            var _b = this.renderer.plot_view.frame, x_range = _b.x_range, y_range = _b.y_range;
            return this.index.indices({
                x0: x_range.min, x1: x_range.max,
                y0: y_range.min, y1: y_range.max,
            });
        };
        PatchesView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sxs = _c.sxs, sys = _c.sys;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sxs.get(i);
                    var sy_i = sys.get(i);
                    var move = true;
                    ctx.beginPath();
                    var n = Math.min(sx_i.length, sy_i.length);
                    for (var j = 0; j < n; j++) {
                        var sx_j = sx_i[j];
                        var sy_j = sy_i[j];
                        if (!isFinite(sx_j + sy_j)) {
                            ctx.closePath();
                            move = true;
                        }
                        else {
                            if (move) {
                                ctx.moveTo(sx_j, sy_j);
                                move = false;
                            }
                            else
                                ctx.lineTo(sx_j, sy_j);
                        }
                    }
                    ctx.closePath();
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        PatchesView.prototype._hit_rect = function (geometry) {
            var e_2, _b;
            var sx0 = geometry.sx0, sx1 = geometry.sx1, sy0 = geometry.sy0, sy1 = geometry.sy1;
            var xs = [sx0, sx1, sx1, sx0];
            var ys = [sy0, sy0, sy1, sy1];
            var _c = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _c[0], x1 = _c[1];
            var _d = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _d[0], y1 = _d[1];
            var candidates = this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 });
            var indices = [];
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var index = candidates_1_1.value;
                    var sxss = this.sxs.get(index);
                    var syss = this.sys.get(index);
                    var hit = true;
                    for (var j = 0, endj = sxss.length; j < endj; j++) {
                        var sx = sxss[j];
                        var sy = syss[j];
                        if (!hittest.point_in_poly(sx, sy, xs, ys)) {
                            hit = false;
                            break;
                        }
                    }
                    if (hit) {
                        indices.push(index);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_b = candidates_1.return))
                        _b.call(candidates_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        PatchesView.prototype._hit_point = function (geometry) {
            var e_3, _b;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            var candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            var indices = [];
            try {
                for (var candidates_2 = (0, tslib_1.__values)(candidates), candidates_2_1 = candidates_2.next(); !candidates_2_1.done; candidates_2_1 = candidates_2.next()) {
                    var index = candidates_2_1.value;
                    var sxsi = this.sxs.get(index);
                    var sysi = this.sys.get(index);
                    var n = sxsi.length;
                    for (var k = 0, j = 0;; j++) {
                        if (isNaN(sxsi[j]) || j == n) {
                            var sxsi_kj = sxsi.subarray(k, j);
                            var sysi_kj = sysi.subarray(k, j);
                            if (hittest.point_in_poly(sx, sy, sxsi_kj, sysi_kj)) {
                                indices.push(index);
                                break;
                            }
                            k = j + 1;
                        }
                        if (j == n)
                            break;
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (candidates_2_1 && !candidates_2_1.done && (_b = candidates_2.return))
                        _b.call(candidates_2);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        PatchesView.prototype._get_snap_coord = function (array) {
            return (0, arrayable_1.sum)(array) / array.length;
        };
        PatchesView.prototype.scenterxy = function (i, sx, sy) {
            var sxsi = this.sxs.get(i);
            var sysi = this.sys.get(i);
            var n = sxsi.length;
            var has_nan = false;
            for (var k = 0, j = 0;; j++) {
                var this_nan = isNaN(sxsi[j]);
                has_nan = has_nan || this_nan;
                if (j == n && !has_nan) {
                    var scx = this._get_snap_coord(sxsi);
                    var scy = this._get_snap_coord(sysi);
                    return [scx, scy];
                }
                if (this_nan || j == n) {
                    var sxsi_kj = sxsi.subarray(k, j);
                    var sysi_kj = sysi.subarray(k, j);
                    if (hittest.point_in_poly(sx, sy, sxsi_kj, sysi_kj)) {
                        var scx = this._get_snap_coord(sxsi_kj);
                        var scy = this._get_snap_coord(sysi_kj);
                        return [scx, scy];
                    }
                    k = j + 1;
                }
                if (j == n)
                    break;
            }
            (0, assert_1.unreachable)();
        };
        PatchesView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        };
        return PatchesView;
    }(glyph_1.GlyphView));
    exports.PatchesView = PatchesView;
    PatchesView.__name__ = "PatchesView";
    var Patches = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Patches, _super);
        function Patches(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Patches;
    }(glyph_1.Glyph));
    exports.Patches = Patches;
    _a = Patches;
    Patches.__name__ = "Patches";
    (function () {
        _a.prototype.default_view = PatchesView;
        _a.define(function (_b) {
            return ({
                xs: [p.XCoordinateSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSpec, { field: "ys" }],
            });
        });
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
    })();
},
/* models/glyphs/quad.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var box_1 = require(392) /* ./box */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var QuadView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(QuadView, _super);
        function QuadView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        QuadView.prototype.scenterxy = function (i) {
            var scx = this.sleft[i] / 2 + this.sright[i] / 2;
            var scy = this.stop[i] / 2 + this.sbottom[i] / 2;
            return [scx, scy];
        };
        QuadView.prototype._lrtb = function (i) {
            var l = this._left[i];
            var r = this._right[i];
            var t = this._top[i];
            var b = this._bottom[i];
            return [l, r, t, b];
        };
        return QuadView;
    }(box_1.BoxView));
    exports.QuadView = QuadView;
    QuadView.__name__ = "QuadView";
    var Quad = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Quad, _super);
        function Quad(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Quad;
    }(box_1.Box));
    exports.Quad = Quad;
    _a = Quad;
    Quad.__name__ = "Quad";
    (function () {
        _a.prototype.default_view = QuadView;
        _a.define(function (_b) {
            return ({
                right: [p.XCoordinateSpec, { field: "right" }],
                bottom: [p.YCoordinateSpec, { field: "bottom" }],
                left: [p.XCoordinateSpec, { field: "left" }],
                top: [p.YCoordinateSpec, { field: "top" }],
            });
        });
    })();
},
/* models/glyphs/quadratic.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var glyph_1 = require(294) /* ./glyph */;
    var utils_1 = require(299) /* ./utils */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    // Formula from: http://pomax.nihongoresources.com/pages/bezier/
    //
    // if segment is quadratic bezier do:
    //   for both directions do:
    //     if control between start and end, compute linear bounding box
    //     otherwise, compute
    //       bound = u(1-t)^2 + 2v(1-t)t + wt^2
    //         (with t = ((u-v) / (u-2v+w)), with {u = start, v = control, w = end})
    //       if control precedes start, min = bound, otherwise max = bound
    function _qbb(u, v, w) {
        if (v == (u + w) / 2)
            return [u, w];
        else {
            var t = (u - v) / ((u - (2 * v)) + w);
            var bd = (u * Math.pow((1 - t), 2)) + (2 * v * (1 - t) * t) + (w * Math.pow(t, 2));
            return [Math.min(u, w, bd), Math.max(u, w, bd)];
        }
    }
    var QuadraticView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(QuadraticView, _super);
        function QuadraticView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        QuadraticView.prototype._project_data = function () {
            projections_1.inplace.project_xy(this._x0, this._y0);
            projections_1.inplace.project_xy(this._x1, this._y1);
        };
        QuadraticView.prototype._index_data = function (index) {
            var _b = this, _x0 = _b._x0, _x1 = _b._x1, _y0 = _b._y0, _y1 = _b._y1, _cx = _b._cx, _cy = _b._cy, data_size = _b.data_size;
            for (var i = 0; i < data_size; i++) {
                var x0_i = _x0[i];
                var x1_i = _x1[i];
                var y0_i = _y0[i];
                var y1_i = _y1[i];
                var cx_i = _cx[i];
                var cy_i = _cy[i];
                if (!isFinite(x0_i + x1_i + y0_i + y1_i + cx_i + cy_i))
                    index.add_empty();
                else {
                    var _c = (0, tslib_1.__read)(_qbb(x0_i, cx_i, x1_i), 2), x0 = _c[0], x1 = _c[1];
                    var _d = (0, tslib_1.__read)(_qbb(y0_i, cy_i, y1_i), 2), y0 = _d[0], y1 = _d[1];
                    index.add_rect(x0, y0, x1, y1);
                }
            }
        };
        QuadraticView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            if (this.visuals.line.doit) {
                var _c = data !== null && data !== void 0 ? data : this, sx0 = _c.sx0, sy0 = _c.sy0, sx1 = _c.sx1, sy1 = _c.sy1, scx = _c.scx, scy = _c.scy;
                try {
                    for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                        var i = indices_1_1.value;
                        var sx0_i = sx0[i];
                        var sy0_i = sy0[i];
                        var sx1_i = sx1[i];
                        var sy1_i = sy1[i];
                        var scx_i = scx[i];
                        var scy_i = scy[i];
                        if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i + scx_i + scy_i))
                            continue;
                        ctx.beginPath();
                        ctx.moveTo(sx0_i, sy0_i);
                        ctx.quadraticCurveTo(scx_i, scy_i, sx1_i, sy1_i);
                        this.visuals.line.set_vectorize(ctx, i);
                        ctx.stroke();
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                            _b.call(indices_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
        };
        QuadraticView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        };
        QuadraticView.prototype.scenterxy = function () {
            throw new Error(this + ".scenterxy() is not implemented");
        };
        return QuadraticView;
    }(glyph_1.GlyphView));
    exports.QuadraticView = QuadraticView;
    QuadraticView.__name__ = "QuadraticView";
    var Quadratic = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Quadratic, _super);
        function Quadratic(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Quadratic;
    }(glyph_1.Glyph));
    exports.Quadratic = Quadratic;
    _a = Quadratic;
    Quadratic.__name__ = "Quadratic";
    (function () {
        _a.prototype.default_view = QuadraticView;
        _a.define(function (_b) {
            return ({
                x0: [p.XCoordinateSpec, { field: "x0" }],
                y0: [p.YCoordinateSpec, { field: "y0" }],
                x1: [p.XCoordinateSpec, { field: "x1" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
                cx: [p.XCoordinateSpec, { field: "cx" }],
                cy: [p.YCoordinateSpec, { field: "cy" }],
            });
        });
        _a.mixins(property_mixins_1.LineVector);
    })();
},
/* models/glyphs/ray.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var utils_1 = require(299) /* ./utils */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var types_1 = require(139) /* ../../core/types */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var RayView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RayView, _super);
        function RayView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RayView.prototype._map_data = function () {
            if (this.model.properties.length.units == "data")
                this.slength = this.sdist(this.renderer.xscale, this._x, this.length);
            else
                this.slength = (0, types_1.to_screen)(this.length);
            var _b = this.renderer.plot_view.frame.bbox, width = _b.width, height = _b.height;
            var inf_len = 2 * (width + height);
            var slength = this.slength;
            for (var i = 0, end = slength.length; i < end; i++) {
                if (slength[i] == 0)
                    slength[i] = inf_len;
            }
        };
        RayView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, slength = _c.slength, angle = _c.angle;
            if (this.visuals.line.doit) {
                try {
                    for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                        var i = indices_1_1.value;
                        var sx_i = sx[i];
                        var sy_i = sy[i];
                        var angle_i = angle.get(i);
                        var slength_i = slength[i];
                        if (!isFinite(sx_i + sy_i + angle_i + slength_i))
                            continue;
                        ctx.translate(sx_i, sy_i);
                        ctx.rotate(angle_i);
                        ctx.beginPath();
                        ctx.moveTo(0, 0);
                        ctx.lineTo(slength_i, 0);
                        this.visuals.line.set_vectorize(ctx, i);
                        ctx.stroke();
                        ctx.rotate(-angle_i);
                        ctx.translate(-sx_i, -sy_i);
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                            _b.call(indices_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
        };
        RayView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        };
        return RayView;
    }(xy_glyph_1.XYGlyphView));
    exports.RayView = RayView;
    RayView.__name__ = "RayView";
    var Ray = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Ray, _super);
        function Ray(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Ray;
    }(xy_glyph_1.XYGlyph));
    exports.Ray = Ray;
    _a = Ray;
    Ray.__name__ = "Ray";
    (function () {
        _a.prototype.default_view = RayView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(function (_b) {
            return ({
                length: [p.DistanceSpec, 0],
                angle: [p.AngleSpec, 0],
            });
        });
    })();
},
/* models/glyphs/rect.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var center_rotatable_1 = require(390) /* ./center_rotatable */;
    var utils_1 = require(299) /* ./utils */;
    var types_1 = require(139) /* ../../core/types */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var selection_1 = require(187) /* ../selections/selection */;
    var RectView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RectView, _super);
        function RectView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RectView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var webgl, RectGL;
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _b.sent();
                            webgl = this.renderer.plot_view.canvas_view.webgl;
                            if (!(webgl === null || webgl === void 0 ? void 0 : webgl.regl_wrapper.has_webgl))
                                return [3 /*break*/, 3];
                            return [4 /*yield*/, Promise.resolve().then(function () { return (0, tslib_1.__importStar)(require(540) /* ./webgl/rect */); })];
                        case 2:
                            RectGL = (_b.sent()).RectGL;
                            this.glglyph = new RectGL(webgl.regl_wrapper, this);
                            _b.label = 3;
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        RectView.prototype._map_data = function () {
            var _b, _c;
            if (this.model.properties.width.units == "data")
                _b = (0, tslib_1.__read)(this._map_dist_corner_for_data_side_length(this._x, this.width, this.renderer.xscale), 2), this.sw = _b[0], this.sx0 = _b[1];
            else {
                this.sw = (0, types_1.to_screen)(this.width);
                var n_1 = this.sx.length;
                this.sx0 = new types_1.ScreenArray(n_1);
                for (var i = 0; i < n_1; i++)
                    this.sx0[i] = this.sx[i] - this.sw[i] / 2;
            }
            if (this.model.properties.height.units == "data")
                _c = (0, tslib_1.__read)(this._map_dist_corner_for_data_side_length(this._y, this.height, this.renderer.yscale), 2), this.sh = _c[0], this.sy1 = _c[1];
            else {
                this.sh = (0, types_1.to_screen)(this.height);
                var n_2 = this.sy.length;
                this.sy1 = new types_1.ScreenArray(n_2);
                for (var i = 0; i < n_2; i++)
                    this.sy1[i] = this.sy[i] - this.sh[i] / 2;
            }
            var n = this.sw.length;
            this.ssemi_diag = new types_1.ScreenArray(n);
            for (var i = 0; i < n; i++)
                this.ssemi_diag[i] = Math.sqrt((this.sw[i] / 2 * this.sw[i]) / 2 + (this.sh[i] / 2 * this.sh[i]) / 2);
        };
        RectView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, sx0 = _c.sx0, sy1 = _c.sy1, sw = _c.sw, sh = _c.sh, angle = _c.angle;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var sx0_i = sx0[i];
                    var sy1_i = sy1[i];
                    var sw_i = sw[i];
                    var sh_i = sh[i];
                    var angle_i = angle.get(i);
                    if (!isFinite(sx_i + sy_i + sx0_i + sy1_i + sw_i + sh_i + angle_i))
                        continue;
                    if (sw_i == 0 || sh_i == 0)
                        continue;
                    ctx.beginPath();
                    if (angle_i) {
                        ctx.translate(sx_i, sy_i);
                        ctx.rotate(angle_i);
                        ctx.rect(-sw_i / 2, -sh_i / 2, sw_i, sh_i);
                        ctx.rotate(-angle_i);
                        ctx.translate(-sx_i, -sy_i);
                    }
                    else
                        ctx.rect(sx0_i, sy1_i, sw_i, sh_i);
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        RectView.prototype._hit_rect = function (geometry) {
            return this._hit_rect_against_index(geometry);
        };
        RectView.prototype._hit_point = function (geometry) {
            var e_2, _b;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            var n = this.sx0.length;
            var scenter_x = new types_1.ScreenArray(n);
            for (var i = 0; i < n; i++) {
                scenter_x[i] = this.sx0[i] + this.sw[i] / 2;
            }
            var scenter_y = new types_1.ScreenArray(n);
            for (var i = 0; i < n; i++) {
                scenter_y[i] = this.sy1[i] + this.sh[i] / 2;
            }
            var max_x2_ddist = (0, arrayable_1.max)(this._ddist(0, scenter_x, this.ssemi_diag));
            var max_y2_ddist = (0, arrayable_1.max)(this._ddist(1, scenter_y, this.ssemi_diag));
            var x0 = x - max_x2_ddist;
            var x1 = x + max_x2_ddist;
            var y0 = y - max_y2_ddist;
            var y1 = y + max_y2_ddist;
            var width_in;
            var height_in;
            var indices = [];
            try {
                for (var _c = (0, tslib_1.__values)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var i = _d.value;
                    var angle_i = this.angle.get(i);
                    if (angle_i) {
                        var s = Math.sin(-angle_i);
                        var c = Math.cos(-angle_i);
                        var px = c * (sx - this.sx[i]) - s * (sy - this.sy[i]) + this.sx[i];
                        var py = s * (sx - this.sx[i]) + c * (sy - this.sy[i]) + this.sy[i];
                        sx = px;
                        sy = py;
                        width_in = Math.abs(this.sx[i] - sx) <= this.sw[i] / 2;
                        height_in = Math.abs(this.sy[i] - sy) <= this.sh[i] / 2;
                    }
                    else {
                        var dx = sx - this.sx0[i];
                        var dy = sy - this.sy1[i];
                        width_in = 0 <= dx && dx <= this.sw[i];
                        height_in = 0 <= dy && dy <= this.sh[i];
                    }
                    if (width_in && height_in) {
                        indices.push(i);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        RectView.prototype._map_dist_corner_for_data_side_length = function (coord, side_length, scale) {
            var n = coord.length;
            var pt0 = new Float64Array(n);
            var pt1 = new Float64Array(n);
            for (var i = 0; i < n; i++) {
                var coord_i = coord[i];
                var half_side_length_i = side_length.get(i) / 2;
                pt0[i] = coord_i - half_side_length_i;
                pt1[i] = coord_i + half_side_length_i;
            }
            var spt0 = scale.v_compute(pt0);
            var spt1 = scale.v_compute(pt1);
            var sside_length = this.sdist(scale, pt0, side_length, "edge", this.model.dilate);
            var spt_corner = spt0;
            for (var i = 0; i < n; i++) {
                var spt0i = spt0[i];
                var spt1i = spt1[i];
                if (!isNaN(spt0i + spt1i) && spt0i != spt1i) {
                    spt_corner = spt0i < spt1i ? spt0 : spt1;
                    break;
                }
            }
            return [sside_length, spt_corner];
        };
        RectView.prototype._ddist = function (dim, spts, spans) {
            var ArrayType = (0, types_1.infer_type)(spts, spans);
            var scale = dim == 0 ? this.renderer.xscale : this.renderer.yscale;
            var spt0 = spts;
            var m = spt0.length;
            var spt1 = new ArrayType(m);
            for (var i = 0; i < m; i++)
                spt1[i] = spt0[i] + spans[i];
            var pt0 = scale.v_invert(spt0);
            var pt1 = scale.v_invert(spt1);
            var n = pt0.length;
            var ddist = new ArrayType(n);
            for (var i = 0; i < n; i++)
                ddist[i] = Math.abs(pt1[i] - pt0[i]);
            return ddist;
        };
        RectView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        };
        return RectView;
    }(center_rotatable_1.CenterRotatableView));
    exports.RectView = RectView;
    RectView.__name__ = "RectView";
    var Rect = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Rect, _super);
        function Rect(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Rect;
    }(center_rotatable_1.CenterRotatable));
    exports.Rect = Rect;
    _a = Rect;
    Rect.__name__ = "Rect";
    (function () {
        _a.prototype.default_view = RectView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                dilate: [Boolean, false],
            });
        });
    })();
},
/* models/glyphs/scatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var marker_1 = require(407) /* ./marker */;
    var defs_1 = require(408) /* ./defs */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var ScatterView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ScatterView, _super);
        function ScatterView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ScatterView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var webgl, MarkerGL;
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _b.sent();
                            webgl = this.renderer.plot_view.canvas_view.webgl;
                            if (!(webgl === null || webgl === void 0 ? void 0 : webgl.regl_wrapper.has_webgl))
                                return [3 /*break*/, 3];
                            return [4 /*yield*/, Promise.resolve().then(function () { return (0, tslib_1.__importStar)(require(541) /* ./webgl/markers */); })];
                        case 2:
                            MarkerGL = (_b.sent()).MarkerGL;
                            this.glcls = MarkerGL;
                            _b.label = 3;
                        case 3: return [2 /*return*/];
                    }
                });
            });
        };
        ScatterView.prototype._init_webgl = function () {
            var webgl = this.renderer.plot_view.canvas_view.webgl;
            if (webgl != null) {
                var regl_wrapper = webgl.regl_wrapper;
                if (regl_wrapper.has_webgl) {
                    var marker_types = new Set(this.base != null ? this.base.marker : this.marker);
                    if (marker_types.size == 1) {
                        var _b = (0, tslib_1.__read)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(marker_types), false), 1), marker_type = _b[0];
                        var MarkerGL = this.glcls;
                        if (MarkerGL === null || MarkerGL === void 0 ? void 0 : MarkerGL.is_supported(marker_type)) {
                            var glglyph = this.glglyph;
                            if (glglyph == null || glglyph.marker_type != marker_type) {
                                this.glglyph = new MarkerGL(regl_wrapper, this, marker_type);
                                return;
                            }
                        }
                    }
                }
            }
            delete this.glglyph;
        };
        ScatterView.prototype._set_visuals = function () {
            this._init_webgl();
        };
        ScatterView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, size = _c.size, angle = _c.angle, marker = _c.marker;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var size_i = size.get(i);
                    var angle_i = angle.get(i);
                    var marker_i = marker.get(i);
                    if (!isFinite(sx_i + sy_i + size_i + angle_i) || marker_i == null)
                        continue;
                    var r = size_i / 2;
                    ctx.beginPath();
                    ctx.translate(sx_i, sy_i);
                    if (angle_i)
                        ctx.rotate(angle_i);
                    defs_1.marker_funcs[marker_i](ctx, i, r, this.visuals);
                    if (angle_i)
                        ctx.rotate(-angle_i);
                    ctx.translate(-sx_i, -sy_i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        ScatterView.prototype.draw_legend_for_index = function (ctx, _b, index) {
            var x0 = _b.x0, x1 = _b.x1, y0 = _b.y0, y1 = _b.y1;
            var n = index + 1;
            var marker = this.marker.get(index);
            var args = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, this._get_legend_args({ x0: x0, x1: x1, y0: y0, y1: y1 }, index)), { marker: new p.UniformScalar(marker, n) });
            this._render(ctx, [index], args);
        };
        return ScatterView;
    }(marker_1.MarkerView));
    exports.ScatterView = ScatterView;
    ScatterView.__name__ = "ScatterView";
    var Scatter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Scatter, _super);
        function Scatter(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Scatter;
    }(marker_1.Marker));
    exports.Scatter = Scatter;
    _a = Scatter;
    Scatter.__name__ = "Scatter";
    (function () {
        _a.prototype.default_view = ScatterView;
        _a.define(function () {
            return ({
                marker: [p.MarkerSpec, { value: "circle" }],
            });
        });
    })();
},
/* models/glyphs/marker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var array_1 = require(126) /* ../../core/util/array */;
    var selection_1 = require(187) /* ../selections/selection */;
    var MarkerView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MarkerView, _super);
        function MarkerView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        MarkerView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, size = _c.size, angle = _c.angle;
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var size_i = size.get(i);
                    var angle_i = angle.get(i);
                    if (!isFinite(sx_i + sy_i + size_i + angle_i))
                        continue;
                    var r = size_i / 2;
                    ctx.beginPath();
                    ctx.translate(sx_i, sy_i);
                    if (angle_i)
                        ctx.rotate(angle_i);
                    this._render_one(ctx, i, r, this.visuals);
                    if (angle_i)
                        ctx.rotate(-angle_i);
                    ctx.translate(-sx_i, -sy_i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        MarkerView.prototype._mask_data = function () {
            var _this = this;
            // dilate the inner screen region by max_size and map back to data space for use in spatial query
            var _b = this.renderer.plot_view.frame, x_target = _b.x_target, y_target = _b.y_target;
            var hr = x_target.widen(this.max_size).map(function (x) { return _this.renderer.xscale.invert(x); });
            var vr = y_target.widen(this.max_size).map(function (y) { return _this.renderer.yscale.invert(y); });
            return this.index.indices({
                x0: hr.start, x1: hr.end,
                y0: vr.start, y1: vr.end,
            });
        };
        MarkerView.prototype._hit_point = function (geometry) {
            var e_2, _b;
            var sx = geometry.sx, sy = geometry.sy;
            var max_size = this.max_size;
            var hit_dilation = this.model.hit_dilation;
            var sx0 = sx - max_size * hit_dilation;
            var sx1 = sx + max_size * hit_dilation;
            var _c = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _c[0], x1 = _c[1];
            var sy0 = sy - max_size * hit_dilation;
            var sy1 = sy + max_size * hit_dilation;
            var _d = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _d[0], y1 = _d[1];
            var candidates = this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 });
            var indices = [];
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var i = candidates_1_1.value;
                    var s2 = this.size.get(i) / 2 * hit_dilation;
                    if (Math.abs(this.sx[i] - sx) <= s2 && Math.abs(this.sy[i] - sy) <= s2) {
                        indices.push(i);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_b = candidates_1.return))
                        _b.call(candidates_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        MarkerView.prototype._hit_span = function (geometry) {
            var _b, _c;
            var sx = geometry.sx, sy = geometry.sy;
            var bounds = this.bounds();
            var ms = this.max_size / 2;
            var x0, x1, y0, y1;
            if (geometry.direction == "h") {
                y0 = bounds.y0;
                y1 = bounds.y1;
                var sx0 = sx - ms;
                var sx1 = sx + ms;
                _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
            }
            else {
                x0 = bounds.x0;
                x1 = bounds.x1;
                var sy0 = sy - ms;
                var sy1 = sy + ms;
                _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _c[0], y1 = _c[1];
            }
            var indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), false);
            return new selection_1.Selection({ indices: indices });
        };
        MarkerView.prototype._hit_rect = function (geometry) {
            var sx0 = geometry.sx0, sx1 = geometry.sx1, sy0 = geometry.sy0, sy1 = geometry.sy1;
            var _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
            var _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _c[0], y1 = _c[1];
            var indices = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), false);
            return new selection_1.Selection({ indices: indices });
        };
        MarkerView.prototype._hit_poly = function (geometry) {
            var sx = geometry.sx, sy = geometry.sy;
            // TODO (bev) use spatial index to pare candidate list
            var candidates = (0, array_1.range)(0, this.sx.length);
            var indices = [];
            for (var i = 0, end = candidates.length; i < end; i++) {
                var index = candidates[i];
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        MarkerView.prototype._get_legend_args = function (_b, index) {
            var x0 = _b.x0, x1 = _b.x1, y0 = _b.y0, y1 = _b.y1;
            // using objects like this seems a little wonky, since the keys are coerced to strings, but it works
            var n = index + 1;
            var sx = new Array(n);
            var sy = new Array(n);
            sx[index] = (x0 + x1) / 2;
            sy[index] = (y0 + y1) / 2;
            var vsize = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.4;
            var size = new p.UniformScalar(vsize, n);
            var angle = new p.UniformScalar(0, n); // don't attempt to match glyph angle
            return { sx: sx, sy: sy, size: size, angle: angle };
        };
        MarkerView.prototype.draw_legend_for_index = function (ctx, _b, index) {
            var x0 = _b.x0, x1 = _b.x1, y0 = _b.y0, y1 = _b.y1;
            var args = this._get_legend_args({ x0: x0, x1: x1, y0: y0, y1: y1 }, index);
            this._render(ctx, [index], args); // XXX
        };
        return MarkerView;
    }(xy_glyph_1.XYGlyphView));
    exports.MarkerView = MarkerView;
    MarkerView.__name__ = "MarkerView";
    var Marker = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Marker, _super);
        function Marker(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Marker;
    }(xy_glyph_1.XYGlyph));
    exports.Marker = Marker;
    _a = Marker;
    Marker.__name__ = "Marker";
    (function () {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(function (_b) {
            var Number = _b.Number;
            return ({
                size: [p.ScreenSizeSpec, { value: 4 }],
                angle: [p.AngleSpec, 0],
                hit_dilation: [Number, 1.0],
            });
        });
    })();
},
/* models/glyphs/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var SQ3 = Math.sqrt(3);
    var SQ5 = Math.sqrt(5);
    var c36 = (SQ5 + 1) / 4;
    var s36 = Math.sqrt((5 - SQ5) / 8);
    var c72 = (SQ5 - 1) / 4;
    var s72 = Math.sqrt((5 + SQ5) / 8);
    function _one_line(ctx, r) {
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
    }
    function _one_x(ctx, r) {
        ctx.rotate(Math.PI / 4);
        _one_cross(ctx, r);
        ctx.rotate(-Math.PI / 4);
    }
    function _one_y(ctx, r) {
        var h = r * SQ3;
        var a = h / 3;
        ctx.moveTo(-h / 2, -a);
        ctx.lineTo(0, 0);
        ctx.lineTo(h / 2, -a);
        ctx.lineTo(0, 0);
        ctx.lineTo(0, r);
    }
    function _one_cross(ctx, r) {
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
    }
    function _one_dot(ctx, r) {
        ctx.beginPath();
        ctx.arc(0, 0, r / 4, 0, 2 * Math.PI, false);
        ctx.closePath();
    }
    function _one_diamond(ctx, r) {
        ctx.moveTo(0, r);
        ctx.lineTo(r / 1.5, 0);
        ctx.lineTo(0, -r);
        ctx.lineTo(-r / 1.5, 0);
        ctx.closePath();
    }
    function _one_hex(ctx, r) {
        var r2 = r / 2;
        var h = SQ3 * r2;
        ctx.moveTo(r, 0);
        ctx.lineTo(r2, -h);
        ctx.lineTo(-r2, -h);
        ctx.lineTo(-r, 0);
        ctx.lineTo(-r2, h);
        ctx.lineTo(r2, h);
        ctx.closePath();
    }
    function _one_star(ctx, r) {
        var a = Math.sqrt(5 - 2 * SQ5) * r;
        ctx.moveTo(0, -r);
        ctx.lineTo(a * c72, -r + a * s72);
        ctx.lineTo(a * (1 + c72), -r + a * s72);
        ctx.lineTo(a * (1 + c72 - c36), -r + a * (s72 + s36));
        ctx.lineTo(a * (1 + 2 * c72 - c36), -r + a * (2 * s72 + s36));
        ctx.lineTo(0, -r + a * 2 * s72);
        ctx.lineTo(-a * (1 + 2 * c72 - c36), -r + a * (2 * s72 + s36));
        ctx.lineTo(-a * (1 + c72 - c36), -r + a * (s72 + s36));
        ctx.lineTo(-a * (1 + c72), -r + a * s72);
        ctx.lineTo(-a * c72, -r + a * s72);
        ctx.closePath();
    }
    function _one_tri(ctx, r) {
        var h = r * SQ3;
        var a = h / 3;
        ctx.moveTo(-r, a);
        ctx.lineTo(r, a);
        ctx.lineTo(0, a - h);
        ctx.closePath();
    }
    function asterisk(ctx, i, r, visuals) {
        _one_cross(ctx, r);
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function circle(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function circle_cross(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            _one_cross(ctx, r);
            ctx.stroke();
        }
    }
    function circle_dot(ctx, i, r, visuals) {
        circle(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function circle_y(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            _one_y(ctx, r);
            ctx.stroke();
        }
    }
    function circle_x(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            _one_x(ctx, r);
            ctx.stroke();
        }
    }
    function cross(ctx, i, r, visuals) {
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function diamond(ctx, i, r, visuals) {
        _one_diamond(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function diamond_cross(ctx, i, r, visuals) {
        _one_diamond(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.moveTo(0, r);
            ctx.lineTo(0, -r);
            ctx.moveTo(-r / 1.5, 0);
            ctx.lineTo(r / 1.5, 0);
            ctx.stroke();
        }
    }
    function diamond_dot(ctx, i, r, visuals) {
        diamond(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function dot(ctx, i, r, visuals) {
        _one_dot(ctx, r);
        visuals.line.set_vectorize(ctx, i);
        ctx.fillStyle = ctx.strokeStyle; // NOTE: dots use line color for fill to match
        ctx.fill();
    }
    function hex(ctx, i, r, visuals) {
        _one_hex(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function hex_dot(ctx, i, r, visuals) {
        hex(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function inverted_triangle(ctx, i, r, visuals) {
        ctx.rotate(Math.PI);
        _one_tri(ctx, r);
        ctx.rotate(-Math.PI);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function plus(ctx, i, r, visuals) {
        var a = 3 * r / 8;
        var b = r;
        var xs = [a, a, b, b, a, a, -a, -a, -b, -b, -a, -a];
        var ys = [b, a, a, -a, -a, -b, -b, -a, -a, a, a, b];
        ctx.beginPath();
        for (var j = 0; j < 12; j++) {
            ctx.lineTo(xs[j], ys[j]);
        }
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square(ctx, i, r, visuals) {
        var size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square_pin(ctx, i, r, visuals) {
        var a = 3 * r / 8;
        ctx.moveTo(-r, -r);
        /* eslint-disable space-in-parens */
        ctx.quadraticCurveTo(0, -a, r, -r);
        ctx.quadraticCurveTo(a, 0, r, r);
        ctx.quadraticCurveTo(0, a, -r, r);
        ctx.quadraticCurveTo(-a, 0, -r, -r);
        /* eslint-ensable space-in-parens */
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square_cross(ctx, i, r, visuals) {
        var size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            _one_cross(ctx, r);
            ctx.stroke();
        }
    }
    function square_dot(ctx, i, r, visuals) {
        square(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function square_x(ctx, i, r, visuals) {
        var size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.moveTo(-r, r);
            ctx.lineTo(r, -r);
            ctx.moveTo(-r, -r);
            ctx.lineTo(r, r);
            ctx.stroke();
        }
    }
    function star(ctx, i, r, visuals) {
        _one_star(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function star_dot(ctx, i, r, visuals) {
        star(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function triangle(ctx, i, r, visuals) {
        _one_tri(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function triangle_dot(ctx, i, r, visuals) {
        triangle(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function triangle_pin(ctx, i, r, visuals) {
        var h = r * SQ3;
        var a = h / 3;
        var b = 3 * a / 8;
        ctx.moveTo(-r, a);
        ctx.quadraticCurveTo(0, b, r, a);
        ctx.quadraticCurveTo(SQ3 * b / 2, b / 2, 0, a - h);
        ctx.quadraticCurveTo(-SQ3 * b / 2, b / 2, -r, a);
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function dash(ctx, i, r, visuals) {
        _one_line(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function x(ctx, i, r, visuals) {
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function y(ctx, i, r, visuals) {
        _one_y(ctx, r);
        visuals.line.apply(ctx, i);
    }
    exports.marker_funcs = {
        asterisk: asterisk,
        circle: circle,
        circle_cross: circle_cross,
        circle_dot: circle_dot,
        circle_y: circle_y,
        circle_x: circle_x,
        cross: cross,
        diamond: diamond,
        diamond_dot: diamond_dot,
        diamond_cross: diamond_cross,
        dot: dot,
        hex: hex,
        hex_dot: hex_dot,
        inverted_triangle: inverted_triangle,
        plus: plus,
        square: square,
        square_cross: square_cross,
        square_dot: square_dot,
        square_pin: square_pin,
        square_x: square_x,
        star: star,
        star_dot: star_dot,
        triangle: triangle,
        triangle_dot: triangle_dot,
        triangle_pin: triangle_pin,
        dash: dash,
        x: x,
        y: y,
    };
},
/* models/glyphs/segment.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var glyph_1 = require(294) /* ./glyph */;
    var utils_1 = require(299) /* ./utils */;
    var selection_1 = require(187) /* ../selections/selection */;
    var SegmentView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SegmentView, _super);
        function SegmentView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SegmentView.prototype._project_data = function () {
            projections_1.inplace.project_xy(this._x0, this._y0);
            projections_1.inplace.project_xy(this._x1, this._y1);
        };
        SegmentView.prototype._index_data = function (index) {
            var min = Math.min, max = Math.max;
            var _b = this, _x0 = _b._x0, _x1 = _b._x1, _y0 = _b._y0, _y1 = _b._y1, data_size = _b.data_size;
            for (var i = 0; i < data_size; i++) {
                var x0 = _x0[i];
                var x1 = _x1[i];
                var y0 = _y0[i];
                var y1 = _y1[i];
                index.add_rect(min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1));
            }
        };
        SegmentView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            if (this.visuals.line.doit) {
                var _c = data !== null && data !== void 0 ? data : this, sx0 = _c.sx0, sy0 = _c.sy0, sx1 = _c.sx1, sy1 = _c.sy1;
                try {
                    for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                        var i = indices_1_1.value;
                        var sx0_i = sx0[i];
                        var sy0_i = sy0[i];
                        var sx1_i = sx1[i];
                        var sy1_i = sy1[i];
                        if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i))
                            continue;
                        ctx.beginPath();
                        ctx.moveTo(sx0_i, sy0_i);
                        ctx.lineTo(sx1_i, sy1_i);
                        this.visuals.line.set_vectorize(ctx, i);
                        ctx.stroke();
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                            _b.call(indices_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
        };
        SegmentView.prototype._hit_point = function (geometry) {
            var e_2, _b;
            var sx = geometry.sx, sy = geometry.sy;
            var point = { x: sx, y: sy };
            var lw_voffset = 2; // FIXME: Use maximum of segments line_width/2 instead of magic constant 2
            var _c = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx - lw_voffset, sx + lw_voffset), 2), x0 = _c[0], x1 = _c[1];
            var _d = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy - lw_voffset, sy + lw_voffset), 2), y0 = _d[0], y1 = _d[1];
            var candidates = this.index.indices({ x0: x0, y0: y0, x1: x1, y1: y1 });
            var indices = [];
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var i = candidates_1_1.value;
                    var threshold2 = Math.pow(Math.max(2, this.line_width.get(i) / 2), 2);
                    var p0 = { x: this.sx0[i], y: this.sy0[i] };
                    var p1 = { x: this.sx1[i], y: this.sy1[i] };
                    var dist2 = hittest.dist_to_segment_squared(point, p0, p1);
                    if (dist2 < threshold2) {
                        indices.push(i);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_b = candidates_1.return))
                        _b.call(candidates_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        SegmentView.prototype._hit_span = function (geometry) {
            var _b, _c, e_3, _d;
            var _e = (0, tslib_1.__read)(this.renderer.plot_view.frame.bbox.ranges, 2), hr = _e[0], vr = _e[1];
            var sx = geometry.sx, sy = geometry.sy;
            var v0;
            var v1;
            var val;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                _b = (0, tslib_1.__read)([this._y0, this._y1], 2), v0 = _b[0], v1 = _b[1];
            }
            else {
                val = this.renderer.xscale.invert(sx);
                _c = (0, tslib_1.__read)([this._x0, this._x1], 2), v0 = _c[0], v1 = _c[1];
            }
            var indices = [];
            var _f = (0, tslib_1.__read)(this.renderer.xscale.r_invert(hr.start, hr.end), 2), x0 = _f[0], x1 = _f[1];
            var _g = (0, tslib_1.__read)(this.renderer.yscale.r_invert(vr.start, vr.end), 2), y0 = _g[0], y1 = _g[1];
            var candidates = this.index.indices({ x0: x0, y0: y0, x1: x1, y1: y1 });
            try {
                for (var candidates_2 = (0, tslib_1.__values)(candidates), candidates_2_1 = candidates_2.next(); !candidates_2_1.done; candidates_2_1 = candidates_2.next()) {
                    var i = candidates_2_1.value;
                    if ((v0[i] <= val && val <= v1[i]) || (v1[i] <= val && val <= v0[i]))
                        indices.push(i);
                    var threshold = 1.5 + (this.line_width.get(i) / 2); // Maximum pixel difference to detect hit
                    if (v0[i] == v1[i]) {
                        if (geometry.direction == "h") {
                            if (Math.abs(this.sx0[i] - sx) <= threshold) {
                                indices.push(i);
                            }
                        }
                        else {
                            if (Math.abs(this.sy0[i] - sy) <= threshold) {
                                indices.push(i);
                            }
                        }
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (candidates_2_1 && !candidates_2_1.done && (_d = candidates_2.return))
                        _d.call(candidates_2);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        SegmentView.prototype.scenterxy = function (i) {
            var scx = this.sx0[i] / 2 + this.sx1[i] / 2;
            var scy = this.sy0[i] / 2 + this.sy1[i] / 2;
            return [scx, scy];
        };
        SegmentView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        };
        return SegmentView;
    }(glyph_1.GlyphView));
    exports.SegmentView = SegmentView;
    SegmentView.__name__ = "SegmentView";
    var Segment = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Segment, _super);
        function Segment(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Segment;
    }(glyph_1.Glyph));
    exports.Segment = Segment;
    _a = Segment;
    Segment.__name__ = "Segment";
    (function () {
        _a.prototype.default_view = SegmentView;
        _a.define(function (_b) {
            return ({
                x0: [p.XCoordinateSpec, { field: "x0" }],
                y0: [p.YCoordinateSpec, { field: "y0" }],
                x1: [p.XCoordinateSpec, { field: "x1" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
            });
        });
        _a.mixins(property_mixins_1.LineVector);
    })();
},
/* models/glyphs/spline.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var interpolation_1 = require(411) /* ../../core/util/interpolation */;
    var SplineView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SplineView, _super);
        function SplineView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SplineView.prototype._set_data = function () {
            var _b;
            var _c = this.model, tension = _c.tension, closed = _c.closed;
            _b = (0, tslib_1.__read)((0, interpolation_1.catmullrom_spline)(this._x, this._y, 20, tension, closed), 2), this._xt = _b[0], this._yt = _b[1];
        };
        SplineView.prototype._map_data = function () {
            var _b = this.renderer.coordinates, x_scale = _b.x_scale, y_scale = _b.y_scale;
            this.sxt = x_scale.v_compute(this._xt);
            this.syt = y_scale.v_compute(this._yt);
        };
        SplineView.prototype._render = function (ctx, _indices, data) {
            var _b = data !== null && data !== void 0 ? data : this, sx = _b.sxt, sy = _b.syt;
            var move = true;
            ctx.beginPath();
            var n = sx.length;
            for (var j = 0; j < n; j++) {
                var sx_i = sx[j];
                var sy_i = sy[j];
                if (!isFinite(sx_i + sy_i))
                    move = true;
                else {
                    if (move) {
                        ctx.moveTo(sx_i, sy_i);
                        move = false;
                    }
                    else
                        ctx.lineTo(sx_i, sy_i);
                }
            }
            this.visuals.line.set_value(ctx);
            ctx.stroke();
        };
        return SplineView;
    }(xy_glyph_1.XYGlyphView));
    exports.SplineView = SplineView;
    SplineView.__name__ = "SplineView";
    var Spline = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Spline, _super);
        function Spline(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Spline;
    }(xy_glyph_1.XYGlyph));
    exports.Spline = Spline;
    _a = Spline;
    Spline.__name__ = "Spline";
    (function () {
        _a.prototype.default_view = SplineView;
        _a.mixins(mixins.LineScalar);
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Number = _b.Number;
            return ({
                tension: [Number, 0.5],
                closed: [Boolean, false],
            });
        });
    })();
},
/* core/util/interpolation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(139) /* ../types */;
    var assert_1 = require(127) /* ./assert */;
    function catmullrom_spline(x, y, T, tension, closed) {
        if (T === void 0) {
            T = 10;
        }
        if (tension === void 0) {
            tension = 0.5;
        }
        if (closed === void 0) {
            closed = false;
        }
        /** Centripetal Catmull-Rom spline. */
        (0, assert_1.assert)(x.length == y.length);
        var n = x.length;
        var N = closed ? n + 1 : n;
        var ArrayType = (0, types_1.infer_type)(x, y);
        var xx = new ArrayType(N + 2);
        var yy = new ArrayType(N + 2);
        xx.set(x, 1);
        yy.set(y, 1);
        if (closed) {
            xx[0] = x[n - 1];
            yy[0] = y[n - 1];
            xx[N] = x[0];
            yy[N] = y[0];
            xx[N + 1] = x[1];
            yy[N + 1] = y[1];
        }
        else {
            xx[0] = x[0];
            yy[0] = y[0];
            xx[N + 1] = x[n - 1];
            yy[N + 1] = y[n - 1];
        }
        var basis = new ArrayType(4 * (T + 1));
        for (var j = 0, k = 0; j <= T; j++) {
            var t = j / T;
            var t_2 = Math.pow(t, 2);
            var t_3 = t * t_2;
            basis[k++] = 2 * t_3 - 3 * t_2 + 1; // h00
            basis[k++] = -2 * t_3 + 3 * t_2; // h01
            basis[k++] = t_3 - 2 * t_2 + t; // h10
            basis[k++] = t_3 - t_2; // h11
        }
        var xt = new ArrayType((N - 1) * (T + 1));
        var yt = new ArrayType((N - 1) * (T + 1));
        for (var i = 1, k = 0; i < N; i++) {
            var t0x = (xx[i + 1] - xx[i - 1]) * tension;
            var t0y = (yy[i + 1] - yy[i - 1]) * tension;
            var t1x = (xx[i + 2] - xx[i]) * tension;
            var t1y = (yy[i + 2] - yy[i]) * tension;
            for (var j = 0; j <= 4 * T; k++) {
                var h00 = basis[j++];
                var h01 = basis[j++];
                var h10 = basis[j++];
                var h11 = basis[j++];
                xt[k] = h00 * xx[i] + h01 * xx[i + 1] + h10 * t0x + h11 * t1x;
                yt[k] = h00 * yy[i] + h01 * yy[i + 1] + h10 * t0y + h11 * t1y;
            }
        }
        return [xt, yt];
    }
    exports.catmullrom_spline = catmullrom_spline;
},
/* models/glyphs/step.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var utils_1 = require(299) /* ./utils */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var enums_1 = require(135) /* ../../core/enums */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var StepView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(StepView, _super);
        function StepView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        StepView.prototype._render = function (ctx, indices, data) {
            var e_1, _b, _c, _d, _e, _f, _g, _h;
            var _j = data !== null && data !== void 0 ? data : this, sx = _j.sx, sy = _j.sy;
            var drawing = false;
            var last_index = null;
            this.visuals.line.set_value(ctx);
            var L = indices.length;
            if (L < 2)
                return;
            ctx.beginPath();
            ctx.moveTo(sx[0], sy[0]);
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var x1 = void 0, x2 = void 0;
                    var y1 = void 0, y2 = void 0;
                    switch (this.model.mode) {
                        case "before": {
                            _c = (0, tslib_1.__read)([sx[i - 1], sy[i]], 2), x1 = _c[0], y1 = _c[1];
                            _d = (0, tslib_1.__read)([sx[i], sy[i]], 2), x2 = _d[0], y2 = _d[1];
                            break;
                        }
                        case "after": {
                            _e = (0, tslib_1.__read)([sx[i], sy[i - 1]], 2), x1 = _e[0], y1 = _e[1];
                            _f = (0, tslib_1.__read)([sx[i], sy[i]], 2), x2 = _f[0], y2 = _f[1];
                            break;
                        }
                        case "center": {
                            var xm = (sx[i - 1] + sx[i]) / 2;
                            _g = (0, tslib_1.__read)([xm, sy[i - 1]], 2), x1 = _g[0], y1 = _g[1];
                            _h = (0, tslib_1.__read)([xm, sy[i]], 2), x2 = _h[0], y2 = _h[1];
                            break;
                        }
                        default:
                            (0, assert_1.unreachable)();
                    }
                    if (drawing) {
                        if (!isFinite(sx[i] + sy[i])) {
                            ctx.stroke();
                            ctx.beginPath();
                            drawing = false;
                            last_index = i;
                            continue;
                        }
                        if (last_index != null && i - last_index > 1) {
                            ctx.stroke();
                            drawing = false;
                        }
                    }
                    if (drawing) {
                        ctx.lineTo(x1, y1);
                        ctx.lineTo(x2, y2);
                    }
                    else {
                        ctx.beginPath();
                        ctx.moveTo(sx[i], sy[i]);
                        drawing = true;
                    }
                    last_index = i;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            ctx.lineTo(sx[L - 1], sy[L - 1]);
            ctx.stroke();
        };
        StepView.prototype.draw_legend_for_index = function (ctx, bbox, _index) {
            (0, utils_1.generic_line_scalar_legend)(this.visuals, ctx, bbox);
        };
        return StepView;
    }(xy_glyph_1.XYGlyphView));
    exports.StepView = StepView;
    StepView.__name__ = "StepView";
    var Step = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Step, _super);
        function Step(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Step;
    }(xy_glyph_1.XYGlyph));
    exports.Step = Step;
    _a = Step;
    Step.__name__ = "Step";
    (function () {
        _a.prototype.default_view = StepView;
        _a.mixins(mixins.LineScalar);
        _a.define(function () {
            return ({
                mode: [enums_1.StepMode, "before"],
            });
        });
    })();
},
/* models/glyphs/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../core/hittest */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var text_1 = require(236) /* ../../core/util/text */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var selection_1 = require(187) /* ../selections/selection */;
    var TextView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextView, _super);
        function TextView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TextView.prototype._rotate_point = function (x, y, xoff, yoff, angle) {
            var sxr = (x - xoff) * Math.cos(angle) - (y - yoff) * Math.sin(angle) + xoff;
            var syr = (x - xoff) * Math.sin(angle) + (y - yoff) * Math.cos(angle) + yoff;
            return [sxr, syr];
        };
        TextView.prototype._text_bounds = function (x0, y0, width, height) {
            var xvals = [x0, x0 + width, x0 + width, x0, x0];
            var yvals = [y0, y0, y0 - height, y0 - height, y0];
            return [xvals, yvals];
        };
        TextView.prototype._render = function (ctx, indices, data) {
            var e_1, _b, e_2, _c;
            var _d = data !== null && data !== void 0 ? data : this, sx = _d.sx, sy = _d.sy, x_offset = _d.x_offset, y_offset = _d.y_offset, angle = _d.angle, text = _d.text;
            this._sys = [];
            this._sxs = [];
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sxs_i = this._sxs[i] = [];
                    var sys_i = this._sys[i] = [];
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var x_offset_i = x_offset.get(i);
                    var y_offset_i = y_offset.get(i);
                    var angle_i = angle.get(i);
                    var text_i = text.get(i);
                    if (!isFinite(sx_i + sy_i + x_offset_i + y_offset_i + angle_i) || text_i == null)
                        continue;
                    if (this.visuals.text.doit) {
                        var text_2 = "" + text_i;
                        ctx.save();
                        ctx.translate(sx_i + x_offset_i, sy_i + y_offset_i);
                        ctx.rotate(angle_i);
                        this.visuals.text.set_vectorize(ctx, i);
                        var font = this.visuals.text.font_value(i);
                        var height = (0, text_1.font_metrics)(font).height;
                        var line_height = this.text_line_height.get(i) * height;
                        if (text_2.indexOf("\n") == -1) {
                            ctx.fillText(text_2, 0, 0);
                            var x0 = sx_i + x_offset_i;
                            var y0 = sy_i + y_offset_i;
                            var width = ctx.measureText(text_2).width;
                            var _e = (0, tslib_1.__read)(this._text_bounds(x0, y0, width, line_height), 2), xvalues = _e[0], yvalues = _e[1];
                            sxs_i.push(xvalues);
                            sys_i.push(yvalues);
                        }
                        else {
                            var lines = text_2.split("\n");
                            var block_height = line_height * lines.length;
                            var baseline = this.text_baseline.get(i);
                            var y = void 0;
                            switch (baseline) {
                                case "top": {
                                    y = 0;
                                    break;
                                }
                                case "middle": {
                                    y = (-block_height / 2) + (line_height / 2);
                                    break;
                                }
                                case "bottom": {
                                    y = -block_height + line_height;
                                    break;
                                }
                                default: {
                                    y = 0;
                                    console.warn("'" + baseline + "' baseline not supported with multi line text");
                                }
                            }
                            try {
                                for (var lines_1 = (e_2 = void 0, (0, tslib_1.__values)(lines)), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
                                    var line = lines_1_1.value;
                                    ctx.fillText(line, 0, y);
                                    var x0 = sx_i + x_offset_i;
                                    var y0 = y + sy_i + y_offset_i;
                                    var width = ctx.measureText(line).width;
                                    var _f = (0, tslib_1.__read)(this._text_bounds(x0, y0, width, line_height), 2), xvalues = _f[0], yvalues = _f[1];
                                    sxs_i.push(xvalues);
                                    sys_i.push(yvalues);
                                    y += line_height;
                                }
                            }
                            catch (e_2_1) {
                                e_2 = { error: e_2_1 };
                            }
                            finally {
                                try {
                                    if (lines_1_1 && !lines_1_1.done && (_c = lines_1.return))
                                        _c.call(lines_1);
                                }
                                finally {
                                    if (e_2)
                                        throw e_2.error;
                                }
                            }
                        }
                        ctx.restore();
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        TextView.prototype._hit_point = function (geometry) {
            var sx = geometry.sx, sy = geometry.sy;
            var indices = [];
            for (var i = 0; i < this._sxs.length; i++) {
                var sxs = this._sxs[i];
                var sys = this._sys[i];
                var n = sxs.length;
                for (var j = 0, endj = n; j < endj; j++) {
                    var _b = (0, tslib_1.__read)(this._rotate_point(sx, sy, sxs[n - 1][0], sys[n - 1][0], -this.angle.get(i)), 2), sxr = _b[0], syr = _b[1];
                    if (hittest.point_in_poly(sxr, syr, sxs[j], sys[j])) {
                        indices.push(i);
                    }
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        TextView.prototype.scenterxy = function (i) {
            var sxs = this._sxs[i];
            var sys = this._sys[i];
            (0, assert_1.assert)(sxs.length != 0 && sys.length != 0);
            var sx0 = sxs[0][0];
            var sy0 = sys[0][0];
            var sxc = (sxs[0][2] + sx0) / 2;
            var syc = (sys[0][2] + sy0) / 2;
            var _b = (0, tslib_1.__read)(this._rotate_point(sxc, syc, sx0, sy0, this.angle.get(i)), 2), sxcr = _b[0], sycr = _b[1];
            return [sxcr, sycr];
        };
        return TextView;
    }(xy_glyph_1.XYGlyphView));
    exports.TextView = TextView;
    TextView.__name__ = "TextView";
    var Text = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Text, _super);
        function Text(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Text;
    }(xy_glyph_1.XYGlyph));
    exports.Text = Text;
    _a = Text;
    Text.__name__ = "Text";
    (function () {
        _a.prototype.default_view = TextView;
        _a.mixins(property_mixins_1.TextVector);
        _a.define(function (_b) {
            return ({
                text: [p.NullStringSpec, { field: "text" }],
                angle: [p.AngleSpec, 0],
                x_offset: [p.NumberSpec, 0],
                y_offset: [p.NumberSpec, 0],
            });
        });
    })();
},
/* models/glyphs/vbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var box_1 = require(392) /* ./box */;
    var types_1 = require(139) /* ../../core/types */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var VBarView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VBarView, _super);
        function VBarView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        VBarView.prototype.scenterxy = function (i) {
            var scx = this.sx[i];
            var scy = (this.stop[i] + this.sbottom[i]) / 2;
            return [scx, scy];
        };
        VBarView.prototype._lrtb = function (i) {
            var half_width_i = this.width.get(i) / 2;
            var x_i = this._x[i];
            var top_i = this._top[i];
            var bottom_i = this._bottom[i];
            var l = x_i - half_width_i;
            var r = x_i + half_width_i;
            var t = Math.max(top_i, bottom_i);
            var b = Math.min(top_i, bottom_i);
            return [l, r, t, b];
        };
        VBarView.prototype._map_data = function () {
            this.sx = this.renderer.xscale.v_compute(this._x);
            this.sw = this.sdist(this.renderer.xscale, this._x, this.width, "center");
            this.stop = this.renderer.yscale.v_compute(this._top);
            this.sbottom = this.renderer.yscale.v_compute(this._bottom);
            var n = this.sx.length;
            this.sleft = new types_1.ScreenArray(n);
            this.sright = new types_1.ScreenArray(n);
            for (var i = 0; i < n; i++) {
                this.sleft[i] = this.sx[i] - this.sw[i] / 2;
                this.sright[i] = this.sx[i] + this.sw[i] / 2;
            }
            this._clamp_viewport();
        };
        return VBarView;
    }(box_1.BoxView));
    exports.VBarView = VBarView;
    VBarView.__name__ = "VBarView";
    var VBar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(VBar, _super);
        function VBar(attrs) {
            return _super.call(this, attrs) || this;
        }
        return VBar;
    }(box_1.Box));
    exports.VBar = VBar;
    _a = VBar;
    VBar.__name__ = "VBar";
    (function () {
        _a.prototype.default_view = VBarView;
        _a.define(function (_b) {
            return ({
                x: [p.XCoordinateSpec, { field: "x" }],
                bottom: [p.YCoordinateSpec, { value: 0 }],
                width: [p.NumberSpec, { value: 1 }],
                top: [p.YCoordinateSpec, { field: "top" }],
            });
        });
    })();
},
/* models/glyphs/wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var xy_glyph_1 = require(293) /* ./xy_glyph */;
    var utils_1 = require(299) /* ./utils */;
    var property_mixins_1 = require(163) /* ../../core/property_mixins */;
    var types_1 = require(139) /* ../../core/types */;
    var enums_1 = require(135) /* ../../core/enums */;
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var math_1 = require(117) /* ../../core/util/math */;
    var selection_1 = require(187) /* ../selections/selection */;
    var WedgeView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WedgeView, _super);
        function WedgeView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        WedgeView.prototype._map_data = function () {
            if (this.model.properties.radius.units == "data")
                this.sradius = this.sdist(this.renderer.xscale, this._x, this.radius);
            else
                this.sradius = (0, types_1.to_screen)(this.radius);
        };
        WedgeView.prototype._render = function (ctx, indices, data) {
            var e_1, _b;
            var _c = data !== null && data !== void 0 ? data : this, sx = _c.sx, sy = _c.sy, sradius = _c.sradius, start_angle = _c.start_angle, end_angle = _c.end_angle;
            var anticlock = this.model.direction == "anticlock";
            try {
                for (var indices_1 = (0, tslib_1.__values)(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {
                    var i = indices_1_1.value;
                    var sx_i = sx[i];
                    var sy_i = sy[i];
                    var sradius_i = sradius[i];
                    var start_angle_i = start_angle.get(i);
                    var end_angle_i = end_angle.get(i);
                    if (!isFinite(sx_i + sy_i + sradius_i + start_angle_i + end_angle_i))
                        continue;
                    ctx.beginPath();
                    ctx.arc(sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                    ctx.lineTo(sx_i, sy_i);
                    ctx.closePath();
                    this.visuals.fill.apply(ctx, i);
                    this.visuals.hatch.apply(ctx, i);
                    this.visuals.line.apply(ctx, i);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (indices_1_1 && !indices_1_1.done && (_b = indices_1.return))
                        _b.call(indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        WedgeView.prototype._hit_point = function (geometry) {
            var _b, _c, e_2, _d, _e, _f, e_3, _g;
            var dist, sx0, sx1, sy0, sy1, x0, x1, y0, y1;
            var sx = geometry.sx, sy = geometry.sy;
            var x = this.renderer.xscale.invert(sx);
            var y = this.renderer.yscale.invert(sy);
            // check diameter first
            var max_diameter = 2 * this.max_radius;
            if (this.model.properties.radius.units === "data") {
                x0 = x - max_diameter;
                x1 = x + max_diameter;
                y0 = y - max_diameter;
                y1 = y + max_diameter;
            }
            else {
                sx0 = sx - max_diameter;
                sx1 = sx + max_diameter;
                _b = (0, tslib_1.__read)(this.renderer.xscale.r_invert(sx0, sx1), 2), x0 = _b[0], x1 = _b[1];
                sy0 = sy - max_diameter;
                sy1 = sy + max_diameter;
                _c = (0, tslib_1.__read)(this.renderer.yscale.r_invert(sy0, sy1), 2), y0 = _c[0], y1 = _c[1];
            }
            var candidates = [];
            try {
                for (var _h = (0, tslib_1.__values)(this.index.indices({ x0: x0, x1: x1, y0: y0, y1: y1 })), _j = _h.next(); !_j.done; _j = _h.next()) {
                    var i = _j.value;
                    var r2 = Math.pow(this.sradius[i], 2);
                    _e = (0, tslib_1.__read)(this.renderer.xscale.r_compute(x, this._x[i]), 2), sx0 = _e[0], sx1 = _e[1];
                    _f = (0, tslib_1.__read)(this.renderer.yscale.r_compute(y, this._y[i]), 2), sy0 = _f[0], sy1 = _f[1];
                    dist = Math.pow((sx0 - sx1), 2) + Math.pow((sy0 - sy1), 2);
                    if (dist <= r2) {
                        candidates.push(i);
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_j && !_j.done && (_d = _h.return))
                        _d.call(_h);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            var anticlock = this.model.direction == "anticlock";
            var indices = [];
            try {
                for (var candidates_1 = (0, tslib_1.__values)(candidates), candidates_1_1 = candidates_1.next(); !candidates_1_1.done; candidates_1_1 = candidates_1.next()) {
                    var i = candidates_1_1.value;
                    // NOTE: minus the angle because JS uses non-mathy convention for angles
                    var angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
                    if ((0, math_1.angle_between)(-angle, -this.start_angle.get(i), -this.end_angle.get(i), anticlock)) {
                        indices.push(i);
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (candidates_1_1 && !candidates_1_1.done && (_g = candidates_1.return))
                        _g.call(candidates_1);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            return new selection_1.Selection({ indices: indices });
        };
        WedgeView.prototype.draw_legend_for_index = function (ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        };
        WedgeView.prototype.scenterxy = function (i) {
            var r = this.sradius[i] / 2;
            var a = (this.start_angle.get(i) + this.end_angle.get(i)) / 2;
            var scx = this.sx[i] + r * Math.cos(a);
            var scy = this.sy[i] + r * Math.sin(a);
            return [scx, scy];
        };
        return WedgeView;
    }(xy_glyph_1.XYGlyphView));
    exports.WedgeView = WedgeView;
    WedgeView.__name__ = "WedgeView";
    var Wedge = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Wedge, _super);
        function Wedge(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Wedge;
    }(xy_glyph_1.XYGlyph));
    exports.Wedge = Wedge;
    _a = Wedge;
    Wedge.__name__ = "Wedge";
    (function () {
        _a.prototype.default_view = WedgeView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(function (_b) {
            return ({
                direction: [enums_1.Direction, "anticlock"],
                radius: [p.DistanceSpec, { field: "radius" }],
                start_angle: [p.AngleSpec, { field: "start_angle" }],
                end_angle: [p.AngleSpec, { field: "end_angle" }],
            });
        });
    })();
},
/* models/graphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    (0, tslib_1.__exportStar)(require(417) /* ./graph_hit_test_policy */, exports);
    (0, tslib_1.__exportStar)(require(418) /* ./layout_provider */, exports);
    (0, tslib_1.__exportStar)(require(419) /* ./static_layout_provider */, exports);
},
/* models/graphs/graph_hit_test_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../../model */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var array_1 = require(126) /* ../../core/util/array */;
    var selection_1 = require(187) /* ../selections/selection */;
    var GraphHitTestPolicy = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GraphHitTestPolicy, _super);
        function GraphHitTestPolicy(attrs) {
            return _super.call(this, attrs) || this;
        }
        GraphHitTestPolicy.prototype._hit_test = function (geometry, graph_view, renderer_view) {
            if (!graph_view.model.visible)
                return null;
            var hit_test_result = renderer_view.glyph.hit_test(geometry);
            if (hit_test_result == null)
                return null;
            else
                return renderer_view.model.view.convert_selection_from_subset(hit_test_result);
        };
        return GraphHitTestPolicy;
    }(model_1.Model));
    exports.GraphHitTestPolicy = GraphHitTestPolicy;
    GraphHitTestPolicy.__name__ = "GraphHitTestPolicy";
    var EdgesOnly = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EdgesOnly, _super);
        function EdgesOnly(attrs) {
            return _super.call(this, attrs) || this;
        }
        EdgesOnly.prototype.hit_test = function (geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.edge_view);
        };
        EdgesOnly.prototype.do_selection = function (hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            var edge_selection = graph.edge_renderer.data_source.selected;
            edge_selection.update(hit_test_result, final, mode);
            graph.edge_renderer.data_source._select.emit();
            return !edge_selection.is_empty();
        };
        EdgesOnly.prototype.do_inspection = function (hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            var edge_renderer = graph_view.model.edge_renderer;
            var edge_inspection = edge_renderer.get_selection_manager().get_or_create_inspector(graph_view.edge_view.model);
            edge_inspection.update(hit_test_result, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            graph_view.edge_view.model.data_source.inspect.emit([graph_view.edge_view.model, { geometry: geometry }]);
            return !edge_inspection.is_empty();
        };
        return EdgesOnly;
    }(GraphHitTestPolicy));
    exports.EdgesOnly = EdgesOnly;
    EdgesOnly.__name__ = "EdgesOnly";
    var NodesOnly = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NodesOnly, _super);
        function NodesOnly(attrs) {
            return _super.call(this, attrs) || this;
        }
        NodesOnly.prototype.hit_test = function (geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        };
        NodesOnly.prototype.do_selection = function (hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            var node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        };
        NodesOnly.prototype.do_inspection = function (hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            var node_renderer = graph_view.model.node_renderer;
            var node_inspection = node_renderer.get_selection_manager().get_or_create_inspector(graph_view.node_view.model);
            node_inspection.update(hit_test_result, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, { geometry: geometry }]);
            return !node_inspection.is_empty();
        };
        return NodesOnly;
    }(GraphHitTestPolicy));
    exports.NodesOnly = NodesOnly;
    NodesOnly.__name__ = "NodesOnly";
    var NodesAndLinkedEdges = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NodesAndLinkedEdges, _super);
        function NodesAndLinkedEdges(attrs) {
            return _super.call(this, attrs) || this;
        }
        NodesAndLinkedEdges.prototype.hit_test = function (geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        };
        NodesAndLinkedEdges.prototype.get_linked_edges = function (node_source, edge_source, mode) {
            var e_1, _a;
            var node_indices = [];
            if (mode == "selection") {
                node_indices = node_source.selected.indices.map(function (i) { return node_source.data.index[i]; });
            }
            else if (mode == "inspection") {
                node_indices = node_source.inspected.indices.map(function (i) { return node_source.data.index[i]; });
            }
            var edge_indices = [];
            for (var i = 0; i < edge_source.data.start.length; i++) {
                if ((0, array_1.contains)(node_indices, edge_source.data.start[i]) || (0, array_1.contains)(node_indices, edge_source.data.end[i]))
                    edge_indices.push(i);
            }
            var linked_edges = new selection_1.Selection();
            try {
                for (var edge_indices_1 = (0, tslib_1.__values)(edge_indices), edge_indices_1_1 = edge_indices_1.next(); !edge_indices_1_1.done; edge_indices_1_1 = edge_indices_1.next()) {
                    var i = edge_indices_1_1.value;
                    linked_edges.multiline_indices[i] = [0]; //currently only supports 2-element multilines, so this is all of it
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (edge_indices_1_1 && !edge_indices_1_1.done && (_a = edge_indices_1.return))
                        _a.call(edge_indices_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            linked_edges.indices = edge_indices;
            return linked_edges;
        };
        NodesAndLinkedEdges.prototype.do_selection = function (hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            var node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            var edge_selection = graph.edge_renderer.data_source.selected;
            var linked_edges_selection = this.get_linked_edges(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            edge_selection.update(linked_edges_selection, final, mode);
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        };
        NodesAndLinkedEdges.prototype.do_inspection = function (hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            var node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            node_inspection.update(hit_test_result, final, mode);
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            var edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model);
            var linked_edges = this.get_linked_edges(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            edge_inspection.update(linked_edges, final, mode);
            //silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, { geometry: geometry }]);
            return !node_inspection.is_empty();
        };
        return NodesAndLinkedEdges;
    }(GraphHitTestPolicy));
    exports.NodesAndLinkedEdges = NodesAndLinkedEdges;
    NodesAndLinkedEdges.__name__ = "NodesAndLinkedEdges";
    var EdgesAndLinkedNodes = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EdgesAndLinkedNodes, _super);
        function EdgesAndLinkedNodes(attrs) {
            return _super.call(this, attrs) || this;
        }
        EdgesAndLinkedNodes.prototype.hit_test = function (geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.edge_view);
        };
        EdgesAndLinkedNodes.prototype.get_linked_nodes = function (node_source, edge_source, mode) {
            var e_2, _a;
            var edge_indices = [];
            if (mode == "selection")
                edge_indices = edge_source.selected.indices;
            else if (mode == "inspection")
                edge_indices = edge_source.inspected.indices;
            var nodes = [];
            try {
                for (var edge_indices_2 = (0, tslib_1.__values)(edge_indices), edge_indices_2_1 = edge_indices_2.next(); !edge_indices_2_1.done; edge_indices_2_1 = edge_indices_2.next()) {
                    var i = edge_indices_2_1.value;
                    nodes.push(edge_source.data.start[i]);
                    nodes.push(edge_source.data.end[i]);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (edge_indices_2_1 && !edge_indices_2_1.done && (_a = edge_indices_2.return))
                        _a.call(edge_indices_2);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            var node_indices = (0, array_1.uniq)(nodes).map(function (i) { return (0, arrayable_1.indexOf)(node_source.data.index, i); });
            return new selection_1.Selection({ indices: node_indices });
        };
        EdgesAndLinkedNodes.prototype.do_selection = function (hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            var edge_selection = graph.edge_renderer.data_source.selected;
            edge_selection.update(hit_test_result, final, mode);
            var node_selection = graph.node_renderer.data_source.selected;
            var linked_nodes = this.get_linked_nodes(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            node_selection.update(linked_nodes, final, mode);
            graph.edge_renderer.data_source._select.emit();
            return !edge_selection.is_empty();
        };
        EdgesAndLinkedNodes.prototype.do_inspection = function (hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            var edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model);
            edge_inspection.update(hit_test_result, final, mode);
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            var node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            var linked_nodes = this.get_linked_nodes(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            node_inspection.update(linked_nodes, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            graph_view.edge_view.model.data_source.inspect.emit([graph_view.edge_view.model, { geometry: geometry }]);
            return !edge_inspection.is_empty();
        };
        return EdgesAndLinkedNodes;
    }(GraphHitTestPolicy));
    exports.EdgesAndLinkedNodes = EdgesAndLinkedNodes;
    EdgesAndLinkedNodes.__name__ = "EdgesAndLinkedNodes";
},
/* models/graphs/layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var coordinate_transform_1 = require(375) /* ../expressions/coordinate_transform */;
    var LayoutProvider = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LayoutProvider, _super);
        function LayoutProvider(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(LayoutProvider.prototype, "node_coordinates", {
            get: function () {
                return new NodeCoordinates({ layout: this });
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutProvider.prototype, "edge_coordinates", {
            get: function () {
                return new EdgeCoordinates({ layout: this });
            },
            enumerable: false,
            configurable: true
        });
        return LayoutProvider;
    }(model_1.Model));
    exports.LayoutProvider = LayoutProvider;
    LayoutProvider.__name__ = "LayoutProvider";
    var GraphCoordinates = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GraphCoordinates, _super);
        function GraphCoordinates(attrs) {
            return _super.call(this, attrs) || this;
        }
        return GraphCoordinates;
    }(coordinate_transform_1.CoordinateTransform));
    exports.GraphCoordinates = GraphCoordinates;
    _a = GraphCoordinates;
    GraphCoordinates.__name__ = "GraphCoordinates";
    (function () {
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                layout: [Ref(LayoutProvider)],
            });
        });
    })();
    var NodeCoordinates = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(NodeCoordinates, _super);
        function NodeCoordinates(attrs) {
            return _super.call(this, attrs) || this;
        }
        NodeCoordinates.prototype._v_compute = function (source) {
            var _b = (0, tslib_1.__read)(this.layout.get_node_coordinates(source), 2), x = _b[0], y = _b[1];
            return { x: x, y: y };
        };
        return NodeCoordinates;
    }(GraphCoordinates));
    exports.NodeCoordinates = NodeCoordinates;
    NodeCoordinates.__name__ = "NodeCoordinates";
    var EdgeCoordinates = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EdgeCoordinates, _super);
        function EdgeCoordinates(attrs) {
            return _super.call(this, attrs) || this;
        }
        EdgeCoordinates.prototype._v_compute = function (source) {
            var _b = (0, tslib_1.__read)(this.layout.get_edge_coordinates(source), 2), x = _b[0], y = _b[1];
            return { x: x, y: y };
        };
        return EdgeCoordinates;
    }(GraphCoordinates));
    exports.EdgeCoordinates = EdgeCoordinates;
    EdgeCoordinates.__name__ = "EdgeCoordinates";
},
/* models/graphs/static_layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var layout_provider_1 = require(418) /* ./layout_provider */;
    var StaticLayoutProvider = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(StaticLayoutProvider, _super);
        function StaticLayoutProvider(attrs) {
            return _super.call(this, attrs) || this;
        }
        StaticLayoutProvider.prototype.get_node_coordinates = function (node_source) {
            var _b;
            var index = (_b = node_source.data.index) !== null && _b !== void 0 ? _b : [];
            var n = index.length;
            var xs = new Float64Array(n);
            var ys = new Float64Array(n);
            for (var i = 0; i < n; i++) {
                var point = this.graph_layout[index[i]];
                var _c = (0, tslib_1.__read)(point !== null && point !== void 0 ? point : [NaN, NaN], 2), x = _c[0], y = _c[1];
                xs[i] = x;
                ys[i] = y;
            }
            return [xs, ys];
        };
        StaticLayoutProvider.prototype.get_edge_coordinates = function (edge_source) {
            var _b, _c;
            var starts = (_b = edge_source.data.start) !== null && _b !== void 0 ? _b : [];
            var ends = (_c = edge_source.data.end) !== null && _c !== void 0 ? _c : [];
            var n = Math.min(starts.length, ends.length);
            var xs = [];
            var ys = [];
            var has_paths = edge_source.data.xs != null && edge_source.data.ys != null;
            for (var i = 0; i < n; i++) {
                var in_layout = this.graph_layout[starts[i]] != null && this.graph_layout[ends[i]] != null;
                if (has_paths && in_layout) {
                    xs.push(edge_source.data.xs[i]);
                    ys.push(edge_source.data.ys[i]);
                }
                else {
                    var start = void 0, end = void 0;
                    if (in_layout) {
                        start = this.graph_layout[starts[i]];
                        end = this.graph_layout[ends[i]];
                    }
                    else {
                        start = [NaN, NaN];
                        end = [NaN, NaN];
                    }
                    xs.push([start[0], end[0]]);
                    ys.push([start[1], end[1]]);
                }
            }
            return [xs, ys];
        };
        return StaticLayoutProvider;
    }(layout_provider_1.LayoutProvider));
    exports.StaticLayoutProvider = StaticLayoutProvider;
    _a = StaticLayoutProvider;
    StaticLayoutProvider.__name__ = "StaticLayoutProvider";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Tuple = _b.Tuple, Dict = _b.Dict;
            return ({
                graph_layout: [Dict(Tuple(Number, Number)), {}],
            });
        });
    })();
},
/* models/grids/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var grid_1 = require(421) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
},
/* models/grids/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var axes_1 = require(242) /* ../axes */;
    var guide_renderer_1 = require(244) /* ../renderers/guide_renderer */;
    var ticker_1 = require(245) /* ../tickers/ticker */;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var types_1 = require(125) /* ../../core/util/types */;
    var GridView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GridView, _super);
        function GridView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        GridView.prototype._render = function () {
            var ctx = this.layer.ctx;
            ctx.save();
            this._draw_regions(ctx);
            this._draw_minor_grids(ctx);
            this._draw_grids(ctx);
            ctx.restore();
        };
        GridView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.change, function () { return _this.request_render(); });
        };
        GridView.prototype._draw_regions = function (ctx) {
            if (!this.visuals.band_fill.doit && !this.visuals.band_hatch.doit)
                return;
            var _b = (0, tslib_1.__read)(this.grid_coords("major", false), 2), xs = _b[0], ys = _b[1];
            for (var i = 0; i < xs.length - 1; i++) {
                if (i % 2 != 1)
                    continue;
                var _c = (0, tslib_1.__read)(this.coordinates.map_to_screen(xs[i], ys[i]), 2), sx0 = _c[0], sy0 = _c[1];
                var _d = (0, tslib_1.__read)(this.coordinates.map_to_screen(xs[i + 1], ys[i + 1]), 2), sx1 = _d[0], sy1 = _d[1];
                ctx.beginPath();
                ctx.rect(sx0[0], sy0[0], sx1[1] - sx0[0], sy1[1] - sy0[0]);
                this.visuals.band_fill.apply(ctx);
                this.visuals.band_hatch.apply(ctx);
            }
        };
        GridView.prototype._draw_grids = function (ctx) {
            if (!this.visuals.grid_line.doit)
                return;
            var _b = (0, tslib_1.__read)(this.grid_coords("major"), 2), xs = _b[0], ys = _b[1];
            this._draw_grid_helper(ctx, this.visuals.grid_line, xs, ys);
        };
        GridView.prototype._draw_minor_grids = function (ctx) {
            if (!this.visuals.minor_grid_line.doit)
                return;
            var _b = (0, tslib_1.__read)(this.grid_coords("minor"), 2), xs = _b[0], ys = _b[1];
            this._draw_grid_helper(ctx, this.visuals.minor_grid_line, xs, ys);
        };
        GridView.prototype._draw_grid_helper = function (ctx, visuals, xs, ys) {
            visuals.set_value(ctx);
            ctx.beginPath();
            for (var i = 0; i < xs.length; i++) {
                var _b = (0, tslib_1.__read)(this.coordinates.map_to_screen(xs[i], ys[i]), 2), sx = _b[0], sy = _b[1];
                ctx.moveTo(Math.round(sx[0]), Math.round(sy[0]));
                for (var i_1 = 1; i_1 < sx.length; i_1++) {
                    ctx.lineTo(Math.round(sx[i_1]), Math.round(sy[i_1]));
                }
            }
            ctx.stroke();
        };
        // {{{ TODO: state
        GridView.prototype.ranges = function () {
            var i = this.model.dimension;
            var j = (i + 1) % 2;
            var ranges = this.coordinates.ranges;
            return [ranges[i], ranges[j]];
        };
        GridView.prototype.computed_bounds = function () {
            var _b, e_1, _c, _d;
            var _e = (0, tslib_1.__read)(this.ranges(), 1), range = _e[0];
            var user_bounds = this.model.bounds;
            var range_bounds = [range.min, range.max];
            var start;
            var end;
            if ((0, types_1.isArray)(user_bounds)) {
                start = Math.min(user_bounds[0], user_bounds[1]);
                end = Math.max(user_bounds[0], user_bounds[1]);
                if (start < range_bounds[0])
                    start = range_bounds[0];
                // XXX:
                //else if (start > range_bounds[1])
                //  start = null
                if (end > range_bounds[1])
                    end = range_bounds[1];
                // XXX:
                //else if (end < range_bounds[0])
                //  end = null
            }
            else {
                _b = (0, tslib_1.__read)(range_bounds, 2), start = _b[0], end = _b[1];
                try {
                    for (var _f = (0, tslib_1.__values)(this.plot_view.axis_views), _g = _f.next(); !_g.done; _g = _f.next()) {
                        var axis_view = _g.value;
                        if (axis_view.dimension == this.model.dimension
                            && axis_view.model.x_range_name == this.model.x_range_name
                            && axis_view.model.y_range_name == this.model.y_range_name) {
                            _d = (0, tslib_1.__read)(axis_view.computed_bounds, 2), start = _d[0], end = _d[1];
                        }
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (_g && !_g.done && (_c = _f.return))
                            _c.call(_f);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
            return [start, end];
        };
        GridView.prototype.grid_coords = function (location, exclude_ends) {
            var _b;
            if (exclude_ends === void 0) {
                exclude_ends = true;
            }
            var i = this.model.dimension;
            var j = (i + 1) % 2;
            var _c = (0, tslib_1.__read)(this.ranges(), 2), range = _c[0], cross_range = _c[1];
            var _d = (0, tslib_1.__read)(this.computed_bounds(), 2), start = _d[0], end = _d[1];
            _b = (0, tslib_1.__read)([Math.min(start, end), Math.max(start, end)], 2), start = _b[0], end = _b[1];
            var coords = [[], []];
            // TODO: (bev) using cross_range.min for cross_loc is a bit of a cheat. Since we
            // currently only support "straight line" grids, this should be OK for now. If
            // we ever want to support "curved" grids, e.g. for some projections, we may
            // have to communicate more than just a single cross location.
            var ticker = this.model.get_ticker();
            if (ticker == null) {
                return coords;
            }
            var ticks = ticker.get_ticks(start, end, range, cross_range.min)[location];
            var min = range.min;
            var max = range.max;
            var cmin = cross_range.min;
            var cmax = cross_range.max;
            if (!exclude_ends) {
                if (ticks[0] != min)
                    ticks.splice(0, 0, min);
                if (ticks[ticks.length - 1] != max)
                    ticks.push(max);
            }
            for (var ii = 0; ii < ticks.length; ii++) {
                if ((ticks[ii] == min || ticks[ii] == max) && exclude_ends)
                    continue;
                var dim_i = [];
                var dim_j = [];
                var N = 2;
                for (var n = 0; n < N; n++) {
                    var loc = cmin + (cmax - cmin) / (N - 1) * n;
                    dim_i.push(ticks[ii]);
                    dim_j.push(loc);
                }
                coords[i].push(dim_i);
                coords[j].push(dim_j);
            }
            return coords;
        };
        return GridView;
    }(guide_renderer_1.GuideRendererView));
    exports.GridView = GridView;
    GridView.__name__ = "GridView";
    var Grid = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Grid, _super);
        function Grid(attrs) {
            return _super.call(this, attrs) || this;
        }
        Grid.prototype.get_ticker = function () {
            if (this.ticker != null) {
                return this.ticker;
            }
            if (this.axis != null) {
                return this.axis.ticker;
            }
            return null;
        };
        return Grid;
    }(guide_renderer_1.GuideRenderer));
    exports.Grid = Grid;
    _a = Grid;
    Grid.__name__ = "Grid";
    (function () {
        _a.prototype.default_view = GridView;
        _a.mixins([
            ["grid_", mixins.Line],
            ["minor_grid_", mixins.Line],
            ["band_", mixins.Fill],
            ["band_", mixins.Hatch],
        ]);
        _a.define(function (_b) {
            var Number = _b.Number, Auto = _b.Auto, Enum = _b.Enum, Ref = _b.Ref, Tuple = _b.Tuple, Or = _b.Or, Nullable = _b.Nullable;
            return ({
                bounds: [Or(Tuple(Number, Number), Auto), "auto"],
                dimension: [Enum(0, 1), 0],
                axis: [Nullable(Ref(axes_1.Axis)), null],
                ticker: [Nullable(Ref(ticker_1.Ticker)), null],
            });
        });
        _a.override({
            level: "underlay",
            band_fill_color: null,
            band_fill_alpha: 0,
            grid_line_color: "#e5e5e5",
            minor_grid_line_color: null,
        });
    })();
},
/* models/layouts/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var box_1 = require(423) /* ./box */;
    __esExport("Box", box_1.Box);
    var column_1 = require(425) /* ./column */;
    __esExport("Column", column_1.Column);
    var grid_box_1 = require(426) /* ./grid_box */;
    __esExport("GridBox", grid_box_1.GridBox);
    var html_box_1 = require(427) /* ./html_box */;
    __esExport("HTMLBox", html_box_1.HTMLBox);
    var layout_dom_1 = require(424) /* ./layout_dom */;
    __esExport("LayoutDOM", layout_dom_1.LayoutDOM);
    var panel_1 = require(428) /* ./panel */;
    __esExport("Panel", panel_1.Panel);
    var row_1 = require(429) /* ./row */;
    __esExport("Row", row_1.Row);
    var spacer_1 = require(430) /* ./spacer */;
    __esExport("Spacer", spacer_1.Spacer);
    var tabs_1 = require(431) /* ./tabs */;
    __esExport("Tabs", tabs_1.Tabs);
    var widget_box_1 = require(434) /* ./widget_box */;
    __esExport("WidgetBox", widget_box_1.WidgetBox);
},
/* models/layouts/box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var layout_dom_1 = require(424) /* ./layout_dom */;
    var BoxView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxView, _super);
        function BoxView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BoxView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.children.change, function () { return _this.rebuild(); });
        };
        Object.defineProperty(BoxView.prototype, "child_models", {
            get: function () {
                return this.model.children;
            },
            enumerable: false,
            configurable: true
        });
        return BoxView;
    }(layout_dom_1.LayoutDOMView));
    exports.BoxView = BoxView;
    BoxView.__name__ = "BoxView";
    var Box = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Box, _super);
        function Box(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Box;
    }(layout_dom_1.LayoutDOM));
    exports.Box = Box;
    _a = Box;
    Box.__name__ = "Box";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, Array = _b.Array, Ref = _b.Ref;
            return ({
                children: [Array(Ref(layout_dom_1.LayoutDOM)), []],
                spacing: [Number, 0],
            });
        });
    })();
},
/* models/layouts/layout_dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var enums_1 = require(135) /* ../../core/enums */;
    var dom_1 = require(158) /* ../../core/dom */;
    var logging_1 = require(134) /* ../../core/logging */;
    var types_1 = require(125) /* ../../core/util/types */;
    var color_1 = require(137) /* ../../core/util/color */;
    var text_1 = require(236) /* ../../core/util/text */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var dom_view_1 = require(341) /* ../../core/dom_view */;
    var layout_1 = require(322) /* ../../core/layout */;
    var root_css_1 = require(159) /* ../../styles/root.css */;
    var canvas_1 = require(350) /* ../../core/util/canvas */;
    var LayoutDOMView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LayoutDOMView, _super);
        function LayoutDOMView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._offset_parent = null;
            _this._viewport = {};
            return _this;
        }
        Object.defineProperty(LayoutDOMView.prototype, "is_layout_root", {
            get: function () {
                return this.is_root || !(this.parent instanceof LayoutDOMView);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(LayoutDOMView.prototype, "base_font_size", {
            get: function () {
                var font_size = getComputedStyle(this.el).fontSize;
                var result = (0, text_1.parse_css_font_size)(font_size);
                if (result != null) {
                    var value = result.value, unit = result.unit;
                    if (unit == "px")
                        return value;
                }
                return null;
            },
            enumerable: false,
            configurable: true
        });
        LayoutDOMView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.el.style.position = this.is_layout_root ? "relative" : "absolute";
            this._child_views = new Map();
        };
        LayoutDOMView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _b.sent();
                            return [4 /*yield*/, this.build_child_views()];
                        case 2:
                            _b.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        LayoutDOMView.prototype.remove = function () {
            var e_1, _b;
            try {
                for (var _c = (0, tslib_1.__values)(this.child_views), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var child_view = _d.value;
                    child_view.remove();
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            this._child_views.clear();
            _super.prototype.remove.call(this);
        };
        LayoutDOMView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            if (this.is_layout_root) {
                this._on_resize = function () { return _this.resize_layout(); };
                window.addEventListener("resize", this._on_resize);
                this._parent_observer = setInterval(function () {
                    var offset_parent = _this.el.offsetParent;
                    if (_this._offset_parent != offset_parent) {
                        _this._offset_parent = offset_parent;
                        if (offset_parent != null) {
                            _this.compute_viewport();
                            _this.invalidate_layout();
                        }
                    }
                }, 250);
            }
            var p = this.model.properties;
            this.on_change([
                p.width, p.height,
                p.min_width, p.min_height,
                p.max_width, p.max_height,
                p.margin,
                p.width_policy, p.height_policy, p.sizing_mode,
                p.aspect_ratio,
                p.visible,
            ], function () { return _this.invalidate_layout(); });
            this.on_change([
                p.background,
                p.css_classes,
            ], function () { return _this.invalidate_render(); });
        };
        LayoutDOMView.prototype.disconnect_signals = function () {
            if (this._parent_observer != null)
                clearTimeout(this._parent_observer);
            if (this._on_resize != null)
                window.removeEventListener("resize", this._on_resize);
            _super.prototype.disconnect_signals.call(this);
        };
        LayoutDOMView.prototype.css_classes = function () {
            return _super.prototype.css_classes.call(this).concat(this.model.css_classes);
        };
        Object.defineProperty(LayoutDOMView.prototype, "child_views", {
            get: function () {
                var _this = this;
                return this.child_models.map(function (child) { return _this._child_views.get(child); });
            },
            enumerable: false,
            configurable: true
        });
        LayoutDOMView.prototype.build_child_views = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, (0, build_views_1.build_views)(this._child_views, this.child_models, { parent: this })];
                        case 1:
                            _b.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        LayoutDOMView.prototype.render = function () {
            var _b, e_2, _c;
            _super.prototype.render.call(this);
            (0, dom_1.empty)(this.el); // XXX: this should be in super
            var background = this.model.background;
            this.el.style.backgroundColor = background != null ? (0, color_1.color2css)(background) : "";
            (_b = (0, dom_1.classes)(this.el).clear()).add.apply(_b, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.css_classes()), false));
            try {
                for (var _d = (0, tslib_1.__values)(this.child_views), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var child_view = _e.value;
                    this.el.appendChild(child_view.el);
                    child_view.render();
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_c = _d.return))
                        _c.call(_d);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        };
        LayoutDOMView.prototype.update_layout = function () {
            var e_3, _b;
            try {
                for (var _c = (0, tslib_1.__values)(this.child_views), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var child_view = _d.value;
                    child_view.update_layout();
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            this._update_layout();
        };
        LayoutDOMView.prototype.update_position = function () {
            var e_4, _b;
            this.el.style.display = this.model.visible ? "block" : "none";
            var margin = this.is_layout_root ? this.layout.sizing.margin : undefined;
            (0, dom_1.position)(this.el, this.layout.bbox, margin);
            try {
                for (var _c = (0, tslib_1.__values)(this.child_views), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var child_view = _d.value;
                    child_view.update_position();
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
        };
        LayoutDOMView.prototype.after_layout = function () {
            var e_5, _b;
            try {
                for (var _c = (0, tslib_1.__values)(this.child_views), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var child_view = _d.value;
                    child_view.after_layout();
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            this._has_finished = true;
        };
        LayoutDOMView.prototype.compute_viewport = function () {
            this._viewport = this._viewport_size();
        };
        LayoutDOMView.prototype.renderTo = function (element) {
            element.appendChild(this.el);
            this._offset_parent = this.el.offsetParent;
            this.compute_viewport();
            this.build();
            this.notify_finished();
        };
        LayoutDOMView.prototype.build = function () {
            if (!this.is_layout_root)
                throw new Error(this.toString() + " is not a root layout");
            this.render();
            this.update_layout();
            this.compute_layout();
            return this;
        };
        LayoutDOMView.prototype.rebuild = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, this.build_child_views()];
                        case 1:
                            _b.sent();
                            this.invalidate_render();
                            return [2 /*return*/];
                    }
                });
            });
        };
        LayoutDOMView.prototype.compute_layout = function () {
            var start = Date.now();
            this.layout.compute(this._viewport);
            this.update_position();
            this.after_layout();
            logging_1.logger.debug("layout computed in " + (Date.now() - start) + " ms");
        };
        LayoutDOMView.prototype.resize_layout = function () {
            this.root.compute_viewport();
            this.root.compute_layout();
        };
        LayoutDOMView.prototype.invalidate_layout = function () {
            this.root.update_layout();
            this.root.compute_layout();
        };
        LayoutDOMView.prototype.invalidate_render = function () {
            this.render();
            this.invalidate_layout();
        };
        LayoutDOMView.prototype.has_finished = function () {
            var e_6, _b;
            if (!_super.prototype.has_finished.call(this))
                return false;
            try {
                for (var _c = (0, tslib_1.__values)(this.child_views), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var child_view = _d.value;
                    if (!child_view.has_finished())
                        return false;
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            return true;
        };
        LayoutDOMView.prototype._width_policy = function () {
            return this.model.width != null ? "fixed" : "fit";
        };
        LayoutDOMView.prototype._height_policy = function () {
            return this.model.height != null ? "fixed" : "fit";
        };
        LayoutDOMView.prototype.box_sizing = function () {
            var _b;
            var _c = this.model, width_policy = _c.width_policy, height_policy = _c.height_policy, aspect_ratio = _c.aspect_ratio;
            if (width_policy == "auto")
                width_policy = this._width_policy();
            if (height_policy == "auto")
                height_policy = this._height_policy();
            var sizing_mode = this.model.sizing_mode;
            if (sizing_mode != null) {
                if (sizing_mode == "fixed")
                    width_policy = height_policy = "fixed";
                else if (sizing_mode == "stretch_both")
                    width_policy = height_policy = "max";
                else if (sizing_mode == "stretch_width")
                    width_policy = "max";
                else if (sizing_mode == "stretch_height")
                    height_policy = "max";
                else {
                    if (aspect_ratio == null)
                        aspect_ratio = "auto";
                    switch (sizing_mode) {
                        case "scale_width":
                            width_policy = "max";
                            height_policy = "min";
                            break;
                        case "scale_height":
                            width_policy = "min";
                            height_policy = "max";
                            break;
                        case "scale_both":
                            width_policy = "max";
                            height_policy = "max";
                            break;
                    }
                }
            }
            var sizing = { width_policy: width_policy, height_policy: height_policy };
            var _d = this.model, min_width = _d.min_width, min_height = _d.min_height;
            if (min_width != null)
                sizing.min_width = min_width;
            if (min_height != null)
                sizing.min_height = min_height;
            var _e = this.model, width = _e.width, height = _e.height;
            if (width != null)
                sizing.width = width;
            if (height != null)
                sizing.height = height;
            var _f = this.model, max_width = _f.max_width, max_height = _f.max_height;
            if (max_width != null)
                sizing.max_width = max_width;
            if (max_height != null)
                sizing.max_height = max_height;
            if (aspect_ratio == "auto" && width != null && height != null)
                sizing.aspect = width / height;
            else if ((0, types_1.isNumber)(aspect_ratio))
                sizing.aspect = aspect_ratio;
            var margin = this.model.margin;
            if (margin != null) {
                if ((0, types_1.isNumber)(margin))
                    sizing.margin = { top: margin, right: margin, bottom: margin, left: margin };
                else if (margin.length == 2) {
                    var _g = (0, tslib_1.__read)(margin, 2), vertical = _g[0], horizontal = _g[1];
                    sizing.margin = { top: vertical, right: horizontal, bottom: vertical, left: horizontal };
                }
                else {
                    var _h = (0, tslib_1.__read)(margin, 4), top = _h[0], right = _h[1], bottom = _h[2], left = _h[3];
                    sizing.margin = { top: top, right: right, bottom: bottom, left: left };
                }
            }
            sizing.visible = this.model.visible;
            var align = this.model.align;
            if ((0, types_1.isArray)(align))
                _b = (0, tslib_1.__read)(align, 2), sizing.halign = _b[0], sizing.valign = _b[1];
            else
                sizing.halign = sizing.valign = align;
            return sizing;
        };
        LayoutDOMView.prototype._viewport_size = function () {
            var _this = this;
            return (0, dom_1.undisplayed)(this.el, function () {
                var measuring = _this.el;
                while (measuring = measuring.parentElement) {
                    // .bk-root element doesn't bring any value
                    if (measuring.classList.contains(root_css_1.root))
                        continue;
                    // we reached <body> element, so use viewport size
                    if (measuring == document.body) {
                        var _b = (0, dom_1.extents)(document.body).margin, left_1 = _b.left, right_1 = _b.right, top_1 = _b.top, bottom_1 = _b.bottom;
                        var width_1 = Math.ceil(document.documentElement.clientWidth - left_1 - right_1);
                        var height_1 = Math.ceil(document.documentElement.clientHeight - top_1 - bottom_1);
                        return { width: width_1, height: height_1 };
                    }
                    // stop on first element with sensible dimensions
                    var _c = (0, dom_1.extents)(measuring).padding, left = _c.left, right = _c.right, top = _c.top, bottom = _c.bottom;
                    var _d = measuring.getBoundingClientRect(), width = _d.width, height = _d.height;
                    var inner_width = Math.ceil(width - left - right);
                    var inner_height = Math.ceil(height - top - bottom);
                    if (inner_width > 0 || inner_height > 0)
                        return {
                            width: inner_width > 0 ? inner_width : undefined,
                            height: inner_height > 0 ? inner_height : undefined,
                        };
                }
                // this element is detached from DOM
                return {};
            });
        };
        LayoutDOMView.prototype.export = function (type, hidpi) {
            var e_7, _b;
            if (hidpi === void 0) {
                hidpi = true;
            }
            var output_backend = type == "png" ? "canvas" : "svg";
            var composite = new canvas_1.CanvasLayer(output_backend, hidpi);
            var _c = this.layout.bbox, width = _c.width, height = _c.height;
            composite.resize(width, height);
            try {
                for (var _d = (0, tslib_1.__values)(this.child_views), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var view = _e.value;
                    var region = view.export(type, hidpi);
                    var _f = view.layout.bbox, x = _f.x, y = _f.y;
                    composite.ctx.drawImage(region.canvas, x, y);
                }
            }
            catch (e_7_1) {
                e_7 = { error: e_7_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_7)
                        throw e_7.error;
                }
            }
            return composite;
        };
        LayoutDOMView.prototype.serializable_state = function () {
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _super.prototype.serializable_state.call(this)), { bbox: this.layout.bbox.box, children: this.child_views.map(function (child) { return child.serializable_state(); }) });
        };
        return LayoutDOMView;
    }(dom_view_1.DOMView));
    exports.LayoutDOMView = LayoutDOMView;
    LayoutDOMView.__name__ = "LayoutDOMView";
    var LayoutDOM = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LayoutDOM, _super);
        function LayoutDOM(attrs) {
            return _super.call(this, attrs) || this;
        }
        return LayoutDOM;
    }(model_1.Model));
    exports.LayoutDOM = LayoutDOM;
    _a = LayoutDOM;
    LayoutDOM.__name__ = "LayoutDOM";
    (function () {
        _a.define(function (types) {
            var Boolean = types.Boolean, Number = types.Number, String = types.String, Auto = types.Auto, Color = types.Color, Array = types.Array, Tuple = types.Tuple, Or = types.Or, Null = types.Null, Nullable = types.Nullable;
            var Number2 = Tuple(Number, Number);
            var Number4 = Tuple(Number, Number, Number, Number);
            return {
                width: [Nullable(Number), null],
                height: [Nullable(Number), null],
                min_width: [Nullable(Number), null],
                min_height: [Nullable(Number), null],
                max_width: [Nullable(Number), null],
                max_height: [Nullable(Number), null],
                margin: [Nullable(Or(Number, Number2, Number4)), [0, 0, 0, 0]],
                width_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                height_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                aspect_ratio: [Or(Number, Auto, Null), null],
                sizing_mode: [Nullable(enums_1.SizingMode), null],
                visible: [Boolean, true],
                disabled: [Boolean, false],
                align: [Or(enums_1.Align, Tuple(enums_1.Align, enums_1.Align)), "start"],
                background: [Nullable(Color), null],
                css_classes: [Array(String), []],
            };
        });
    })();
},
/* models/layouts/column.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var box_1 = require(423) /* ./box */;
    var grid_1 = require(324) /* ../../core/layout/grid */;
    var ColumnView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColumnView, _super);
        function ColumnView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ColumnView.prototype._update_layout = function () {
            var items = this.child_views.map(function (child) { return child.layout; });
            this.layout = new grid_1.Column(items);
            this.layout.rows = this.model.rows;
            this.layout.spacing = [this.model.spacing, 0];
            this.layout.set_sizing(this.box_sizing());
        };
        return ColumnView;
    }(box_1.BoxView));
    exports.ColumnView = ColumnView;
    ColumnView.__name__ = "ColumnView";
    var Column = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Column, _super);
        function Column(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Column;
    }(box_1.Box));
    exports.Column = Column;
    _a = Column;
    Column.__name__ = "Column";
    (function () {
        _a.prototype.default_view = ColumnView;
        _a.define(function (_b) {
            var Any = _b.Any;
            return ({
                rows: [Any /*TODO*/, "auto"],
            });
        });
    })();
},
/* models/layouts/grid_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var layout_dom_1 = require(424) /* ./layout_dom */;
    var grid_1 = require(324) /* ../../core/layout/grid */;
    var GridBoxView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GridBoxView, _super);
        function GridBoxView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        GridBoxView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var _b = this.model.properties, children = _b.children, rows = _b.rows, cols = _b.cols, spacing = _b.spacing;
            this.on_change([children, rows, cols, spacing], function () { return _this.rebuild(); });
        };
        Object.defineProperty(GridBoxView.prototype, "child_models", {
            get: function () {
                return this.model.children.map(function (_b) {
                    var _c = (0, tslib_1.__read)(_b, 1), child = _c[0];
                    return child;
                });
            },
            enumerable: false,
            configurable: true
        });
        GridBoxView.prototype._update_layout = function () {
            var e_1, _b;
            this.layout = new grid_1.Grid();
            this.layout.rows = this.model.rows;
            this.layout.cols = this.model.cols;
            this.layout.spacing = this.model.spacing;
            try {
                for (var _c = (0, tslib_1.__values)(this.model.children), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 5), child = _e[0], row = _e[1], col = _e[2], row_span = _e[3], col_span = _e[4];
                    var child_view = this._child_views.get(child);
                    this.layout.items.push({ layout: child_view.layout, row: row, col: col, row_span: row_span, col_span: col_span });
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            this.layout.set_sizing(this.box_sizing());
        };
        return GridBoxView;
    }(layout_dom_1.LayoutDOMView));
    exports.GridBoxView = GridBoxView;
    GridBoxView.__name__ = "GridBoxView";
    var GridBox = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GridBox, _super);
        function GridBox(attrs) {
            return _super.call(this, attrs) || this;
        }
        return GridBox;
    }(layout_dom_1.LayoutDOM));
    exports.GridBox = GridBox;
    _a = GridBox;
    GridBox.__name__ = "GridBox";
    (function () {
        _a.prototype.default_view = GridBoxView;
        _a.define(function (_b) {
            var Any = _b.Any, Int = _b.Int, Number = _b.Number, Tuple = _b.Tuple, Array = _b.Array, Ref = _b.Ref, Or = _b.Or, Opt = _b.Opt;
            return ({
                children: [Array(Tuple(Ref(layout_dom_1.LayoutDOM), Int, Int, Opt(Int), Opt(Int))), []],
                rows: [Any /*TODO*/, "auto"],
                cols: [Any /*TODO*/, "auto"],
                spacing: [Or(Number, Tuple(Number, Number)), 0],
            });
        });
    })();
},
/* models/layouts/html_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var layout_dom_1 = require(424) /* ../layouts/layout_dom */;
    var layout_1 = require(322) /* ../../core/layout */;
    var HTMLBoxView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HTMLBoxView, _super);
        function HTMLBoxView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(HTMLBoxView.prototype, "child_models", {
            get: function () {
                return [];
            },
            enumerable: false,
            configurable: true
        });
        HTMLBoxView.prototype._update_layout = function () {
            this.layout = new layout_1.ContentBox(this.el);
            this.layout.set_sizing(this.box_sizing());
        };
        return HTMLBoxView;
    }(layout_dom_1.LayoutDOMView));
    exports.HTMLBoxView = HTMLBoxView;
    HTMLBoxView.__name__ = "HTMLBoxView";
    var HTMLBox = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HTMLBox, _super);
        function HTMLBox(attrs) {
            return _super.call(this, attrs) || this;
        }
        return HTMLBox;
    }(layout_dom_1.LayoutDOM));
    exports.HTMLBox = HTMLBox;
    HTMLBox.__name__ = "HTMLBox";
},
/* models/layouts/panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var layout_dom_1 = require(424) /* ./layout_dom */;
    var Panel = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Panel, _super);
        function Panel(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Panel;
    }(model_1.Model));
    exports.Panel = Panel;
    _a = Panel;
    Panel.__name__ = "Panel";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, String = _b.String, Ref = _b.Ref;
            return ({
                title: [String, ""],
                child: [Ref(layout_dom_1.LayoutDOM)],
                closable: [Boolean, false],
                disabled: [Boolean, false],
            });
        });
    })();
},
/* models/layouts/row.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var box_1 = require(423) /* ./box */;
    var grid_1 = require(324) /* ../../core/layout/grid */;
    var RowView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RowView, _super);
        function RowView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RowView.prototype._update_layout = function () {
            var items = this.child_views.map(function (child) { return child.layout; });
            this.layout = new grid_1.Row(items);
            this.layout.cols = this.model.cols;
            this.layout.spacing = [0, this.model.spacing];
            this.layout.set_sizing(this.box_sizing());
        };
        return RowView;
    }(box_1.BoxView));
    exports.RowView = RowView;
    RowView.__name__ = "RowView";
    var Row = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Row, _super);
        function Row(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Row;
    }(box_1.Box));
    exports.Row = Row;
    _a = Row;
    Row.__name__ = "Row";
    (function () {
        _a.prototype.default_view = RowView;
        _a.define(function (_b) {
            var Any = _b.Any;
            return ({
                cols: [Any /*TODO*/, "auto"],
            });
        });
    })();
},
/* models/layouts/spacer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var layout_dom_1 = require(424) /* ./layout_dom */;
    var layout_1 = require(322) /* ../../core/layout */;
    var SpacerView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SpacerView, _super);
        function SpacerView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(SpacerView.prototype, "child_models", {
            get: function () {
                return [];
            },
            enumerable: false,
            configurable: true
        });
        SpacerView.prototype._update_layout = function () {
            this.layout = new layout_1.LayoutItem();
            this.layout.set_sizing(this.box_sizing());
        };
        return SpacerView;
    }(layout_dom_1.LayoutDOMView));
    exports.SpacerView = SpacerView;
    SpacerView.__name__ = "SpacerView";
    var Spacer = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Spacer, _super);
        function Spacer(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Spacer;
    }(layout_dom_1.LayoutDOM));
    exports.Spacer = Spacer;
    _a = Spacer;
    Spacer.__name__ = "Spacer";
    (function () {
        _a.prototype.default_view = SpacerView;
    })();
},
/* models/layouts/tabs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var layout_1 = require(322) /* ../../core/layout */;
    var dom_1 = require(158) /* ../../core/dom */;
    var array_1 = require(126) /* ../../core/util/array */;
    var math_1 = require(117) /* ../../core/util/math */;
    var enums_1 = require(135) /* ../../core/enums */;
    var layout_dom_1 = require(424) /* ./layout_dom */;
    var panel_1 = require(428) /* ./panel */;
    var tabs_css_1 = (0, tslib_1.__importStar)(require(432) /* ../../styles/tabs.css */), tabs = tabs_css_1;
    var buttons_css_1 = (0, tslib_1.__importStar)(require(433) /* ../../styles/buttons.css */), buttons = buttons_css_1;
    var menus_css_1 = (0, tslib_1.__importStar)(require(344) /* ../../styles/menus.css */), menus = menus_css_1;
    var TabsView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TabsView, _super);
        function TabsView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._scroll_index = 0;
            return _this;
        }
        TabsView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.tabs.change, function () { return _this.rebuild(); });
            this.connect(this.model.properties.active.change, function () { return _this.on_active_change(); });
        };
        TabsView.prototype.styles = function () {
            return (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(_super.prototype.styles.call(this)), false), [buttons_css_1.default, menus_css_1.default, tabs_css_1.default], false);
        };
        Object.defineProperty(TabsView.prototype, "child_models", {
            get: function () {
                return this.model.tabs.map(function (tab) { return tab.child; });
            },
            enumerable: false,
            configurable: true
        });
        TabsView.prototype._update_layout = function () {
            var loc = this.model.tabs_location;
            var vertical = loc == "above" || loc == "below";
            // XXX: this is a hack, this should be handled by "fit" policy in grid layout
            var _b = this, scroll_el = _b.scroll_el, headers_el = _b.headers_el;
            this.header = new /** @class */ (function (_super) {
                (0, tslib_1.__extends)(class_1, _super);
                function class_1() {
                    return _super !== null && _super.apply(this, arguments) || this;
                }
                class_1.prototype._measure = function (viewport) {
                    var min_headers = 3;
                    var scroll = (0, dom_1.size)(scroll_el);
                    var headers = (0, dom_1.children)(headers_el).slice(0, min_headers).map(function (el) { return (0, dom_1.size)(el); });
                    var _b = _super.prototype._measure.call(this, viewport), width = _b.width, height = _b.height;
                    if (vertical) {
                        var min_width = scroll.width + (0, array_1.sum)(headers.map(function (size) { return size.width; }));
                        return { width: viewport.width != Infinity ? viewport.width : min_width, height: height };
                    }
                    else {
                        var min_height = scroll.height + (0, array_1.sum)(headers.map(function (size) { return size.height; }));
                        return { width: width, height: viewport.height != Infinity ? viewport.height : min_height };
                    }
                };
                return class_1;
            }(layout_1.ContentBox))(this.header_el);
            if (vertical)
                this.header.set_sizing({ width_policy: "fit", height_policy: "fixed" });
            else
                this.header.set_sizing({ width_policy: "fixed", height_policy: "fit" });
            var row = 1;
            var col = 1;
            switch (loc) {
                case "above":
                    row -= 1;
                    break;
                case "below":
                    row += 1;
                    break;
                case "left":
                    col -= 1;
                    break;
                case "right":
                    col += 1;
                    break;
            }
            var header = { layout: this.header, row: row, col: col };
            var panels = this.child_views.map(function (child_view) {
                return { layout: child_view.layout, row: 1, col: 1 };
            });
            this.layout = new layout_1.Grid((0, tslib_1.__spreadArray)([header], (0, tslib_1.__read)(panels), false));
            this.layout.set_sizing(this.box_sizing());
        };
        TabsView.prototype.update_position = function () {
            var e_1, _b;
            _super.prototype.update_position.call(this);
            this.header_el.style.position = "absolute"; // XXX: do it in position()
            (0, dom_1.position)(this.header_el, this.header.bbox);
            var loc = this.model.tabs_location;
            var vertical = loc == "above" || loc == "below";
            var scroll_el_size = (0, dom_1.size)(this.scroll_el);
            var headers_el_size = (0, dom_1.scroll_size)(this.headers_el);
            if (vertical) {
                var width = this.header.bbox.width;
                if (headers_el_size.width > width) {
                    this.wrapper_el.style.maxWidth = width - scroll_el_size.width + "px";
                    (0, dom_1.display)(this.scroll_el);
                    this.do_scroll(this.model.active);
                }
                else {
                    this.wrapper_el.style.maxWidth = "";
                    (0, dom_1.undisplay)(this.scroll_el);
                }
            }
            else {
                var height = this.header.bbox.height;
                if (headers_el_size.height > height) {
                    this.wrapper_el.style.maxHeight = height - scroll_el_size.height + "px";
                    (0, dom_1.display)(this.scroll_el);
                    this.do_scroll(this.model.active);
                }
                else {
                    this.wrapper_el.style.maxHeight = "";
                    (0, dom_1.undisplay)(this.scroll_el);
                }
            }
            var child_views = this.child_views;
            try {
                for (var child_views_1 = (0, tslib_1.__values)(child_views), child_views_1_1 = child_views_1.next(); !child_views_1_1.done; child_views_1_1 = child_views_1.next()) {
                    var child_view = child_views_1_1.value;
                    (0, dom_1.hide)(child_view.el);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (child_views_1_1 && !child_views_1_1.done && (_b = child_views_1.return))
                        _b.call(child_views_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            var tab = child_views[this.model.active];
            if (tab != null)
                (0, dom_1.show)(tab.el);
        };
        TabsView.prototype.render = function () {
            var _this = this;
            _super.prototype.render.call(this);
            var active = this.model.active;
            var headers = this.model.tabs.map(function (tab, i) {
                var el = (0, dom_1.div)({ class: [tabs.tab, i == active ? tabs.active : null] }, tab.title);
                el.addEventListener("click", function (event) {
                    if (_this.model.disabled)
                        return;
                    if (event.target == event.currentTarget)
                        _this.change_active(i);
                });
                if (tab.closable) {
                    var close_el = (0, dom_1.div)({ class: tabs.close });
                    close_el.addEventListener("click", function (event) {
                        if (event.target == event.currentTarget) {
                            _this.model.tabs = (0, array_1.remove_at)(_this.model.tabs, i);
                            var ntabs = _this.model.tabs.length;
                            if (_this.model.active > ntabs - 1)
                                _this.model.active = ntabs - 1;
                        }
                    });
                    el.appendChild(close_el);
                }
                if (_this.model.disabled || tab.disabled) {
                    el.classList.add(tabs.disabled);
                }
                return el;
            });
            this.headers_el = (0, dom_1.div)({ class: [tabs.headers] }, headers);
            this.wrapper_el = (0, dom_1.div)({ class: tabs.headers_wrapper }, this.headers_el);
            this.left_el = (0, dom_1.div)({ class: [buttons.btn, buttons.btn_default], disabled: "" }, (0, dom_1.div)({ class: [menus.caret, tabs.left] }));
            this.right_el = (0, dom_1.div)({ class: [buttons.btn, buttons.btn_default] }, (0, dom_1.div)({ class: [menus.caret, tabs.right] }));
            this.left_el.addEventListener("click", function () { return _this.do_scroll("left"); });
            this.right_el.addEventListener("click", function () { return _this.do_scroll("right"); });
            this.scroll_el = (0, dom_1.div)({ class: buttons.btn_group }, this.left_el, this.right_el);
            var loc = this.model.tabs_location;
            this.header_el = (0, dom_1.div)({ class: [tabs.tabs_header, tabs[loc]] }, this.scroll_el, this.wrapper_el);
            this.el.appendChild(this.header_el);
        };
        TabsView.prototype.do_scroll = function (target) {
            var ntabs = this.model.tabs.length;
            if (target == "left")
                this._scroll_index -= 1;
            else if (target == "right")
                this._scroll_index += 1;
            else
                this._scroll_index = target;
            this._scroll_index = (0, math_1.clamp)(this._scroll_index, 0, ntabs - 1);
            if (this._scroll_index == 0)
                this.left_el.setAttribute("disabled", "");
            else
                this.left_el.removeAttribute("disabled");
            if (this._scroll_index == ntabs - 1)
                this.right_el.setAttribute("disabled", "");
            else
                this.right_el.removeAttribute("disabled");
            var sizes = (0, dom_1.children)(this.headers_el)
                .slice(0, this._scroll_index)
                .map(function (el) { return el.getBoundingClientRect(); });
            var loc = this.model.tabs_location;
            var vertical = loc == "above" || loc == "below";
            if (vertical) {
                var left = -(0, array_1.sum)(sizes.map(function (size) { return size.width; }));
                this.headers_el.style.left = left + "px";
            }
            else {
                var top = -(0, array_1.sum)(sizes.map(function (size) { return size.height; }));
                this.headers_el.style.top = top + "px";
            }
        };
        TabsView.prototype.change_active = function (i) {
            if (i != this.model.active) {
                this.model.active = i;
            }
        };
        TabsView.prototype.on_active_change = function () {
            var e_2, _b, e_3, _c;
            var i = this.model.active;
            var headers = (0, dom_1.children)(this.headers_el);
            try {
                for (var headers_1 = (0, tslib_1.__values)(headers), headers_1_1 = headers_1.next(); !headers_1_1.done; headers_1_1 = headers_1.next()) {
                    var el = headers_1_1.value;
                    el.classList.remove(tabs.active);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (headers_1_1 && !headers_1_1.done && (_b = headers_1.return))
                        _b.call(headers_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            headers[i].classList.add(tabs.active);
            var child_views = this.child_views;
            try {
                for (var child_views_2 = (0, tslib_1.__values)(child_views), child_views_2_1 = child_views_2.next(); !child_views_2_1.done; child_views_2_1 = child_views_2.next()) {
                    var child_view = child_views_2_1.value;
                    (0, dom_1.hide)(child_view.el);
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (child_views_2_1 && !child_views_2_1.done && (_c = child_views_2.return))
                        _c.call(child_views_2);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            (0, dom_1.show)(child_views[i].el);
        };
        return TabsView;
    }(layout_dom_1.LayoutDOMView));
    exports.TabsView = TabsView;
    TabsView.__name__ = "TabsView";
    var Tabs = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Tabs, _super);
        function Tabs(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Tabs;
    }(layout_dom_1.LayoutDOM));
    exports.Tabs = Tabs;
    _a = Tabs;
    Tabs.__name__ = "Tabs";
    (function () {
        _a.prototype.default_view = TabsView;
        _a.define(function (_b) {
            var Int = _b.Int, Array = _b.Array, Ref = _b.Ref;
            return ({
                tabs: [Array(Ref(panel_1.Panel)), []],
                tabs_location: [enums_1.Location, "above"],
                active: [Int, 0],
            });
        });
    })();
},
/* styles/tabs.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tabs_header = "bk-tabs-header";
    exports.btn_group = "bk-btn-group";
    exports.btn = "bk-btn";
    exports.headers_wrapper = "bk-headers-wrapper";
    exports.above = "bk-above";
    exports.right = "bk-right";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.headers = "bk-headers";
    exports.tab = "bk-tab";
    exports.active = "bk-active";
    exports.close = "bk-close";
    exports.disabled = "bk-disabled";
    exports.default = ".bk-root .bk-tabs-header{display:flex;flex-wrap:nowrap;align-items:center;overflow:hidden;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;}.bk-root .bk-tabs-header .bk-btn-group{height:auto;margin-right:5px;}.bk-root .bk-tabs-header .bk-btn-group > .bk-btn{flex-grow:0;height:auto;padding:4px 4px;}.bk-root .bk-tabs-header .bk-headers-wrapper{flex-grow:1;overflow:hidden;color:#666666;}.bk-root .bk-tabs-header.bk-above .bk-headers-wrapper{border-bottom:1px solid #e6e6e6;}.bk-root .bk-tabs-header.bk-right .bk-headers-wrapper{border-left:1px solid #e6e6e6;}.bk-root .bk-tabs-header.bk-below .bk-headers-wrapper{border-top:1px solid #e6e6e6;}.bk-root .bk-tabs-header.bk-left .bk-headers-wrapper{border-right:1px solid #e6e6e6;}.bk-root .bk-tabs-header.bk-above,.bk-root .bk-tabs-header.bk-below{flex-direction:row;}.bk-root .bk-tabs-header.bk-above .bk-headers,.bk-root .bk-tabs-header.bk-below .bk-headers{flex-direction:row;}.bk-root .bk-tabs-header.bk-left,.bk-root .bk-tabs-header.bk-right{flex-direction:column;}.bk-root .bk-tabs-header.bk-left .bk-headers,.bk-root .bk-tabs-header.bk-right .bk-headers{flex-direction:column;}.bk-root .bk-tabs-header .bk-headers{position:relative;display:flex;flex-wrap:nowrap;align-items:center;}.bk-root .bk-tabs-header .bk-tab{padding:4px 8px;border:solid transparent;white-space:nowrap;cursor:pointer;}.bk-root .bk-tabs-header .bk-tab:hover{background-color:#f2f2f2;}.bk-root .bk-tabs-header .bk-tab.bk-active{color:#4d4d4d;background-color:white;border-color:#e6e6e6;}.bk-root .bk-tabs-header .bk-tab .bk-close{margin-left:10px;}.bk-root .bk-tabs-header .bk-tab.bk-disabled{cursor:not-allowed;pointer-events:none;opacity:0.65;}.bk-root .bk-tabs-header.bk-above .bk-tab{border-width:3px 1px 0px 1px;border-radius:4px 4px 0 0;}.bk-root .bk-tabs-header.bk-right .bk-tab{border-width:1px 3px 1px 0px;border-radius:0 4px 4px 0;}.bk-root .bk-tabs-header.bk-below .bk-tab{border-width:0px 1px 3px 1px;border-radius:0 0 4px 4px;}.bk-root .bk-tabs-header.bk-left .bk-tab{border-width:1px 0px 1px 3px;border-radius:4px 0 0 4px;}.bk-root .bk-close{display:inline-block;width:10px;height:10px;vertical-align:middle;background-image:url('data:image/svg+xml;utf8,      <svg viewPort=\"0 0 10 10\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">        <line x1=\"1\" y1=\"9\" x2=\"9\" y2=\"1\" stroke=\"gray\" stroke-width=\"2\"/>        <line x1=\"1\" y1=\"1\" x2=\"9\" y2=\"9\" stroke=\"gray\" stroke-width=\"2\"/>      </svg>');}.bk-root .bk-close:hover{background-image:url('data:image/svg+xml;utf8,      <svg viewPort=\"0 0 10 10\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">        <line x1=\"1\" y1=\"9\" x2=\"9\" y2=\"1\" stroke=\"red\" stroke-width=\"2\"/>        <line x1=\"1\" y1=\"1\" x2=\"9\" y2=\"9\" stroke=\"red\" stroke-width=\"2\"/>      </svg>');}";
},
/* styles/buttons.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.btn = "bk-btn";
    exports.active = "bk-active";
    exports.btn_default = "bk-btn-default";
    exports.btn_primary = "bk-btn-primary";
    exports.btn_success = "bk-btn-success";
    exports.btn_warning = "bk-btn-warning";
    exports.btn_danger = "bk-btn-danger";
    exports.btn_light = "bk-btn-light";
    exports.btn_group = "bk-btn-group";
    exports.vertical = "bk-vertical";
    exports.horizontal = "bk-horizontal";
    exports.dropdown_toggle = "bk-dropdown-toggle";
    exports.default = ".bk-root .bk-btn{height:100%;display:inline-block;text-align:center;vertical-align:middle;white-space:nowrap;cursor:pointer;padding:6px 12px;font-size:12px;border:1px solid transparent;border-radius:4px;outline:0;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;}.bk-root .bk-btn:hover,.bk-root .bk-btn:focus{text-decoration:none;}.bk-root .bk-btn:active,.bk-root .bk-btn.bk-active{background-image:none;box-shadow:inset 0 3px 5px rgba(0, 0, 0, 0.125);}.bk-root .bk-btn[disabled]{cursor:not-allowed;pointer-events:none;opacity:0.65;box-shadow:none;}.bk-root .bk-btn-default{color:#333;background-color:#fff;border-color:#ccc;}.bk-root .bk-btn-default:hover{background-color:#f5f5f5;border-color:#b8b8b8;}.bk-root .bk-btn-default.bk-active{background-color:#ebebeb;border-color:#adadad;}.bk-root .bk-btn-default[disabled],.bk-root .bk-btn-default[disabled]:hover,.bk-root .bk-btn-default[disabled]:focus,.bk-root .bk-btn-default[disabled]:active,.bk-root .bk-btn-default[disabled].bk-active{background-color:#e6e6e6;border-color:#ccc;}.bk-root .bk-btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd;}.bk-root .bk-btn-primary:hover{background-color:#3681c1;border-color:#2c699e;}.bk-root .bk-btn-primary.bk-active{background-color:#3276b1;border-color:#285e8e;}.bk-root .bk-btn-primary[disabled],.bk-root .bk-btn-primary[disabled]:hover,.bk-root .bk-btn-primary[disabled]:focus,.bk-root .bk-btn-primary[disabled]:active,.bk-root .bk-btn-primary[disabled].bk-active{background-color:#506f89;border-color:#357ebd;}.bk-root .bk-btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c;}.bk-root .bk-btn-success:hover{background-color:#4eb24e;border-color:#409240;}.bk-root .bk-btn-success.bk-active{background-color:#47a447;border-color:#398439;}.bk-root .bk-btn-success[disabled],.bk-root .bk-btn-success[disabled]:hover,.bk-root .bk-btn-success[disabled]:focus,.bk-root .bk-btn-success[disabled]:active,.bk-root .bk-btn-success[disabled].bk-active{background-color:#667b66;border-color:#4cae4c;}.bk-root .bk-btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236;}.bk-root .bk-btn-warning:hover{background-color:#eea43b;border-color:#e89014;}.bk-root .bk-btn-warning.bk-active{background-color:#ed9c28;border-color:#d58512;}.bk-root .bk-btn-warning[disabled],.bk-root .bk-btn-warning[disabled]:hover,.bk-root .bk-btn-warning[disabled]:focus,.bk-root .bk-btn-warning[disabled]:active,.bk-root .bk-btn-warning[disabled].bk-active{background-color:#c89143;border-color:#eea236;}.bk-root .bk-btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a;}.bk-root .bk-btn-danger:hover{background-color:#d5433e;border-color:#bd2d29;}.bk-root .bk-btn-danger.bk-active{background-color:#d2322d;border-color:#ac2925;}.bk-root .bk-btn-danger[disabled],.bk-root .bk-btn-danger[disabled]:hover,.bk-root .bk-btn-danger[disabled]:focus,.bk-root .bk-btn-danger[disabled]:active,.bk-root .bk-btn-danger[disabled].bk-active{background-color:#a55350;border-color:#d43f3a;}.bk-root .bk-btn-light{color:#333;background-color:#fff;border-color:#ccc;border-color:transparent;}.bk-root .bk-btn-light:hover{background-color:#f5f5f5;border-color:#b8b8b8;}.bk-root .bk-btn-light.bk-active{background-color:#ebebeb;border-color:#adadad;}.bk-root .bk-btn-light[disabled],.bk-root .bk-btn-light[disabled]:hover,.bk-root .bk-btn-light[disabled]:focus,.bk-root .bk-btn-light[disabled]:active,.bk-root .bk-btn-light[disabled].bk-active{background-color:#e6e6e6;border-color:#ccc;}.bk-root .bk-btn-group{height:100%;display:flex;flex-wrap:nowrap;align-items:center;}.bk-root .bk-btn-group:not(.bk-vertical),.bk-root .bk-btn-group.bk-horizontal{flex-direction:row;}.bk-root .bk-btn-group.bk-vertical{flex-direction:column;}.bk-root .bk-btn-group > .bk-btn{flex-grow:1;}.bk-root .bk-btn-group:not(.bk-vertical) > .bk-btn + .bk-btn{margin-left:-1px;}.bk-root .bk-btn-group.bk-vertical > .bk-btn + .bk-btn{margin-top:-1px;}.bk-root .bk-btn-group:not(.bk-vertical) > .bk-btn:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0;}.bk-root .bk-btn-group.bk-vertical > .bk-btn:first-child:not(:last-child){border-bottom-left-radius:0;border-bottom-right-radius:0;}.bk-root .bk-btn-group:not(.bk-vertical) > .bk-btn:not(:first-child):last-child{border-bottom-left-radius:0;border-top-left-radius:0;}.bk-root .bk-btn-group.bk-vertical > .bk-btn:not(:first-child):last-child{border-top-left-radius:0;border-top-right-radius:0;}.bk-root .bk-btn-group > .bk-btn:not(:first-child):not(:last-child){border-radius:0;}.bk-root .bk-btn-group.bk-vertical > .bk-btn{width:100%;}.bk-root .bk-btn-group .bk-dropdown-toggle{flex:0 0 0;padding:6px 6px;}";
},
/* models/layouts/widget_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var column_1 = require(425) /* ./column */;
    var WidgetBoxView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WidgetBoxView, _super);
        function WidgetBoxView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return WidgetBoxView;
    }(column_1.ColumnView));
    exports.WidgetBoxView = WidgetBoxView;
    WidgetBoxView.__name__ = "WidgetBoxView";
    var WidgetBox = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WidgetBox, _super);
        function WidgetBox(attrs) {
            return _super.call(this, attrs) || this;
        }
        return WidgetBox;
    }(column_1.Column));
    exports.WidgetBox = WidgetBox;
    _a = WidgetBox;
    WidgetBox.__name__ = "WidgetBox";
    (function () {
        _a.prototype.default_view = WidgetBoxView;
    })();
},
/* models/text/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var math_text_1 = require(250) /* ./math_text */;
    __esExport("MathText", math_text_1.MathText);
    __esExport("Ascii", math_text_1.Ascii);
    __esExport("MathML", math_text_1.MathML);
    __esExport("TeX", math_text_1.TeX);
    var plain_text_1 = require(254) /* ./plain_text */;
    __esExport("PlainText", plain_text_1.PlainText);
},
/* models/transforms/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_transform_1 = require(437) /* ./customjs_transform */;
    __esExport("CustomJSTransform", customjs_transform_1.CustomJSTransform);
    var dodge_1 = require(438) /* ./dodge */;
    __esExport("Dodge", dodge_1.Dodge);
    var interpolator_1 = require(440) /* ./interpolator */;
    __esExport("Interpolator", interpolator_1.Interpolator);
    var jitter_1 = require(441) /* ./jitter */;
    __esExport("Jitter", jitter_1.Jitter);
    var linear_interpolator_1 = require(442) /* ./linear_interpolator */;
    __esExport("LinearInterpolator", linear_interpolator_1.LinearInterpolator);
    var step_interpolator_1 = require(443) /* ./step_interpolator */;
    __esExport("StepInterpolator", step_interpolator_1.StepInterpolator);
    var transform_1 = require(171) /* ./transform */;
    __esExport("Transform", transform_1.Transform);
},
/* models/transforms/customjs_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var transform_1 = require(171) /* ./transform */;
    var object_1 = require(128) /* ../../core/util/object */;
    var string_1 = require(149) /* ../../core/util/string */;
    var CustomJSTransform = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomJSTransform, _super);
        function CustomJSTransform(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CustomJSTransform.prototype, "names", {
            get: function () {
                return (0, object_1.keys)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomJSTransform.prototype, "values", {
            get: function () {
                return (0, object_1.values)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        CustomJSTransform.prototype._make_transform = function (name, func) {
            return new (Function.bind.apply(Function, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([void 0], (0, tslib_1.__read)(this.names), false), [name, (0, string_1.use_strict)(func)], false)))();
        };
        Object.defineProperty(CustomJSTransform.prototype, "scalar_transform", {
            get: function () {
                return this._make_transform("x", this.func);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CustomJSTransform.prototype, "vector_transform", {
            get: function () {
                return this._make_transform("xs", this.v_func);
            },
            enumerable: false,
            configurable: true
        });
        CustomJSTransform.prototype.compute = function (x) {
            return this.scalar_transform.apply(this, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.values), false), [x], false));
        };
        CustomJSTransform.prototype.v_compute = function (xs) {
            return this.vector_transform.apply(this, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.values), false), [xs], false));
        };
        return CustomJSTransform;
    }(transform_1.Transform));
    exports.CustomJSTransform = CustomJSTransform;
    _a = CustomJSTransform;
    CustomJSTransform.__name__ = "CustomJSTransform";
    (function () {
        _a.define(function (_b) {
            var Unknown = _b.Unknown, String = _b.String, Dict = _b.Dict;
            return ({
                args: [Dict(Unknown), {}],
                func: [String, ""],
                v_func: [String, ""],
            });
        });
    })();
},
/* models/transforms/dodge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var range_transform_1 = require(439) /* ./range_transform */;
    var Dodge = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Dodge, _super);
        function Dodge(attrs) {
            return _super.call(this, attrs) || this;
        }
        Dodge.prototype._compute = function (x) {
            return x + this.value;
        };
        return Dodge;
    }(range_transform_1.RangeTransform));
    exports.Dodge = Dodge;
    _a = Dodge;
    Dodge.__name__ = "Dodge";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number;
            return ({
                value: [Number, 0],
            });
        });
    })();
},
/* models/transforms/range_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var transform_1 = require(171) /* ./transform */;
    var range_1 = require(172) /* ../ranges/range */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var types_1 = require(139) /* ../../core/types */;
    var types_2 = require(125) /* ../../core/util/types */;
    var assert_1 = require(127) /* ../../core/util/assert */;
    var RangeTransform = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RangeTransform, _super);
        function RangeTransform(attrs) {
            return _super.call(this, attrs) || this;
        }
        RangeTransform.prototype.v_compute = function (xs0) {
            var xs;
            if (this.range instanceof factor_range_1.FactorRange)
                xs = this.range.v_synthetic(xs0);
            else if ((0, types_2.isArrayableOf)(xs0, types_2.isNumber))
                xs = xs0;
            else
                (0, assert_1.unreachable)();
            var result = new ((0, types_1.infer_type)(xs))(xs.length);
            for (var i = 0; i < xs.length; i++) {
                var x = xs[i];
                result[i] = this._compute(x);
            }
            return result;
        };
        RangeTransform.prototype.compute = function (x) {
            if (this.range instanceof factor_range_1.FactorRange)
                return this._compute(this.range.synthetic(x));
            else if ((0, types_2.isNumber)(x))
                return this._compute(x);
            else
                (0, assert_1.unreachable)();
        };
        return RangeTransform;
    }(transform_1.Transform));
    exports.RangeTransform = RangeTransform;
    _a = RangeTransform;
    RangeTransform.__name__ = "RangeTransform";
    (function () {
        _a.define(function (_b) {
            var Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                range: [Nullable(Ref(range_1.Range)), null],
            });
        });
    })();
},
/* models/transforms/interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var transform_1 = require(171) /* ./transform */;
    var columnar_data_source_1 = require(185) /* ../sources/columnar_data_source */;
    var types_1 = require(139) /* ../../core/types */;
    var array_1 = require(126) /* ../../core/util/array */;
    var types_2 = require(125) /* ../../core/util/types */;
    var Interpolator = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Interpolator, _super);
        function Interpolator(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this._sorted_dirty = true;
            return _this;
        }
        Interpolator.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.change, function () { return _this._sorted_dirty = true; });
        };
        Interpolator.prototype.v_compute = function (xs) {
            var ArrayType = (0, types_1.infer_type)(xs);
            var result = new ArrayType(xs.length);
            for (var i = 0; i < xs.length; i++) {
                var x = xs[i];
                result[i] = this.compute(x);
            }
            return result;
        };
        Interpolator.prototype.sort = function (descending) {
            if (descending === void 0) {
                descending = false;
            }
            if (!this._sorted_dirty)
                return;
            var tsx;
            var tsy;
            if ((0, types_2.isString)(this.x) && (0, types_2.isString)(this.y) && this.data != null) {
                var column_names = this.data.columns();
                if (!(0, array_1.includes)(column_names, this.x))
                    throw new Error("The x parameter does not correspond to a valid column name defined in the data parameter");
                if (!(0, array_1.includes)(column_names, this.y))
                    throw new Error("The y parameter does not correspond to a valid column name defined in the data parameter");
                tsx = this.data.get_column(this.x);
                tsy = this.data.get_column(this.y);
            }
            else if ((0, types_2.isArray)(this.x) && (0, types_2.isArray)(this.y)) {
                tsx = this.x;
                tsy = this.y;
            }
            else {
                throw new Error("parameters 'x' and 'y' must be both either string fields or arrays");
            }
            if (tsx.length !== tsy.length)
                throw new Error("The length for x and y do not match");
            if (tsx.length < 2)
                throw new Error("x and y must have at least two elements to support interpolation");
            var n = tsx.length;
            var index = new Uint32Array(n);
            for (var i = 0; i < n; i++) {
                index[i] = i;
            }
            var sign = descending ? -1 : 1;
            index.sort(function (i, j) { return sign * (tsx[i] - tsx[j]); });
            this._x_sorted = new ((0, types_1.infer_type)(tsx))(n);
            this._y_sorted = new ((0, types_1.infer_type)(tsy))(n);
            for (var i = 0; i < n; i++) {
                this._x_sorted[i] = tsx[index[i]];
                this._y_sorted[i] = tsy[index[i]];
            }
            this._sorted_dirty = false;
        };
        return Interpolator;
    }(transform_1.Transform));
    exports.Interpolator = Interpolator;
    _a = Interpolator;
    Interpolator.__name__ = "Interpolator";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Number = _b.Number, String = _b.String, Ref = _b.Ref, Array = _b.Array, Or = _b.Or, Nullable = _b.Nullable;
            return ({
                x: [Or(String, Array(Number))],
                y: [Or(String, Array(Number))],
                data: [Nullable(Ref(columnar_data_source_1.ColumnarDataSource)), null],
                clip: [Boolean, true],
            });
        });
    })();
},
/* models/transforms/jitter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var range_transform_1 = require(439) /* ./range_transform */;
    var factor_range_1 = require(182) /* ../ranges/factor_range */;
    var enums_1 = require(135) /* ../../core/enums */;
    var types_1 = require(125) /* ../../core/util/types */;
    var arrayable_1 = require(116) /* ../../core/util/arrayable */;
    var bokeh_math = (0, tslib_1.__importStar)(require(117) /* ../../core/util/math */);
    var assert_1 = require(127) /* ../../core/util/assert */;
    var Jitter = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Jitter, _super);
        function Jitter(attrs) {
            return _super.call(this, attrs) || this;
        }
        Jitter.prototype.v_compute = function (xs0) {
            var _this = this;
            var _b;
            var xs;
            if (this.range instanceof factor_range_1.FactorRange)
                xs = this.range.v_synthetic(xs0);
            else if ((0, types_1.isArrayableOf)(xs0, types_1.isNumber))
                xs = xs0;
            else
                (0, assert_1.unreachable)();
            var xs_length = xs.length;
            if (((_b = this.previous_offsets) === null || _b === void 0 ? void 0 : _b.length) != xs_length) {
                this.previous_offsets = new Array(xs_length);
                this.previous_offsets = (0, arrayable_1.map)(this.previous_offsets, function () { return _this._compute(); });
            }
            var offsets = this.previous_offsets;
            return (0, arrayable_1.map)(xs, function (xs, i) { return offsets[i] + xs; });
        };
        Jitter.prototype._compute = function () {
            switch (this.distribution) {
                case "uniform":
                    return this.mean + (bokeh_math.random() - 0.5) * this.width;
                case "normal":
                    return bokeh_math.rnorm(this.mean, this.width);
            }
        };
        return Jitter;
    }(range_transform_1.RangeTransform));
    exports.Jitter = Jitter;
    _a = Jitter;
    Jitter.__name__ = "Jitter";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number;
            return ({
                mean: [Number, 0],
                width: [Number, 1],
                distribution: [enums_1.Distribution, "uniform"],
            });
        });
    })();
},
/* models/transforms/linear_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var array_1 = require(126) /* ../../core/util/array */;
    var interpolator_1 = require(440) /* ./interpolator */;
    var LinearInterpolator = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LinearInterpolator, _super);
        function LinearInterpolator(attrs) {
            return _super.call(this, attrs) || this;
        }
        LinearInterpolator.prototype.compute = function (x) {
            this.sort(false);
            if (this.clip) {
                if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length - 1])
                    return NaN;
            }
            else {
                if (x < this._x_sorted[0])
                    return this._y_sorted[0];
                if (x > this._x_sorted[this._x_sorted.length - 1])
                    return this._y_sorted[this._y_sorted.length - 1];
            }
            if (x == this._x_sorted[0])
                return this._y_sorted[0];
            var ind = (0, array_1.find_last_index)(this._x_sorted, function (num) { return num < x; });
            var x1 = this._x_sorted[ind];
            var x2 = this._x_sorted[ind + 1];
            var y1 = this._y_sorted[ind];
            var y2 = this._y_sorted[ind + 1];
            return y1 + (((x - x1) / (x2 - x1)) * (y2 - y1));
        };
        return LinearInterpolator;
    }(interpolator_1.Interpolator));
    exports.LinearInterpolator = LinearInterpolator;
    LinearInterpolator.__name__ = "LinearInterpolator";
},
/* models/transforms/step_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var interpolator_1 = require(440) /* ./interpolator */;
    var enums_1 = require(135) /* ../../core/enums */;
    var array_1 = require(126) /* ../../core/util/array */;
    var StepInterpolator = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(StepInterpolator, _super);
        function StepInterpolator(attrs) {
            return _super.call(this, attrs) || this;
        }
        StepInterpolator.prototype.compute = function (x) {
            this.sort(false);
            if (this.clip) {
                if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length - 1])
                    return NaN;
            }
            else {
                if (x < this._x_sorted[0])
                    return this._y_sorted[0];
                if (x > this._x_sorted[this._x_sorted.length - 1])
                    return this._y_sorted[this._y_sorted.length - 1];
            }
            var ind;
            switch (this.mode) {
                case "after": {
                    ind = (0, array_1.find_last_index)(this._x_sorted, function (num) { return x >= num; });
                    break;
                }
                case "before": {
                    ind = (0, array_1.find_index)(this._x_sorted, function (num) { return x <= num; });
                    break;
                }
                case "center": {
                    var diffs = (0, array_1.map)(this._x_sorted, function (tx) { return Math.abs(tx - x); });
                    var mdiff_1 = (0, array_1.min)(diffs);
                    ind = (0, array_1.find_index)(diffs, function (num) { return mdiff_1 === num; });
                    break;
                }
                default:
                    throw new Error("unknown mode: " + this.mode);
            }
            return ind != -1 ? this._y_sorted[ind] : NaN;
        };
        return StepInterpolator;
    }(interpolator_1.Interpolator));
    exports.StepInterpolator = StepInterpolator;
    _a = StepInterpolator;
    StepInterpolator.__name__ = "StepInterpolator";
    (function () {
        _a.define(function () {
            return ({
                mode: [enums_1.StepMode, "after"],
            });
        });
    })();
},
/* models/plots/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var gmap_plot_1 = require(445) /* ./gmap_plot */;
    __esExport("MapOptions", gmap_plot_1.MapOptions);
    var gmap_plot_2 = require(445) /* ./gmap_plot */;
    __esExport("GMapOptions", gmap_plot_2.GMapOptions);
    var gmap_plot_3 = require(445) /* ./gmap_plot */;
    __esExport("GMapPlot", gmap_plot_3.GMapPlot);
    var plot_1 = require(446) /* ./plot */;
    __esExport("Plot", plot_1.Plot);
},
/* models/plots/gmap_plot.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b, _c;
    var plot_1 = require(446) /* ./plot */;
    var model_1 = require(168) /* ../../model */;
    var range1d_1 = require(173) /* ../ranges/range1d */;
    var gmap_plot_canvas_1 = require(451) /* ./gmap_plot_canvas */;
    __esExport("GMapPlotView", gmap_plot_canvas_1.GMapPlotView);
    var MapOptions = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MapOptions, _super);
        function MapOptions(attrs) {
            return _super.call(this, attrs) || this;
        }
        return MapOptions;
    }(model_1.Model));
    exports.MapOptions = MapOptions;
    _a = MapOptions;
    MapOptions.__name__ = "MapOptions";
    (function () {
        _a.define(function (_d) {
            var Int = _d.Int, Number = _d.Number;
            return ({
                lat: [Number],
                lng: [Number],
                zoom: [Int, 12],
            });
        });
    })();
    var GMapOptions = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GMapOptions, _super);
        function GMapOptions(attrs) {
            return _super.call(this, attrs) || this;
        }
        return GMapOptions;
    }(MapOptions));
    exports.GMapOptions = GMapOptions;
    _b = GMapOptions;
    GMapOptions.__name__ = "GMapOptions";
    (function () {
        _b.define(function (_d) {
            var Boolean = _d.Boolean, Int = _d.Int, String = _d.String;
            return ({
                map_type: [String, "roadmap"],
                scale_control: [Boolean, false],
                styles: [String],
                tilt: [Int, 45],
            });
        });
    })();
    var GMapPlot = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GMapPlot, _super);
        function GMapPlot(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.use_map = true;
            return _this;
        }
        return GMapPlot;
    }(plot_1.Plot));
    exports.GMapPlot = GMapPlot;
    _c = GMapPlot;
    GMapPlot.__name__ = "GMapPlot";
    (function () {
        _c.prototype.default_view = gmap_plot_canvas_1.GMapPlotView;
        // This seems to be necessary so that everything can initialize.
        // Feels very clumsy, but I'm not sure how the properties system wants
        // to handle something like this situation.
        _c.define(function (_d) {
            var String = _d.String, Ref = _d.Ref;
            return ({
                map_options: [Ref(GMapOptions)],
                api_key: [String],
                api_version: [String, "3.43"],
            });
        });
        _c.override({
            x_range: function () { return new range1d_1.Range1d(); },
            y_range: function () { return new range1d_1.Range1d(); },
        });
    })();
},
/* models/plots/plot.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var mixins = (0, tslib_1.__importStar)(require(163) /* ../../core/property_mixins */);
    var p = (0, tslib_1.__importStar)(require(133) /* ../../core/properties */);
    var signaling_1 = require(130) /* ../../core/signaling */;
    var enums_1 = require(135) /* ../../core/enums */;
    var array_1 = require(126) /* ../../core/util/array */;
    var object_1 = require(128) /* ../../core/util/object */;
    var types_1 = require(125) /* ../../core/util/types */;
    var layout_dom_1 = require(424) /* ../layouts/layout_dom */;
    var axis_1 = require(243) /* ../axes/axis */;
    var grid_1 = require(421) /* ../grids/grid */;
    var annotation_1 = require(155) /* ../annotations/annotation */;
    var title_1 = require(233) /* ../annotations/title */;
    var linear_scale_1 = require(174) /* ../scales/linear_scale */;
    var toolbar_1 = require(336) /* ../tools/toolbar */;
    var range_1 = require(172) /* ../ranges/range */;
    var scale_1 = require(170) /* ../scales/scale */;
    var column_data_source_1 = require(190) /* ../sources/column_data_source */;
    var renderer_1 = require(156) /* ../renderers/renderer */;
    var data_renderer_1 = require(291) /* ../renderers/data_renderer */;
    var glyph_renderer_1 = require(290) /* ../renderers/glyph_renderer */;
    var data_range1d_1 = require(178) /* ../ranges/data_range1d */;
    var plot_canvas_1 = require(447) /* ./plot_canvas */;
    __esExport("PlotView", plot_canvas_1.PlotView);
    var Plot = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Plot, _super);
        function Plot(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.use_map = false;
            return _this;
        }
        Plot.prototype._doc_attached = function () {
            _super.prototype._doc_attached.call(this);
            this._push_changes([
                [this.properties.inner_height, null, this.inner_height],
                [this.properties.inner_width, null, this.inner_width],
            ]);
        };
        Plot.prototype.initialize = function () {
            var e_1, _b, e_2, _c;
            _super.prototype.initialize.call(this);
            this.reset = new signaling_1.Signal0(this, "reset");
            try {
                for (var _d = (0, tslib_1.__values)((0, object_1.values)(this.extra_x_ranges).concat(this.x_range)), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var xr = _e.value;
                    var plots = xr.plots;
                    if ((0, types_1.isArray)(plots)) {
                        plots = plots.concat(this);
                        xr.setv({ plots: plots }, { silent: true });
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            try {
                for (var _f = (0, tslib_1.__values)((0, object_1.values)(this.extra_y_ranges).concat(this.y_range)), _g = _f.next(); !_g.done; _g = _f.next()) {
                    var yr = _g.value;
                    var plots = yr.plots;
                    if ((0, types_1.isArray)(plots)) {
                        plots = plots.concat(this);
                        yr.setv({ plots: plots }, { silent: true });
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_g && !_g.done && (_c = _f.return))
                        _c.call(_f);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        };
        Plot.prototype.add_layout = function (renderer, side) {
            var _b;
            if (side === void 0) {
                side = "center";
            }
            var renderers = this.properties[side].get_value();
            this.setv((_b = {}, _b[side] = (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(renderers), false), [renderer], false), _b));
        };
        Plot.prototype.remove_layout = function (renderer) {
            var del = function (items) {
                (0, array_1.remove_by)(items, function (item) { return item == renderer; });
            };
            del(this.left);
            del(this.right);
            del(this.above);
            del(this.below);
            del(this.center);
        };
        Object.defineProperty(Plot.prototype, "data_renderers", {
            get: function () {
                return this.renderers.filter(function (r) { return r instanceof data_renderer_1.DataRenderer; });
            },
            enumerable: false,
            configurable: true
        });
        Plot.prototype.add_renderers = function () {
            var renderers = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                renderers[_i] = arguments[_i];
            }
            this.renderers = this.renderers.concat(renderers);
        };
        Plot.prototype.add_glyph = function (glyph, source, attrs) {
            if (source === void 0) {
                source = new column_data_source_1.ColumnDataSource();
            }
            if (attrs === void 0) {
                attrs = {};
            }
            var renderer = new glyph_renderer_1.GlyphRenderer((0, tslib_1.__assign)((0, tslib_1.__assign)({}, attrs), { data_source: source, glyph: glyph }));
            this.add_renderers(renderer);
            return renderer;
        };
        Plot.prototype.add_tools = function () {
            var tools = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                tools[_i] = arguments[_i];
            }
            this.toolbar.tools = this.toolbar.tools.concat(tools);
        };
        Object.defineProperty(Plot.prototype, "panels", {
            get: function () {
                return (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.side_panels), false), (0, tslib_1.__read)(this.center), false);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Plot.prototype, "side_panels", {
            get: function () {
                var _b = this, above = _b.above, below = _b.below, left = _b.left, right = _b.right;
                return (0, array_1.concat)([above, below, left, right]);
            },
            enumerable: false,
            configurable: true
        });
        return Plot;
    }(layout_dom_1.LayoutDOM));
    exports.Plot = Plot;
    _a = Plot;
    Plot.__name__ = "Plot";
    (function () {
        _a.prototype.default_view = plot_canvas_1.PlotView;
        _a.mixins([
            ["outline_", mixins.Line],
            ["background_", mixins.Fill],
            ["border_", mixins.Fill],
        ]);
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Number = _b.Number, String = _b.String, Array = _b.Array, Dict = _b.Dict, Or = _b.Or, Ref = _b.Ref, Null = _b.Null, Nullable = _b.Nullable;
            return ({
                toolbar: [Ref(toolbar_1.Toolbar), function () { return new toolbar_1.Toolbar(); }],
                toolbar_location: [Nullable(enums_1.Location), "right"],
                toolbar_sticky: [Boolean, true],
                plot_width: [p.Alias("width")],
                plot_height: [p.Alias("height")],
                frame_width: [Nullable(Number), null],
                frame_height: [Nullable(Number), null],
                // revise this when https://github.com/microsoft/TypeScript/pull/42425 is merged
                title: [Or(Ref(title_1.Title), String, Null), "", {
                        convert: function (title) { return (0, types_1.isString)(title) ? new title_1.Title({ text: title }) : title; },
                    }],
                title_location: [Nullable(enums_1.Location), "above"],
                above: [Array(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis))), []],
                below: [Array(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis))), []],
                left: [Array(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis))), []],
                right: [Array(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis))), []],
                center: [Array(Or(Ref(annotation_1.Annotation), Ref(grid_1.Grid))), []],
                renderers: [Array(Ref(renderer_1.Renderer)), []],
                x_range: [Ref(range_1.Range), function () { return new data_range1d_1.DataRange1d(); }],
                y_range: [Ref(range_1.Range), function () { return new data_range1d_1.DataRange1d(); }],
                x_scale: [Ref(scale_1.Scale), function () { return new linear_scale_1.LinearScale(); }],
                y_scale: [Ref(scale_1.Scale), function () { return new linear_scale_1.LinearScale(); }],
                extra_x_ranges: [Dict(Ref(range_1.Range)), {}],
                extra_y_ranges: [Dict(Ref(range_1.Range)), {}],
                extra_x_scales: [Dict(Ref(scale_1.Scale)), {}],
                extra_y_scales: [Dict(Ref(scale_1.Scale)), {}],
                lod_factor: [Number, 10],
                lod_interval: [Number, 300],
                lod_threshold: [Nullable(Number), 2000],
                lod_timeout: [Number, 500],
                hidpi: [Boolean, true],
                output_backend: [enums_1.OutputBackend, "canvas"],
                min_border: [Nullable(Number), 5],
                min_border_top: [Nullable(Number), null],
                min_border_left: [Nullable(Number), null],
                min_border_bottom: [Nullable(Number), null],
                min_border_right: [Nullable(Number), null],
                inner_width: [Number, 0],
                inner_height: [Number, 0],
                outer_width: [Number, 0],
                outer_height: [Number, 0],
                match_aspect: [Boolean, false],
                aspect_scale: [Number, 1],
                reset_policy: [enums_1.ResetPolicy, "standard"],
            });
        });
        _a.override({
            width: 600,
            height: 600,
            outline_line_color: "#e5e5e5",
            border_fill_color: "#ffffff",
            background_fill_color: "#ffffff",
        });
    })();
},
/* models/plots/plot_canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var cartesian_frame_1 = require(241) /* ../canvas/cartesian_frame */;
    var canvas_1 = require(364) /* ../canvas/canvas */;
    var layout_dom_1 = require(424) /* ../layouts/layout_dom */;
    var annotation_1 = require(155) /* ../annotations/annotation */;
    var title_1 = require(233) /* ../annotations/title */;
    var axis_1 = require(243) /* ../axes/axis */;
    var toolbar_panel_1 = require(335) /* ../annotations/toolbar_panel */;
    var bokeh_events_1 = require(366) /* ../../core/bokeh_events */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var visuals_1 = require(160) /* ../../core/visuals */;
    var logging_1 = require(134) /* ../../core/logging */;
    var bokeh_events_2 = require(366) /* ../../core/bokeh_events */;
    var throttle_1 = require(448) /* ../../core/util/throttle */;
    var types_1 = require(125) /* ../../core/util/types */;
    var array_1 = require(126) /* ../../core/util/array */;
    var canvas_2 = require(350) /* ../../core/util/canvas */;
    var alignments_1 = require(323) /* ../../core/layout/alignments */;
    var border_1 = require(326) /* ../../core/layout/border */;
    var grid_1 = require(324) /* ../../core/layout/grid */;
    var side_panel_1 = require(238) /* ../../core/layout/side_panel */;
    var bbox_1 = require(180) /* ../../core/util/bbox */;
    var range_manager_1 = require(449) /* ./range_manager */;
    var state_manager_1 = require(450) /* ./state_manager */;
    var settings_1 = require(143) /* ../../core/settings */;
    var PlotView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PlotView, _super);
        function PlotView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._outer_bbox = new bbox_1.BBox();
            _this._inner_bbox = new bbox_1.BBox();
            _this._needs_paint = true;
            _this._needs_layout = false;
            _this._invalidated_painters = new Set();
            _this._invalidate_all = true;
            _this._needs_notify = false;
            return _this;
        }
        Object.defineProperty(PlotView.prototype, "canvas", {
            get: function () {
                return this.canvas_view;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(PlotView.prototype, "state", {
            get: function () {
                return this._state_manager;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(PlotView.prototype, "invalidate_dataranges", {
            set: function (value) {
                this._range_manager.invalidate_dataranges = value;
            },
            enumerable: false,
            configurable: true
        });
        PlotView.prototype.renderer_view = function (renderer) {
            var e_1, _a;
            var view = this.renderer_views.get(renderer);
            if (view == null) {
                try {
                    for (var _b = (0, tslib_1.__values)(this.renderer_views), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var _d = (0, tslib_1.__read)(_c.value, 2), renderer_view = _d[1];
                        var view_1 = renderer_view.renderer_view(renderer);
                        if (view_1 != null)
                            return view_1;
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
            }
            return view;
        };
        Object.defineProperty(PlotView.prototype, "is_paused", {
            get: function () {
                return this._is_paused != null && this._is_paused !== 0;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(PlotView.prototype, "child_models", {
            get: function () {
                return [];
            },
            enumerable: false,
            configurable: true
        });
        PlotView.prototype.pause = function () {
            if (this._is_paused == null)
                this._is_paused = 1;
            else
                this._is_paused += 1;
        };
        PlotView.prototype.unpause = function (no_render) {
            if (no_render === void 0) {
                no_render = false;
            }
            if (this._is_paused == null)
                throw new Error("wasn't paused");
            this._is_paused -= 1;
            if (this._is_paused == 0 && !no_render)
                this.request_paint("everything");
        };
        PlotView.prototype.notify_finished_after_paint = function () {
            this._needs_notify = true;
        };
        // TODO: this needs to be removed
        PlotView.prototype.request_render = function () {
            this.request_paint("everything");
        };
        PlotView.prototype.request_paint = function (to_invalidate) {
            this.invalidate_painters(to_invalidate);
            this.schedule_paint();
        };
        PlotView.prototype.invalidate_painters = function (to_invalidate) {
            var e_2, _a;
            if (to_invalidate == "everything")
                this._invalidate_all = true;
            else if ((0, types_1.isArray)(to_invalidate)) {
                try {
                    for (var to_invalidate_1 = (0, tslib_1.__values)(to_invalidate), to_invalidate_1_1 = to_invalidate_1.next(); !to_invalidate_1_1.done; to_invalidate_1_1 = to_invalidate_1.next()) {
                        var renderer_view = to_invalidate_1_1.value;
                        this._invalidated_painters.add(renderer_view);
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (to_invalidate_1_1 && !to_invalidate_1_1.done && (_a = to_invalidate_1.return))
                            _a.call(to_invalidate_1);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
            }
            else
                this._invalidated_painters.add(to_invalidate);
        };
        PlotView.prototype.schedule_paint = function () {
            if (!this.is_paused) {
                var promise_1 = this.throttled_paint();
                this._ready = this._ready.then(function () { return promise_1; });
            }
        };
        PlotView.prototype.request_layout = function () {
            this._needs_layout = true;
            this.request_paint("everything");
        };
        PlotView.prototype.reset = function () {
            if (this.model.reset_policy == "standard") {
                this.state.clear();
                this.reset_range();
                this.reset_selection();
            }
            this.model.trigger_event(new bokeh_events_1.Reset());
        };
        PlotView.prototype.remove = function () {
            (0, build_views_1.remove_views)(this.renderer_views);
            (0, build_views_1.remove_views)(this.tool_views);
            this.canvas_view.remove();
            _super.prototype.remove.call(this);
        };
        PlotView.prototype.render = function () {
            _super.prototype.render.call(this);
            this.el.appendChild(this.canvas_view.el);
            this.canvas_view.render();
        };
        PlotView.prototype.initialize = function () {
            var _this = this;
            this.pause();
            _super.prototype.initialize.call(this);
            this.lod_started = false;
            this.visuals = new visuals_1.Visuals(this);
            this._initial_state = {
                selection: new Map(),
                dimensions: { width: 0, height: 0 }, // XXX: initial dimensions
            };
            this.visibility_callbacks = [];
            this.renderer_views = new Map();
            this.tool_views = new Map();
            this.frame = new cartesian_frame_1.CartesianFrame(this.model.x_scale, this.model.y_scale, this.model.x_range, this.model.y_range, this.model.extra_x_ranges, this.model.extra_y_ranges, this.model.extra_x_scales, this.model.extra_y_scales);
            this._range_manager = new range_manager_1.RangeManager(this);
            this._state_manager = new state_manager_1.StateManager(this, this._initial_state);
            this.throttled_paint = (0, throttle_1.throttle)(function () { return _this.repaint(); }, 1000 / 60);
            var _a = this.model, title_location = _a.title_location, title = _a.title;
            if (title_location != null && title != null) {
                this._title = title instanceof title_1.Title ? title : new title_1.Title({ text: title });
            }
            var _b = this.model, toolbar_location = _b.toolbar_location, toolbar = _b.toolbar;
            if (toolbar_location != null && toolbar != null) {
                this._toolbar = new toolbar_panel_1.ToolbarPanel({ toolbar: toolbar });
                toolbar.toolbar_location = toolbar_location;
            }
        };
        PlotView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var _a, hidpi, output_backend, canvas, _b;
                return (0, tslib_1.__generator)(this, function (_c) {
                    switch (_c.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _c.sent();
                            _a = this.model, hidpi = _a.hidpi, output_backend = _a.output_backend;
                            canvas = new canvas_1.Canvas({ hidpi: hidpi, output_backend: output_backend });
                            _b = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(canvas, { parent: this })];
                        case 2:
                            _b.canvas_view = _c.sent();
                            this.canvas_view.plot_views = [this];
                            return [4 /*yield*/, this.build_renderer_views()];
                        case 3:
                            _c.sent();
                            return [4 /*yield*/, this.build_tool_views()];
                        case 4:
                            _c.sent();
                            this._range_manager.update_dataranges();
                            this.unpause(true);
                            logging_1.logger.debug("PlotView initialized");
                            return [2 /*return*/];
                    }
                });
            });
        };
        PlotView.prototype._width_policy = function () {
            return this.model.frame_width == null ? _super.prototype._width_policy.call(this) : "min";
        };
        PlotView.prototype._height_policy = function () {
            return this.model.frame_height == null ? _super.prototype._height_policy.call(this) : "min";
        };
        PlotView.prototype._update_layout = function () {
            var _this = this;
            var _a, _b, _c, _d, _e;
            this.layout = new border_1.BorderLayout();
            this.layout.set_sizing(this.box_sizing());
            var above = (0, array_1.copy)(this.model.above);
            var below = (0, array_1.copy)(this.model.below);
            var left = (0, array_1.copy)(this.model.left);
            var right = (0, array_1.copy)(this.model.right);
            var get_side = function (side) {
                switch (side) {
                    case "above": return above;
                    case "below": return below;
                    case "left": return left;
                    case "right": return right;
                }
            };
            var _f = this.model, title_location = _f.title_location, title = _f.title;
            if (title_location != null && title != null) {
                get_side(title_location).push(this._title);
            }
            var _g = this.model, toolbar_location = _g.toolbar_location, toolbar = _g.toolbar;
            if (toolbar_location != null && toolbar != null) {
                var panels = get_side(toolbar_location);
                var push_toolbar = true;
                if (this.model.toolbar_sticky) {
                    for (var i = 0; i < panels.length; i++) {
                        var panel = panels[i];
                        if (panel instanceof title_1.Title) {
                            if (toolbar_location == "above" || toolbar_location == "below")
                                panels[i] = [panel, this._toolbar];
                            else
                                panels[i] = [this._toolbar, panel];
                            push_toolbar = false;
                            break;
                        }
                    }
                }
                if (push_toolbar)
                    panels.push(this._toolbar);
            }
            var set_layout = function (side, model) {
                var _a;
                var view = _this.renderer_view(model);
                view.panel = new side_panel_1.Panel(side);
                (_a = view.update_layout) === null || _a === void 0 ? void 0 : _a.call(view);
                return view.layout;
            };
            var set_layouts = function (side, panels) {
                var e_3, _a;
                var horizontal = side == "above" || side == "below";
                var layouts = [];
                try {
                    for (var panels_1 = (0, tslib_1.__values)(panels), panels_1_1 = panels_1.next(); !panels_1_1.done; panels_1_1 = panels_1.next()) {
                        var panel = panels_1_1.value;
                        if ((0, types_1.isArray)(panel)) {
                            var items = panel.map(function (subpanel) {
                                var _a;
                                var item = set_layout(side, subpanel);
                                if (subpanel instanceof toolbar_panel_1.ToolbarPanel) {
                                    var dim = horizontal ? "width_policy" : "height_policy";
                                    item.set_sizing((0, tslib_1.__assign)((0, tslib_1.__assign)({}, item.sizing), (_a = {}, _a[dim] = "min", _a)));
                                }
                                return item;
                            });
                            var layout = void 0;
                            if (horizontal) {
                                layout = new grid_1.Row(items);
                                layout.set_sizing({ width_policy: "max", height_policy: "min" });
                            }
                            else {
                                layout = new grid_1.Column(items);
                                layout.set_sizing({ width_policy: "min", height_policy: "max" });
                            }
                            layout.absolute = true;
                            layouts.push(layout);
                        }
                        else
                            layouts.push(set_layout(side, panel));
                    }
                }
                catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                }
                finally {
                    try {
                        if (panels_1_1 && !panels_1_1.done && (_a = panels_1.return))
                            _a.call(panels_1);
                    }
                    finally {
                        if (e_3)
                            throw e_3.error;
                    }
                }
                return layouts;
            };
            var min_border = (_a = this.model.min_border) !== null && _a !== void 0 ? _a : 0;
            this.layout.min_border = {
                left: (_b = this.model.min_border_left) !== null && _b !== void 0 ? _b : min_border,
                top: (_c = this.model.min_border_top) !== null && _c !== void 0 ? _c : min_border,
                right: (_d = this.model.min_border_right) !== null && _d !== void 0 ? _d : min_border,
                bottom: (_e = this.model.min_border_bottom) !== null && _e !== void 0 ? _e : min_border,
            };
            var center_panel = new alignments_1.NodeLayout();
            var top_panel = new alignments_1.VStack();
            var bottom_panel = new alignments_1.VStack();
            var left_panel = new alignments_1.HStack();
            var right_panel = new alignments_1.HStack();
            center_panel.absolute = true;
            top_panel.absolute = true;
            bottom_panel.absolute = true;
            left_panel.absolute = true;
            right_panel.absolute = true;
            center_panel.children =
                this.model.center.filter(function (obj) {
                    return obj instanceof annotation_1.Annotation;
                }).map(function (model) {
                    var _a;
                    var view = _this.renderer_view(model);
                    (_a = view.update_layout) === null || _a === void 0 ? void 0 : _a.call(view);
                    return view.layout;
                }).filter(function (layout) {
                    return layout != null;
                });
            var _h = this.model, frame_width = _h.frame_width, frame_height = _h.frame_height;
            center_panel.set_sizing((0, tslib_1.__assign)((0, tslib_1.__assign)({}, (frame_width != null ? { width_policy: "fixed", width: frame_width } : { width_policy: "fit" })), (frame_height != null ? { height_policy: "fixed", height: frame_height } : { height_policy: "fit" })));
            center_panel.on_resize(function (bbox) { return _this.frame.set_geometry(bbox); });
            top_panel.children = (0, array_1.reversed)(set_layouts("above", above));
            bottom_panel.children = set_layouts("below", below);
            left_panel.children = (0, array_1.reversed)(set_layouts("left", left));
            right_panel.children = set_layouts("right", right);
            top_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: this.layout.min_border.top*/ });
            bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: this.layout.min_width.bottom*/ });
            left_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: this.layout.min_width.left*/ });
            right_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: this.layout.min_width.right*/ });
            this.layout.center_panel = center_panel;
            this.layout.top_panel = top_panel;
            this.layout.bottom_panel = bottom_panel;
            this.layout.left_panel = left_panel;
            this.layout.right_panel = right_panel;
        };
        Object.defineProperty(PlotView.prototype, "axis_views", {
            get: function () {
                var e_4, _a;
                var views = [];
                try {
                    for (var _b = (0, tslib_1.__values)(this.renderer_views), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var _d = (0, tslib_1.__read)(_c.value, 2), renderer_view = _d[1];
                        if (renderer_view instanceof axis_1.AxisView)
                            views.push(renderer_view);
                    }
                }
                catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_4)
                            throw e_4.error;
                    }
                }
                return views;
            },
            enumerable: false,
            configurable: true
        });
        PlotView.prototype.set_toolbar_visibility = function (visible) {
            var e_5, _a;
            try {
                for (var _b = (0, tslib_1.__values)(this.visibility_callbacks), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var callback = _c.value;
                    callback(visible);
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
        };
        PlotView.prototype.update_range = function (range_info, options) {
            this.pause();
            this._range_manager.update(range_info, options);
            this.unpause();
        };
        PlotView.prototype.reset_range = function () {
            this.update_range(null);
            this.trigger_ranges_update_event();
        };
        PlotView.prototype.trigger_ranges_update_event = function () {
            var _a = this.model, x_range = _a.x_range, y_range = _a.y_range;
            this.model.trigger_event(new bokeh_events_2.RangesUpdate(x_range.start, x_range.end, y_range.start, y_range.end));
        };
        PlotView.prototype.get_selection = function () {
            var e_6, _a;
            var selection = new Map();
            try {
                for (var _b = (0, tslib_1.__values)(this.model.data_renderers), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var renderer = _c.value;
                    var selected = renderer.selection_manager.source.selected;
                    selection.set(renderer, selected);
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            return selection;
        };
        PlotView.prototype.update_selection = function (selections) {
            var e_7, _a;
            try {
                for (var _b = (0, tslib_1.__values)(this.model.data_renderers), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var renderer = _c.value;
                    var ds = renderer.selection_manager.source;
                    if (selections != null) {
                        var selection = selections.get(renderer);
                        if (selection != null) {
                            ds.selected.update(selection, true);
                        }
                    }
                    else
                        ds.selection_manager.clear();
                }
            }
            catch (e_7_1) {
                e_7 = { error: e_7_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_7)
                        throw e_7.error;
                }
            }
        };
        PlotView.prototype.reset_selection = function () {
            this.update_selection(null);
        };
        PlotView.prototype._invalidate_layout = function () {
            var _this = this;
            var needs_layout = function () {
                var e_8, _a;
                var _b;
                try {
                    for (var _c = (0, tslib_1.__values)(_this.model.side_panels), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var panel = _d.value;
                        var view = _this.renderer_views.get(panel);
                        if ((_b = view.layout) === null || _b === void 0 ? void 0 : _b.has_size_changed()) {
                            _this.invalidate_painters(view);
                            return true;
                        }
                    }
                }
                catch (e_8_1) {
                    e_8 = { error: e_8_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_a = _c.return))
                            _a.call(_c);
                    }
                    finally {
                        if (e_8)
                            throw e_8.error;
                    }
                }
                return false;
            };
            if (needs_layout())
                this.root.compute_layout();
        };
        PlotView.prototype.get_renderer_views = function () {
            var _this = this;
            return this.computed_renderers.map(function (r) { return _this.renderer_views.get(r); });
        };
        PlotView.prototype._compute_renderers = function () {
            var _a, above, below, left, right, center, renderers, _b, _c, tool, e_9_1;
            var e_9, _d;
            return (0, tslib_1.__generator)(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        _a = this.model, above = _a.above, below = _a.below, left = _a.left, right = _a.right, center = _a.center, renderers = _a.renderers;
                        return [5 /*yield**/, (0, tslib_1.__values)(renderers)];
                    case 1:
                        _e.sent();
                        return [5 /*yield**/, (0, tslib_1.__values)(above)];
                    case 2:
                        _e.sent();
                        return [5 /*yield**/, (0, tslib_1.__values)(below)];
                    case 3:
                        _e.sent();
                        return [5 /*yield**/, (0, tslib_1.__values)(left)];
                    case 4:
                        _e.sent();
                        return [5 /*yield**/, (0, tslib_1.__values)(right)];
                    case 5:
                        _e.sent();
                        return [5 /*yield**/, (0, tslib_1.__values)(center)];
                    case 6:
                        _e.sent();
                        if (!(this._title != null))
                            return [3 /*break*/, 8];
                        return [4 /*yield*/, this._title];
                    case 7:
                        _e.sent();
                        _e.label = 8;
                    case 8:
                        if (!(this._toolbar != null))
                            return [3 /*break*/, 10];
                        return [4 /*yield*/, this._toolbar];
                    case 9:
                        _e.sent();
                        _e.label = 10;
                    case 10:
                        _e.trys.push([10, 17, 18, 19]);
                        _b = (0, tslib_1.__values)(this.model.toolbar.tools), _c = _b.next();
                        _e.label = 11;
                    case 11:
                        if (!!_c.done)
                            return [3 /*break*/, 16];
                        tool = _c.value;
                        if (!(tool.overlay != null))
                            return [3 /*break*/, 13];
                        return [4 /*yield*/, tool.overlay];
                    case 12:
                        _e.sent();
                        _e.label = 13;
                    case 13: return [5 /*yield**/, (0, tslib_1.__values)(tool.synthetic_renderers)];
                    case 14:
                        _e.sent();
                        _e.label = 15;
                    case 15:
                        _c = _b.next();
                        return [3 /*break*/, 11];
                    case 16: return [3 /*break*/, 19];
                    case 17:
                        e_9_1 = _e.sent();
                        e_9 = { error: e_9_1 };
                        return [3 /*break*/, 19];
                    case 18:
                        try {
                            if (_c && !_c.done && (_d = _b.return))
                                _d.call(_b);
                        }
                        finally {
                            if (e_9)
                                throw e_9.error;
                        }
                        return [7 /*endfinally*/];
                    case 19: return [2 /*return*/];
                }
            });
        };
        PlotView.prototype.build_renderer_views = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            this.computed_renderers = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this._compute_renderers()), false);
                            return [4 /*yield*/, (0, build_views_1.build_views)(this.renderer_views, this.computed_renderers, { parent: this })];
                        case 1:
                            _a.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        PlotView.prototype.build_tool_views = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var tool_models, new_tool_views;
                var _this = this;
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            tool_models = this.model.toolbar.tools;
                            return [4 /*yield*/, (0, build_views_1.build_views)(this.tool_views, tool_models, { parent: this })];
                        case 1:
                            new_tool_views = _a.sent();
                            new_tool_views.map(function (tool_view) { return _this.canvas_view.ui_event_bus.register_tool(tool_view); });
                            return [2 /*return*/];
                    }
                });
            });
        };
        PlotView.prototype.connect_signals = function () {
            var e_10, _a, e_11, _b;
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var _c = this.frame, x_ranges = _c.x_ranges, y_ranges = _c.y_ranges;
            try {
                for (var x_ranges_1 = (0, tslib_1.__values)(x_ranges), x_ranges_1_1 = x_ranges_1.next(); !x_ranges_1_1.done; x_ranges_1_1 = x_ranges_1.next()) {
                    var _d = (0, tslib_1.__read)(x_ranges_1_1.value, 2), range = _d[1];
                    this.connect(range.change, function () { _this._needs_layout = true; _this.request_paint("everything"); });
                }
            }
            catch (e_10_1) {
                e_10 = { error: e_10_1 };
            }
            finally {
                try {
                    if (x_ranges_1_1 && !x_ranges_1_1.done && (_a = x_ranges_1.return))
                        _a.call(x_ranges_1);
                }
                finally {
                    if (e_10)
                        throw e_10.error;
                }
            }
            try {
                for (var y_ranges_1 = (0, tslib_1.__values)(y_ranges), y_ranges_1_1 = y_ranges_1.next(); !y_ranges_1_1.done; y_ranges_1_1 = y_ranges_1.next()) {
                    var _e = (0, tslib_1.__read)(y_ranges_1_1.value, 2), range = _e[1];
                    this.connect(range.change, function () { _this._needs_layout = true; _this.request_paint("everything"); });
                }
            }
            catch (e_11_1) {
                e_11 = { error: e_11_1 };
            }
            finally {
                try {
                    if (y_ranges_1_1 && !y_ranges_1_1.done && (_b = y_ranges_1.return))
                        _b.call(y_ranges_1);
                }
                finally {
                    if (e_11)
                        throw e_11.error;
                }
            }
            var _f = this.model.properties, above = _f.above, below = _f.below, left = _f.left, right = _f.right, center = _f.center, renderers = _f.renderers;
            this.on_change([above, below, left, right, center, renderers], function () {
                return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                    return (0, tslib_1.__generator)(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, this.build_renderer_views()];
                            case 1: return [2 /*return*/, _a.sent()];
                        }
                    });
                });
            });
            this.connect(this.model.toolbar.properties.tools.change, function () {
                return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                    return (0, tslib_1.__generator)(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, this.build_renderer_views()];
                            case 1:
                                _a.sent();
                                return [4 /*yield*/, this.build_tool_views()];
                            case 2:
                                _a.sent();
                                return [2 /*return*/];
                        }
                    });
                });
            });
            this.connect(this.model.change, function () { return _this.request_paint("everything"); });
            this.connect(this.model.reset, function () { return _this.reset(); });
        };
        PlotView.prototype.has_finished = function () {
            var e_12, _a;
            if (!_super.prototype.has_finished.call(this))
                return false;
            if (this.model.visible) {
                try {
                    for (var _b = (0, tslib_1.__values)(this.renderer_views), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var _d = (0, tslib_1.__read)(_c.value, 2), renderer_view = _d[1];
                        if (!renderer_view.has_finished())
                            return false;
                    }
                }
                catch (e_12_1) {
                    e_12 = { error: e_12_1 };
                }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return))
                            _a.call(_b);
                    }
                    finally {
                        if (e_12)
                            throw e_12.error;
                    }
                }
            }
            return true;
        };
        PlotView.prototype.after_layout = function () {
            var e_13, _a;
            var _b;
            _super.prototype.after_layout.call(this);
            try {
                for (var _c = (0, tslib_1.__values)(this.renderer_views), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), child_view = _e[1];
                    if (child_view instanceof annotation_1.AnnotationView)
                        (_b = child_view.after_layout) === null || _b === void 0 ? void 0 : _b.call(child_view);
                }
            }
            catch (e_13_1) {
                e_13 = { error: e_13_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return))
                        _a.call(_c);
                }
                finally {
                    if (e_13)
                        throw e_13.error;
                }
            }
            this._needs_layout = false;
            this.model.setv({
                inner_width: Math.round(this.frame.bbox.width),
                inner_height: Math.round(this.frame.bbox.height),
                outer_width: Math.round(this.layout.bbox.width),
                outer_height: Math.round(this.layout.bbox.height),
            }, { no_change: true });
            if (this.model.match_aspect !== false) {
                this.pause();
                this._range_manager.update_dataranges();
                this.unpause(true);
            }
            if (!this._outer_bbox.equals(this.layout.bbox)) {
                var _f = this.layout.bbox, width = _f.width, height = _f.height;
                this.canvas_view.resize(width, height);
                this._outer_bbox = this.layout.bbox;
                this._invalidate_all = true;
                this._needs_paint = true;
            }
            var inner_bbox = this.layout.inner_bbox;
            if (!this._inner_bbox.equals(inner_bbox)) {
                this._inner_bbox = inner_bbox;
                this._needs_paint = true;
            }
            if (this._needs_paint) {
                // XXX: can't be this.request_paint(), because it would trigger back-and-forth
                // layout recomputing feedback loop between plots. Plots are also much more
                // responsive this way, especially in interactive mode.
                this.paint();
            }
        };
        PlotView.prototype.repaint = function () {
            if (this._needs_layout)
                this._invalidate_layout();
            this.paint();
        };
        PlotView.prototype.paint = function () {
            if (this.is_paused)
                return;
            if (this.model.visible) {
                logging_1.logger.trace(this.toString() + ".paint()");
                this._actual_paint();
            }
            if (this._needs_notify) {
                this._needs_notify = false;
                this.notify_finished();
            }
        };
        PlotView.prototype._actual_paint = function () {
            var e_14, _a;
            var _this = this;
            var _b;
            var document = this.model.document;
            if (document != null) {
                var interactive_duration = document.interactive_duration();
                if (interactive_duration >= 0 && interactive_duration < this.model.lod_interval) {
                    setTimeout(function () {
                        if (document.interactive_duration() > _this.model.lod_timeout) {
                            document.interactive_stop();
                        }
                        _this.request_paint("everything"); // TODO: this.schedule_paint()
                    }, this.model.lod_timeout);
                }
                else
                    document.interactive_stop();
            }
            if (this._range_manager.invalidate_dataranges) {
                this._range_manager.update_dataranges();
                this._invalidate_layout();
            }
            var do_primary = false;
            var do_overlays = false;
            if (this._invalidate_all) {
                do_primary = true;
                do_overlays = true;
            }
            else {
                try {
                    for (var _c = (0, tslib_1.__values)(this._invalidated_painters), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var painter = _d.value;
                        var level = painter.model.level;
                        if (level != "overlay")
                            do_primary = true;
                        else
                            do_overlays = true;
                        if (do_primary && do_overlays)
                            break;
                    }
                }
                catch (e_14_1) {
                    e_14 = { error: e_14_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_a = _c.return))
                            _a.call(_c);
                    }
                    finally {
                        if (e_14)
                            throw e_14.error;
                    }
                }
            }
            this._invalidated_painters.clear();
            this._invalidate_all = false;
            var frame_box = [
                this.frame.bbox.left,
                this.frame.bbox.top,
                this.frame.bbox.width,
                this.frame.bbox.height,
            ];
            var _e = this.canvas_view, primary = _e.primary, overlays = _e.overlays;
            if (do_primary) {
                primary.prepare();
                this.canvas_view.prepare_webgl(frame_box);
                this._map_hook(primary.ctx, frame_box);
                this._paint_empty(primary.ctx, frame_box);
                this._paint_outline(primary.ctx, frame_box);
                this._paint_levels(primary.ctx, "image", frame_box, true);
                this._paint_levels(primary.ctx, "underlay", frame_box, true);
                this._paint_levels(primary.ctx, "glyph", frame_box, true);
                this._paint_levels(primary.ctx, "guide", frame_box, false);
                this._paint_levels(primary.ctx, "annotation", frame_box, false);
                primary.finish();
            }
            if (do_overlays || settings_1.settings.wireframe) {
                overlays.prepare();
                this._paint_levels(overlays.ctx, "overlay", frame_box, false);
                if (settings_1.settings.wireframe)
                    this._paint_layout(overlays.ctx, this.layout);
                overlays.finish();
            }
            if (this._initial_state.range == null) {
                this._initial_state.range = (_b = this._range_manager.compute_initial()) !== null && _b !== void 0 ? _b : undefined;
            }
            this._needs_paint = false;
        };
        PlotView.prototype._paint_levels = function (ctx, level, clip_region, global_clip) {
            var e_15, _a;
            try {
                for (var _b = (0, tslib_1.__values)(this.computed_renderers), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var renderer = _c.value;
                    if (renderer.level != level)
                        continue;
                    var renderer_view = this.renderer_views.get(renderer);
                    ctx.save();
                    if (global_clip || renderer_view.needs_clip) {
                        ctx.beginPath();
                        ctx.rect.apply(ctx, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(clip_region), false));
                        ctx.clip();
                    }
                    renderer_view.render();
                    ctx.restore();
                    if (renderer_view.has_webgl && renderer_view.needs_webgl_blit) {
                        this.canvas_view.blit_webgl(ctx);
                    }
                }
            }
            catch (e_15_1) {
                e_15 = { error: e_15_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_15)
                        throw e_15.error;
                }
            }
        };
        PlotView.prototype._paint_layout = function (ctx, layout) {
            var e_16, _a;
            var _b = layout.bbox, x = _b.x, y = _b.y, width = _b.width, height = _b.height;
            ctx.strokeStyle = "blue";
            ctx.strokeRect(x, y, width, height);
            try {
                for (var layout_1 = (0, tslib_1.__values)(layout), layout_1_1 = layout_1.next(); !layout_1_1.done; layout_1_1 = layout_1.next()) {
                    var child = layout_1_1.value;
                    ctx.save();
                    if (!layout.absolute)
                        ctx.translate(x, y);
                    this._paint_layout(ctx, child);
                    ctx.restore();
                }
            }
            catch (e_16_1) {
                e_16 = { error: e_16_1 };
            }
            finally {
                try {
                    if (layout_1_1 && !layout_1_1.done && (_a = layout_1.return))
                        _a.call(layout_1);
                }
                finally {
                    if (e_16)
                        throw e_16.error;
                }
            }
        };
        PlotView.prototype._map_hook = function (_ctx, _frame_box) { };
        PlotView.prototype._paint_empty = function (ctx, frame_box) {
            var _a = (0, tslib_1.__read)([0, 0, this.layout.bbox.width, this.layout.bbox.height], 4), cx = _a[0], cy = _a[1], cw = _a[2], ch = _a[3];
            var _b = (0, tslib_1.__read)(frame_box, 4), fx = _b[0], fy = _b[1], fw = _b[2], fh = _b[3];
            if (this.visuals.border_fill.doit) {
                this.visuals.border_fill.set_value(ctx);
                ctx.fillRect(cx, cy, cw, ch);
                ctx.clearRect(fx, fy, fw, fh);
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_value(ctx);
                ctx.fillRect(fx, fy, fw, fh);
            }
        };
        PlotView.prototype._paint_outline = function (ctx, frame_box) {
            if (this.visuals.outline_line.doit) {
                ctx.save();
                this.visuals.outline_line.set_value(ctx);
                var _a = (0, tslib_1.__read)(frame_box, 4), x0 = _a[0], y0 = _a[1], w = _a[2], h = _a[3];
                // XXX: shrink outline region by 1px to make right and bottom lines visible
                // if they are on the edge of the canvas.
                if (x0 + w == this.layout.bbox.width) {
                    w -= 1;
                }
                if (y0 + h == this.layout.bbox.height) {
                    h -= 1;
                }
                ctx.strokeRect(x0, y0, w, h);
                ctx.restore();
            }
        };
        PlotView.prototype.to_blob = function () {
            return this.canvas_view.to_blob();
        };
        PlotView.prototype.export = function (type, hidpi) {
            if (hidpi === void 0) {
                hidpi = true;
            }
            var output_backend = type == "png" ? "canvas" : "svg";
            var composite = new canvas_2.CanvasLayer(output_backend, hidpi);
            var _a = this.layout.bbox, width = _a.width, height = _a.height;
            composite.resize(width, height);
            var canvas = this.canvas_view.compose().canvas;
            composite.ctx.drawImage(canvas, 0, 0);
            return composite;
        };
        PlotView.prototype.serializable_state = function () {
            var _a = _super.prototype.serializable_state.call(this), children = _a.children, state = (0, tslib_1.__rest)(_a, ["children"]);
            var renderers = this.get_renderer_views()
                .map(function (view) { return view.serializable_state(); })
                .filter(function (item) { return item.bbox != null; });
            return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, state), { children: (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(children !== null && children !== void 0 ? children : []), false), (0, tslib_1.__read)(renderers), false) });
        };
        return PlotView;
    }(layout_dom_1.LayoutDOMView));
    exports.PlotView = PlotView;
    PlotView.__name__ = "PlotView";
},
/* core/util/throttle.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    /**
     * Returns a function, that, when invoked, will only be triggered at
     * most once during a given interval of time and no more frequently
     * than the animation frame rate allows it.
     *
     * @param func [function] the function to throttle
     * @param wait [number] time in milliseconds to use for window
     * @return [function] throttled function
     */
    function throttle(func, wait) {
        var timeout = null;
        var previous = 0;
        var pending = false;
        return function () {
            return new Promise(function (resolve, reject) {
                var later = function () {
                    previous = Date.now();
                    timeout = null;
                    pending = false;
                    try {
                        func();
                        resolve();
                    }
                    catch (error) {
                        reject(error);
                    }
                };
                var now = Date.now();
                var remaining = wait - (now - previous);
                if (remaining <= 0 && !pending) {
                    if (timeout != null) {
                        clearTimeout(timeout);
                    }
                    pending = true;
                    requestAnimationFrame(later);
                }
                else if (!timeout && !pending) {
                    timeout = setTimeout(function () { return requestAnimationFrame(later); }, remaining);
                }
                else {
                    resolve();
                }
            });
        };
    }
    exports.throttle = throttle;
},
/* models/plots/range_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var data_range1d_1 = require(178) /* ../ranges/data_range1d */;
    var logging_1 = require(134) /* ../../core/logging */;
    var RangeManager = /** @class */ (function () {
        function RangeManager(parent) {
            this.parent = parent;
            this.invalidate_dataranges = true;
        }
        Object.defineProperty(RangeManager.prototype, "frame", {
            get: function () {
                return this.parent.frame;
            },
            enumerable: false,
            configurable: true
        });
        RangeManager.prototype.update = function (range_info, options) {
            var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
            var _e = this.frame, x_ranges = _e.x_ranges, y_ranges = _e.y_ranges;
            if (range_info == null) {
                try {
                    for (var x_ranges_1 = (0, tslib_1.__values)(x_ranges), x_ranges_1_1 = x_ranges_1.next(); !x_ranges_1_1.done; x_ranges_1_1 = x_ranges_1.next()) {
                        var _f = (0, tslib_1.__read)(x_ranges_1_1.value, 2), range = _f[1];
                        range.reset();
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (x_ranges_1_1 && !x_ranges_1_1.done && (_a = x_ranges_1.return))
                            _a.call(x_ranges_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
                try {
                    for (var y_ranges_1 = (0, tslib_1.__values)(y_ranges), y_ranges_1_1 = y_ranges_1.next(); !y_ranges_1_1.done; y_ranges_1_1 = y_ranges_1.next()) {
                        var _g = (0, tslib_1.__read)(y_ranges_1_1.value, 2), range = _g[1];
                        range.reset();
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (y_ranges_1_1 && !y_ranges_1_1.done && (_b = y_ranges_1.return))
                            _b.call(y_ranges_1);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
                this.update_dataranges();
            }
            else {
                var range_info_iter = [];
                try {
                    for (var x_ranges_2 = (0, tslib_1.__values)(x_ranges), x_ranges_2_1 = x_ranges_2.next(); !x_ranges_2_1.done; x_ranges_2_1 = x_ranges_2.next()) {
                        var _h = (0, tslib_1.__read)(x_ranges_2_1.value, 2), name = _h[0], range = _h[1];
                        range_info_iter.push([range, range_info.xrs.get(name)]);
                    }
                }
                catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                }
                finally {
                    try {
                        if (x_ranges_2_1 && !x_ranges_2_1.done && (_c = x_ranges_2.return))
                            _c.call(x_ranges_2);
                    }
                    finally {
                        if (e_3)
                            throw e_3.error;
                    }
                }
                try {
                    for (var y_ranges_2 = (0, tslib_1.__values)(y_ranges), y_ranges_2_1 = y_ranges_2.next(); !y_ranges_2_1.done; y_ranges_2_1 = y_ranges_2.next()) {
                        var _j = (0, tslib_1.__read)(y_ranges_2_1.value, 2), name = _j[0], range = _j[1];
                        range_info_iter.push([range, range_info.yrs.get(name)]);
                    }
                }
                catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                }
                finally {
                    try {
                        if (y_ranges_2_1 && !y_ranges_2_1.done && (_d = y_ranges_2.return))
                            _d.call(y_ranges_2);
                    }
                    finally {
                        if (e_4)
                            throw e_4.error;
                    }
                }
                if (options === null || options === void 0 ? void 0 : options.scrolling) {
                    this._update_ranges_together(range_info_iter); // apply interval bounds while keeping aspect
                }
                this._update_ranges_individually(range_info_iter, options);
            }
        };
        RangeManager.prototype.reset = function () {
            this.update(null);
        };
        RangeManager.prototype._update_dataranges = function (frame) {
            var e_5, _a, e_6, _b, e_7, _c, e_8, _d, e_9, _e, e_10, _f, e_11, _g;
            // Update any DataRange1ds here
            var bounds = new Map();
            var log_bounds = new Map();
            var calculate_log_bounds = false;
            try {
                for (var _h = (0, tslib_1.__values)(frame.x_ranges), _j = _h.next(); !_j.done; _j = _h.next()) {
                    var _k = (0, tslib_1.__read)(_j.value, 2), xr = _k[1];
                    if (xr instanceof data_range1d_1.DataRange1d && xr.scale_hint == "log")
                        calculate_log_bounds = true;
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_j && !_j.done && (_a = _h.return))
                        _a.call(_h);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            try {
                for (var _l = (0, tslib_1.__values)(frame.y_ranges), _m = _l.next(); !_m.done; _m = _l.next()) {
                    var _o = (0, tslib_1.__read)(_m.value, 2), yr = _o[1];
                    if (yr instanceof data_range1d_1.DataRange1d && yr.scale_hint == "log")
                        calculate_log_bounds = true;
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_m && !_m.done && (_b = _l.return))
                        _b.call(_l);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            try {
                for (var _p = (0, tslib_1.__values)(this.parent.model.data_renderers), _q = _p.next(); !_q.done; _q = _p.next()) {
                    var renderer = _q.value;
                    var renderer_view = this.parent.renderer_view(renderer);
                    if (renderer_view == null)
                        continue;
                    var bds = renderer_view.glyph_view.bounds();
                    if (bds != null)
                        bounds.set(renderer, bds);
                    if (calculate_log_bounds) {
                        var log_bds = renderer_view.glyph_view.log_bounds();
                        if (log_bds != null)
                            log_bounds.set(renderer, log_bds);
                    }
                }
            }
            catch (e_7_1) {
                e_7 = { error: e_7_1 };
            }
            finally {
                try {
                    if (_q && !_q.done && (_c = _p.return))
                        _c.call(_p);
                }
                finally {
                    if (e_7)
                        throw e_7.error;
                }
            }
            var follow_enabled = false;
            var has_bounds = false;
            //const {width, height} = frame.bbox
            var width = frame.x_target.span;
            var height = frame.y_target.span;
            var r;
            if (this.parent.model.match_aspect !== false && width != 0 && height != 0)
                r = (1 / this.parent.model.aspect_scale) * (width / height);
            try {
                for (var _r = (0, tslib_1.__values)(frame.x_ranges), _s = _r.next(); !_s.done; _s = _r.next()) {
                    var _t = (0, tslib_1.__read)(_s.value, 2), xr = _t[1];
                    if (xr instanceof data_range1d_1.DataRange1d) {
                        var bounds_to_use = xr.scale_hint == "log" ? log_bounds : bounds;
                        xr.update(bounds_to_use, 0, this.parent.model, r);
                        if (xr.follow) {
                            follow_enabled = true;
                        }
                    }
                    if (xr.bounds != null)
                        has_bounds = true;
                }
            }
            catch (e_8_1) {
                e_8 = { error: e_8_1 };
            }
            finally {
                try {
                    if (_s && !_s.done && (_d = _r.return))
                        _d.call(_r);
                }
                finally {
                    if (e_8)
                        throw e_8.error;
                }
            }
            try {
                for (var _u = (0, tslib_1.__values)(frame.y_ranges), _v = _u.next(); !_v.done; _v = _u.next()) {
                    var _w = (0, tslib_1.__read)(_v.value, 2), yr = _w[1];
                    if (yr instanceof data_range1d_1.DataRange1d) {
                        var bounds_to_use = yr.scale_hint == "log" ? log_bounds : bounds;
                        yr.update(bounds_to_use, 1, this.parent.model, r);
                        if (yr.follow) {
                            follow_enabled = true;
                        }
                    }
                    if (yr.bounds != null)
                        has_bounds = true;
                }
            }
            catch (e_9_1) {
                e_9 = { error: e_9_1 };
            }
            finally {
                try {
                    if (_v && !_v.done && (_e = _u.return))
                        _e.call(_u);
                }
                finally {
                    if (e_9)
                        throw e_9.error;
                }
            }
            if (follow_enabled && has_bounds) {
                logging_1.logger.warn("Follow enabled so bounds are unset.");
                try {
                    for (var _x = (0, tslib_1.__values)(frame.x_ranges), _y = _x.next(); !_y.done; _y = _x.next()) {
                        var _z = (0, tslib_1.__read)(_y.value, 2), xr = _z[1];
                        xr.bounds = null;
                    }
                }
                catch (e_10_1) {
                    e_10 = { error: e_10_1 };
                }
                finally {
                    try {
                        if (_y && !_y.done && (_f = _x.return))
                            _f.call(_x);
                    }
                    finally {
                        if (e_10)
                            throw e_10.error;
                    }
                }
                try {
                    for (var _0 = (0, tslib_1.__values)(frame.y_ranges), _1 = _0.next(); !_1.done; _1 = _0.next()) {
                        var _2 = (0, tslib_1.__read)(_1.value, 2), yr = _2[1];
                        yr.bounds = null;
                    }
                }
                catch (e_11_1) {
                    e_11 = { error: e_11_1 };
                }
                finally {
                    try {
                        if (_1 && !_1.done && (_g = _0.return))
                            _g.call(_0);
                    }
                    finally {
                        if (e_11)
                            throw e_11.error;
                    }
                }
            }
        };
        RangeManager.prototype.update_dataranges = function () {
            var e_12, _a;
            this._update_dataranges(this.frame);
            try {
                for (var _b = (0, tslib_1.__values)(this.parent.model.renderers), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var renderer = _c.value;
                    var coordinates = renderer.coordinates;
                    if (coordinates != null)
                        this._update_dataranges(coordinates);
                }
            }
            catch (e_12_1) {
                e_12 = { error: e_12_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_12)
                        throw e_12.error;
                }
            }
            this.invalidate_dataranges = false;
        };
        RangeManager.prototype.compute_initial = function () {
            var e_13, _a, e_14, _b;
            // check for good values for ranges before setting initial range
            var good_vals = true;
            var _c = this.frame, x_ranges = _c.x_ranges, y_ranges = _c.y_ranges;
            var xrs = new Map();
            var yrs = new Map();
            try {
                for (var x_ranges_3 = (0, tslib_1.__values)(x_ranges), x_ranges_3_1 = x_ranges_3.next(); !x_ranges_3_1.done; x_ranges_3_1 = x_ranges_3.next()) {
                    var _d = (0, tslib_1.__read)(x_ranges_3_1.value, 2), name = _d[0], range = _d[1];
                    var start = range.start, end = range.end;
                    if (start == null || end == null || isNaN(start + end)) {
                        good_vals = false;
                        break;
                    }
                    xrs.set(name, { start: start, end: end });
                }
            }
            catch (e_13_1) {
                e_13 = { error: e_13_1 };
            }
            finally {
                try {
                    if (x_ranges_3_1 && !x_ranges_3_1.done && (_a = x_ranges_3.return))
                        _a.call(x_ranges_3);
                }
                finally {
                    if (e_13)
                        throw e_13.error;
                }
            }
            if (good_vals) {
                try {
                    for (var y_ranges_3 = (0, tslib_1.__values)(y_ranges), y_ranges_3_1 = y_ranges_3.next(); !y_ranges_3_1.done; y_ranges_3_1 = y_ranges_3.next()) {
                        var _e = (0, tslib_1.__read)(y_ranges_3_1.value, 2), name = _e[0], range = _e[1];
                        var start = range.start, end = range.end;
                        if (start == null || end == null || isNaN(start + end)) {
                            good_vals = false;
                            break;
                        }
                        yrs.set(name, { start: start, end: end });
                    }
                }
                catch (e_14_1) {
                    e_14 = { error: e_14_1 };
                }
                finally {
                    try {
                        if (y_ranges_3_1 && !y_ranges_3_1.done && (_b = y_ranges_3.return))
                            _b.call(y_ranges_3);
                    }
                    finally {
                        if (e_14)
                            throw e_14.error;
                    }
                }
            }
            if (good_vals)
                return { xrs: xrs, yrs: yrs };
            else {
                logging_1.logger.warn("could not set initial ranges");
                return null;
            }
        };
        RangeManager.prototype._update_ranges_together = function (range_info_iter) {
            var e_15, _a, e_16, _b;
            // Get weight needed to scale the diff of the range to honor interval limits
            var weight = 1.0;
            try {
                for (var range_info_iter_1 = (0, tslib_1.__values)(range_info_iter), range_info_iter_1_1 = range_info_iter_1.next(); !range_info_iter_1_1.done; range_info_iter_1_1 = range_info_iter_1.next()) {
                    var _c = (0, tslib_1.__read)(range_info_iter_1_1.value, 2), rng = _c[0], range_info = _c[1];
                    weight = Math.min(weight, this._get_weight_to_constrain_interval(rng, range_info));
                }
            }
            catch (e_15_1) {
                e_15 = { error: e_15_1 };
            }
            finally {
                try {
                    if (range_info_iter_1_1 && !range_info_iter_1_1.done && (_a = range_info_iter_1.return))
                        _a.call(range_info_iter_1);
                }
                finally {
                    if (e_15)
                        throw e_15.error;
                }
            }
            // Apply shared weight to all ranges
            if (weight < 1) {
                try {
                    for (var range_info_iter_2 = (0, tslib_1.__values)(range_info_iter), range_info_iter_2_1 = range_info_iter_2.next(); !range_info_iter_2_1.done; range_info_iter_2_1 = range_info_iter_2.next()) {
                        var _d = (0, tslib_1.__read)(range_info_iter_2_1.value, 2), rng = _d[0], range_info = _d[1];
                        range_info.start = weight * range_info.start + (1 - weight) * rng.start;
                        range_info.end = weight * range_info.end + (1 - weight) * rng.end;
                    }
                }
                catch (e_16_1) {
                    e_16 = { error: e_16_1 };
                }
                finally {
                    try {
                        if (range_info_iter_2_1 && !range_info_iter_2_1.done && (_b = range_info_iter_2.return))
                            _b.call(range_info_iter_2);
                    }
                    finally {
                        if (e_16)
                            throw e_16.error;
                    }
                }
            }
        };
        RangeManager.prototype._update_ranges_individually = function (range_info_iter, options) {
            var e_17, _a, e_18, _b;
            var panning = !!(options === null || options === void 0 ? void 0 : options.panning);
            var scrolling = !!(options === null || options === void 0 ? void 0 : options.scrolling);
            var hit_bound = false;
            try {
                for (var range_info_iter_3 = (0, tslib_1.__values)(range_info_iter), range_info_iter_3_1 = range_info_iter_3.next(); !range_info_iter_3_1.done; range_info_iter_3_1 = range_info_iter_3.next()) {
                    var _c = (0, tslib_1.__read)(range_info_iter_3_1.value, 2), rng = _c[0], range_info = _c[1];
                    // Limit range interval first. Note that for scroll events,
                    // the interval has already been limited for all ranges simultaneously
                    if (!scrolling) {
                        var weight = this._get_weight_to_constrain_interval(rng, range_info);
                        if (weight < 1) {
                            range_info.start = weight * range_info.start + (1 - weight) * rng.start;
                            range_info.end = weight * range_info.end + (1 - weight) * rng.end;
                        }
                    }
                    // Prevent range from going outside limits
                    // Also ensure that range keeps the same delta when panning/scrolling
                    if (rng.bounds != null && rng.bounds != "auto") { // check `auto` for type-checking purpose
                        var _d = (0, tslib_1.__read)(rng.bounds, 2), min = _d[0], max = _d[1];
                        var new_interval = Math.abs(range_info.end - range_info.start);
                        if (rng.is_reversed) {
                            if (min != null) {
                                if (min >= range_info.end) {
                                    hit_bound = true;
                                    range_info.end = min;
                                    if (panning || scrolling) {
                                        range_info.start = min + new_interval;
                                    }
                                }
                            }
                            if (max != null) {
                                if (max <= range_info.start) {
                                    hit_bound = true;
                                    range_info.start = max;
                                    if (panning || scrolling) {
                                        range_info.end = max - new_interval;
                                    }
                                }
                            }
                        }
                        else {
                            if (min != null) {
                                if (min >= range_info.start) {
                                    hit_bound = true;
                                    range_info.start = min;
                                    if (panning || scrolling) {
                                        range_info.end = min + new_interval;
                                    }
                                }
                            }
                            if (max != null) {
                                if (max <= range_info.end) {
                                    hit_bound = true;
                                    range_info.end = max;
                                    if (panning || scrolling) {
                                        range_info.start = max - new_interval;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (e_17_1) {
                e_17 = { error: e_17_1 };
            }
            finally {
                try {
                    if (range_info_iter_3_1 && !range_info_iter_3_1.done && (_a = range_info_iter_3.return))
                        _a.call(range_info_iter_3);
                }
                finally {
                    if (e_17)
                        throw e_17.error;
                }
            }
            // Cancel the event when hitting a bound while scrolling. This ensures that
            // the scroll-zoom tool maintains its focus position. Setting `maintain_focus`
            // to false results in a more "gliding" behavior, allowing one to
            // zoom out more smoothly, at the cost of losing the focus position.
            if (scrolling && hit_bound && (options === null || options === void 0 ? void 0 : options.maintain_focus))
                return;
            try {
                for (var range_info_iter_4 = (0, tslib_1.__values)(range_info_iter), range_info_iter_4_1 = range_info_iter_4.next(); !range_info_iter_4_1.done; range_info_iter_4_1 = range_info_iter_4.next()) {
                    var _e = (0, tslib_1.__read)(range_info_iter_4_1.value, 2), rng = _e[0], range_info = _e[1];
                    rng.have_updated_interactively = true;
                    if (rng.start != range_info.start || rng.end != range_info.end)
                        rng.setv(range_info);
                }
            }
            catch (e_18_1) {
                e_18 = { error: e_18_1 };
            }
            finally {
                try {
                    if (range_info_iter_4_1 && !range_info_iter_4_1.done && (_b = range_info_iter_4.return))
                        _b.call(range_info_iter_4);
                }
                finally {
                    if (e_18)
                        throw e_18.error;
                }
            }
        };
        RangeManager.prototype._get_weight_to_constrain_interval = function (rng, range_info) {
            // Get the weight by which a range-update can be applied
            // to still honor the interval limits (including the implicit
            // max interval imposed by the bounds)
            var min_interval = rng.min_interval;
            var max_interval = rng.max_interval;
            // Express bounds as a max_interval. By doing this, the application of
            // bounds and interval limits can be applied independent from each-other.
            if (rng.bounds != null && rng.bounds != "auto") { // check `auto` for type-checking purpose
                var _a = (0, tslib_1.__read)(rng.bounds, 2), min = _a[0], max = _a[1];
                if (min != null && max != null) {
                    var max_interval2 = Math.abs(max - min);
                    max_interval = max_interval != null ? Math.min(max_interval, max_interval2) : max_interval2;
                }
            }
            var weight = 1.0;
            if (min_interval != null || max_interval != null) {
                var old_interval = Math.abs(rng.end - rng.start);
                var new_interval = Math.abs(range_info.end - range_info.start);
                if (min_interval != null && min_interval > 0 && new_interval < min_interval) {
                    weight = (old_interval - min_interval) / (old_interval - new_interval);
                }
                if (max_interval != null && max_interval > 0 && new_interval > max_interval) {
                    weight = (max_interval - old_interval) / (new_interval - old_interval);
                }
                weight = Math.max(0.0, Math.min(1.0, weight));
            }
            return weight;
        };
        return RangeManager;
    }());
    exports.RangeManager = RangeManager;
    RangeManager.__name__ = "RangeManager";
},
/* models/plots/state_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var signaling_1 = require(130) /* ../../core/signaling */;
    var StateManager = /** @class */ (function () {
        function StateManager(parent, initial_state) {
            this.parent = parent;
            this.initial_state = initial_state;
            this.changed = new signaling_1.Signal0(this.parent, "state_changed");
            this.history = [];
            this.index = -1;
        }
        StateManager.prototype._do_state_change = function (index) {
            var state = this.history[index] != null ? this.history[index].state : this.initial_state;
            if (state.range != null)
                this.parent.update_range(state.range);
            if (state.selection != null)
                this.parent.update_selection(state.selection);
            return state;
        };
        StateManager.prototype.push = function (type, new_state) {
            var _a = this, history = _a.history, index = _a.index;
            var prev_state = history[index] != null ? history[index].state : {};
            var state = (0, tslib_1.__assign)((0, tslib_1.__assign)((0, tslib_1.__assign)({}, this.initial_state), prev_state), new_state);
            this.history = this.history.slice(0, this.index + 1);
            this.history.push({ type: type, state: state });
            this.index = this.history.length - 1;
            this.changed.emit();
        };
        StateManager.prototype.clear = function () {
            this.history = [];
            this.index = -1;
            this.changed.emit();
        };
        StateManager.prototype.undo = function () {
            if (this.can_undo) {
                this.index -= 1;
                var state = this._do_state_change(this.index);
                this.changed.emit();
                return state;
            }
            return null;
        };
        StateManager.prototype.redo = function () {
            if (this.can_redo) {
                this.index += 1;
                var state = this._do_state_change(this.index);
                this.changed.emit();
                return state;
            }
            return null;
        };
        Object.defineProperty(StateManager.prototype, "can_undo", {
            get: function () {
                return this.index >= 0;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(StateManager.prototype, "can_redo", {
            get: function () {
                return this.index < this.history.length - 1;
            },
            enumerable: false,
            configurable: true
        });
        return StateManager;
    }());
    exports.StateManager = StateManager;
    StateManager.__name__ = "StateManager";
},
/* models/plots/gmap_plot_canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var logging_1 = require(134) /* ../../core/logging */;
    var signaling_1 = require(130) /* ../../core/signaling */;
    var dom_1 = require(158) /* ../../core/dom */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    var color_1 = require(137) /* ../../core/util/color */;
    var plot_canvas_1 = require(447) /* ./plot_canvas */;
    var gmaps_ready = new signaling_1.Signal0({}, "gmaps_ready");
    var load_google_api = function (api_key, api_version) {
        window._bokeh_gmaps_callback = function () { return gmaps_ready.emit(); };
        var enc = encodeURIComponent;
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://maps.googleapis.com/maps/api/js?v=" + enc(api_version) + "&key=" + enc(api_key) + "&callback=_bokeh_gmaps_callback";
        document.body.appendChild(script);
    };
    var GMapPlotView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GMapPlotView, _super);
        function GMapPlotView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        GMapPlotView.prototype.initialize = function () {
            var _this = this;
            this.pause();
            _super.prototype.initialize.call(this);
            this._tiles_loaded = false;
            this.zoom_count = 0;
            var _a = this.model.map_options, zoom = _a.zoom, lat = _a.lat, lng = _a.lng;
            this.initial_zoom = zoom;
            this.initial_lat = lat;
            this.initial_lng = lng;
            if (!this.model.api_key) {
                var url = "https://developers.google.com/maps/documentation/javascript/get-api-key";
                logging_1.logger.error("api_key is required. See " + url + " for more information on how to obtain your own.");
            }
            if (typeof google === "undefined" || google.maps == null) {
                if (typeof window._bokeh_gmaps_callback === "undefined") {
                    var _b = this.model, api_key = _b.api_key, api_version = _b.api_version;
                    load_google_api(api_key, api_version);
                }
                gmaps_ready.connect(function () { return _this.request_paint("everything"); });
            }
            this.unpause();
        };
        GMapPlotView.prototype.remove = function () {
            (0, dom_1.remove)(this.map_el);
            _super.prototype.remove.call(this);
        };
        GMapPlotView.prototype.update_range = function (range_info, options) {
            var _a, _b;
            // RESET -------------------------
            if (range_info == null) {
                this.map.setCenter({ lat: this.initial_lat, lng: this.initial_lng });
                this.map.setOptions({ zoom: this.initial_zoom });
                _super.prototype.update_range.call(this, null, options);
                // PAN ----------------------------
            }
            else if (range_info.sdx != null || range_info.sdy != null) {
                this.map.panBy((_a = range_info.sdx) !== null && _a !== void 0 ? _a : 0, (_b = range_info.sdy) !== null && _b !== void 0 ? _b : 0);
                _super.prototype.update_range.call(this, range_info, options);
                // ZOOM ---------------------------
            }
            else if (range_info.factor != null) {
                // The zoom count decreases the sensitivity of the zoom. (We could make this user configurable)
                if (this.zoom_count !== 10) {
                    this.zoom_count += 1;
                    return;
                }
                this.zoom_count = 0;
                this.pause();
                _super.prototype.update_range.call(this, range_info, options);
                var zoom_change = range_info.factor < 0 ? -1 : 1;
                var old_map_zoom = this.map.getZoom();
                if (old_map_zoom != null) {
                    var new_map_zoom = old_map_zoom + zoom_change;
                    // Zooming out too far causes problems
                    if (new_map_zoom >= 2) {
                        this.map.setZoom(new_map_zoom);
                        // Check we haven't gone out of bounds, and if we have undo the zoom
                        var _c = (0, tslib_1.__read)(this._get_projected_bounds(), 2), proj_xstart = _c[0], proj_xend = _c[1];
                        if (proj_xend - proj_xstart < 0) {
                            this.map.setZoom(old_map_zoom);
                        }
                    }
                }
                this.unpause();
            }
            // Finally re-center
            this._set_bokeh_ranges();
        };
        GMapPlotView.prototype._build_map = function () {
            var _this = this;
            var maps = google.maps;
            this.map_types = {
                satellite: maps.MapTypeId.SATELLITE,
                terrain: maps.MapTypeId.TERRAIN,
                roadmap: maps.MapTypeId.ROADMAP,
                hybrid: maps.MapTypeId.HYBRID,
            };
            var mo = this.model.map_options;
            var map_options = {
                center: new maps.LatLng(mo.lat, mo.lng),
                zoom: mo.zoom,
                disableDefaultUI: true,
                mapTypeId: this.map_types[mo.map_type],
                scaleControl: mo.scale_control,
                tilt: mo.tilt,
            };
            if (mo.styles != null)
                map_options.styles = JSON.parse(mo.styles);
            // create the map with above options in div
            this.map_el = (0, dom_1.div)({ style: { position: "absolute" } });
            this.canvas_view.add_underlay(this.map_el);
            this.map = new maps.Map(this.map_el, map_options);
            // update bokeh ranges whenever the map idles, which should be after most UI action
            maps.event.addListener(this.map, "idle", function () { return _this._set_bokeh_ranges(); });
            // also need an event when bounds change so that map resizes trigger renders too
            maps.event.addListener(this.map, "bounds_changed", function () { return _this._set_bokeh_ranges(); });
            maps.event.addListenerOnce(this.map, "tilesloaded", function () { return _this._render_finished(); });
            // wire up listeners so that changes to properties are reflected
            this.connect(this.model.properties.map_options.change, function () { return _this._update_options(); });
            this.connect(this.model.map_options.properties.styles.change, function () { return _this._update_styles(); });
            this.connect(this.model.map_options.properties.lat.change, function () { return _this._update_center("lat"); });
            this.connect(this.model.map_options.properties.lng.change, function () { return _this._update_center("lng"); });
            this.connect(this.model.map_options.properties.zoom.change, function () { return _this._update_zoom(); });
            this.connect(this.model.map_options.properties.map_type.change, function () { return _this._update_map_type(); });
            this.connect(this.model.map_options.properties.scale_control.change, function () { return _this._update_scale_control(); });
            this.connect(this.model.map_options.properties.tilt.change, function () { return _this._update_tilt(); });
        };
        GMapPlotView.prototype._render_finished = function () {
            this._tiles_loaded = true;
            this.notify_finished();
        };
        GMapPlotView.prototype.has_finished = function () {
            return _super.prototype.has_finished.call(this) && this._tiles_loaded === true;
        };
        GMapPlotView.prototype._get_latlon_bounds = function () {
            var bounds = this.map.getBounds();
            var top_right = bounds.getNorthEast();
            var bottom_left = bounds.getSouthWest();
            var xstart = bottom_left.lng();
            var xend = top_right.lng();
            var ystart = bottom_left.lat();
            var yend = top_right.lat();
            return [xstart, xend, ystart, yend];
        };
        GMapPlotView.prototype._get_projected_bounds = function () {
            var _a = (0, tslib_1.__read)(this._get_latlon_bounds(), 4), xstart = _a[0], xend = _a[1], ystart = _a[2], yend = _a[3];
            var _b = (0, tslib_1.__read)(projections_1.wgs84_mercator.compute(xstart, ystart), 2), proj_xstart = _b[0], proj_ystart = _b[1];
            var _c = (0, tslib_1.__read)(projections_1.wgs84_mercator.compute(xend, yend), 2), proj_xend = _c[0], proj_yend = _c[1];
            return [proj_xstart, proj_xend, proj_ystart, proj_yend];
        };
        GMapPlotView.prototype._set_bokeh_ranges = function () {
            var _a = (0, tslib_1.__read)(this._get_projected_bounds(), 4), proj_xstart = _a[0], proj_xend = _a[1], proj_ystart = _a[2], proj_yend = _a[3];
            this.frame.x_range.setv({ start: proj_xstart, end: proj_xend });
            this.frame.y_range.setv({ start: proj_ystart, end: proj_yend });
        };
        GMapPlotView.prototype._update_center = function (fld) {
            var _a;
            var center = (_a = this.map.getCenter()) === null || _a === void 0 ? void 0 : _a.toJSON();
            if (center != null) {
                center[fld] = this.model.map_options[fld];
                this.map.setCenter(center);
                this._set_bokeh_ranges();
            }
        };
        GMapPlotView.prototype._update_map_type = function () {
            this.map.setOptions({ mapTypeId: this.map_types[this.model.map_options.map_type] });
        };
        GMapPlotView.prototype._update_scale_control = function () {
            this.map.setOptions({ scaleControl: this.model.map_options.scale_control });
        };
        GMapPlotView.prototype._update_tilt = function () {
            this.map.setOptions({ tilt: this.model.map_options.tilt });
        };
        GMapPlotView.prototype._update_options = function () {
            this._update_styles();
            this._update_center("lat");
            this._update_center("lng");
            this._update_zoom();
            this._update_map_type();
        };
        GMapPlotView.prototype._update_styles = function () {
            this.map.setOptions({ styles: JSON.parse(this.model.map_options.styles) });
        };
        GMapPlotView.prototype._update_zoom = function () {
            this.map.setOptions({ zoom: this.model.map_options.zoom });
            this._set_bokeh_ranges();
        };
        // this method is expected and called by PlotView.render
        GMapPlotView.prototype._map_hook = function (_ctx, frame_box) {
            if (this.map == null && typeof google !== "undefined" && google.maps != null)
                this._build_map();
            if (this.map_el != null) {
                var _a = (0, tslib_1.__read)(frame_box, 4), left = _a[0], top = _a[1], width = _a[2], height = _a[3];
                this.map_el.style.top = top + "px";
                this.map_el.style.left = left + "px";
                this.map_el.style.width = width + "px";
                this.map_el.style.height = height + "px";
            }
        };
        // this overrides the standard _paint_empty to make the inner canvas transparent
        GMapPlotView.prototype._paint_empty = function (ctx, frame_box) {
            var ow = this.layout.bbox.width;
            var oh = this.layout.bbox.height;
            var _a = (0, tslib_1.__read)(frame_box, 4), left = _a[0], top = _a[1], iw = _a[2], ih = _a[3];
            ctx.clearRect(0, 0, ow, oh);
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.lineTo(0, oh);
            ctx.lineTo(ow, oh);
            ctx.lineTo(ow, 0);
            ctx.lineTo(0, 0);
            ctx.moveTo(left, top);
            ctx.lineTo(left + iw, top);
            ctx.lineTo(left + iw, top + ih);
            ctx.lineTo(left, top + ih);
            ctx.lineTo(left, top);
            ctx.closePath();
            if (this.model.border_fill_color != null) {
                ctx.fillStyle = (0, color_1.color2css)(this.model.border_fill_color);
                ctx.fill();
            }
        };
        return GMapPlotView;
    }(plot_canvas_1.PlotView));
    exports.GMapPlotView = GMapPlotView;
    GMapPlotView.__name__ = "GMapPlotView";
},
/* models/policies/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    (0, tslib_1.__exportStar)(require(247) /* ./labeling */, exports);
},
/* models/renderers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var glyph_renderer_1 = require(290) /* ./glyph_renderer */;
    __esExport("GlyphRenderer", glyph_renderer_1.GlyphRenderer);
    var graph_renderer_1 = require(454) /* ./graph_renderer */;
    __esExport("GraphRenderer", graph_renderer_1.GraphRenderer);
    var guide_renderer_1 = require(244) /* ./guide_renderer */;
    __esExport("GuideRenderer", guide_renderer_1.GuideRenderer);
    var renderer_1 = require(156) /* ./renderer */;
    __esExport("Renderer", renderer_1.Renderer);
    __esExport("RendererGroup", renderer_1.RendererGroup);
},
/* models/renderers/graph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var data_renderer_1 = require(291) /* ./data_renderer */;
    var glyph_renderer_1 = require(290) /* ./glyph_renderer */;
    var layout_provider_1 = require(418) /* ../graphs/layout_provider */;
    var graph_hit_test_policy_1 = require(417) /* ../graphs/graph_hit_test_policy */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var xy_glyph_1 = require(293) /* ../glyphs/xy_glyph */;
    var multi_line_1 = require(398) /* ../glyphs/multi_line */;
    var patches_1 = require(401) /* ../glyphs/patches */;
    var GraphRendererView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GraphRendererView, _super);
        function GraphRendererView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(GraphRendererView.prototype, "glyph_view", {
            get: function () {
                return this.node_view.glyph;
            },
            enumerable: false,
            configurable: true
        });
        GraphRendererView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var parent, _b, edge_renderer, node_renderer, _c, _d;
                return (0, tslib_1.__generator)(this, function (_e) {
                    switch (_e.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _e.sent();
                            this.apply_coordinates();
                            parent = this.parent;
                            _b = this.model, edge_renderer = _b.edge_renderer, node_renderer = _b.node_renderer;
                            _c = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(edge_renderer, { parent: parent })];
                        case 2:
                            _c.edge_view = _e.sent();
                            _d = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(node_renderer, { parent: parent })];
                        case 3:
                            _d.node_view = _e.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        GraphRendererView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.layout_provider.change, function () {
                _this.apply_coordinates();
                _this.edge_view.set_data();
                _this.node_view.set_data();
                _this.request_render();
            });
        };
        GraphRendererView.prototype.apply_coordinates = function () {
            var _b = this.model, edge_renderer = _b.edge_renderer, node_renderer = _b.node_renderer;
            // TODO: XsYsGlyph or something
            if (!(edge_renderer.glyph instanceof multi_line_1.MultiLine || edge_renderer.glyph instanceof patches_1.Patches)) {
                throw new Error(this + ".edge_renderer.glyph must be a MultiLine glyph");
            }
            if (!(node_renderer.glyph instanceof xy_glyph_1.XYGlyph)) {
                throw new Error(this + ".node_renderer.glyph must be a XYGlyph glyph");
            }
            var edge_coords = this.model.layout_provider.edge_coordinates;
            var node_coords = this.model.layout_provider.node_coordinates;
            edge_renderer.glyph.properties.xs.internal = true;
            edge_renderer.glyph.properties.ys.internal = true;
            node_renderer.glyph.properties.x.internal = true;
            node_renderer.glyph.properties.y.internal = true;
            edge_renderer.glyph.xs = { expr: edge_coords.x };
            edge_renderer.glyph.ys = { expr: edge_coords.y };
            node_renderer.glyph.x = { expr: node_coords.x };
            node_renderer.glyph.y = { expr: node_coords.y };
            this.model.edge_renderer = edge_renderer;
            this.model.node_renderer = node_renderer;
        };
        GraphRendererView.prototype.remove = function () {
            this.edge_view.remove();
            this.node_view.remove();
            _super.prototype.remove.call(this);
        };
        GraphRendererView.prototype._render = function () {
            this.edge_view.render();
            this.node_view.render();
        };
        GraphRendererView.prototype.renderer_view = function (renderer) {
            if (renderer instanceof glyph_renderer_1.GlyphRenderer) {
                if (renderer == this.edge_view.model)
                    return this.edge_view;
                if (renderer == this.node_view.model)
                    return this.node_view;
            }
            return _super.prototype.renderer_view.call(this, renderer);
        };
        return GraphRendererView;
    }(data_renderer_1.DataRendererView));
    exports.GraphRendererView = GraphRendererView;
    GraphRendererView.__name__ = "GraphRendererView";
    var GraphRenderer = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GraphRenderer, _super);
        function GraphRenderer(attrs) {
            return _super.call(this, attrs) || this;
        }
        GraphRenderer.prototype.get_selection_manager = function () {
            return this.node_renderer.data_source.selection_manager;
        };
        return GraphRenderer;
    }(data_renderer_1.DataRenderer));
    exports.GraphRenderer = GraphRenderer;
    _a = GraphRenderer;
    GraphRenderer.__name__ = "GraphRenderer";
    (function () {
        _a.prototype.default_view = GraphRendererView;
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                layout_provider: [Ref(layout_provider_1.LayoutProvider)],
                node_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
                edge_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
                selection_policy: [Ref(graph_hit_test_policy_1.GraphHitTestPolicy), function () { return new graph_hit_test_policy_1.NodesOnly(); }],
                inspection_policy: [Ref(graph_hit_test_policy_1.GraphHitTestPolicy), function () { return new graph_hit_test_policy_1.NodesOnly(); }],
            });
        });
    })();
},
/* models/selections/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    (0, tslib_1.__exportStar)(require(189) /* ./interaction_policy */, exports);
    var selection_1 = require(187) /* ./selection */;
    __esExport("Selection", selection_1.Selection);
},
/* models/sources/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var server_sent_data_source_1 = require(457) /* ./server_sent_data_source */;
    __esExport("ServerSentDataSource", server_sent_data_source_1.ServerSentDataSource);
    var ajax_data_source_1 = require(459) /* ./ajax_data_source */;
    __esExport("AjaxDataSource", ajax_data_source_1.AjaxDataSource);
    var column_data_source_1 = require(190) /* ./column_data_source */;
    __esExport("ColumnDataSource", column_data_source_1.ColumnDataSource);
    var columnar_data_source_1 = require(185) /* ./columnar_data_source */;
    __esExport("ColumnarDataSource", columnar_data_source_1.ColumnarDataSource);
    var cds_view_1 = require(305) /* ./cds_view */;
    __esExport("CDSView", cds_view_1.CDSView);
    var data_source_1 = require(186) /* ./data_source */;
    __esExport("DataSource", data_source_1.DataSource);
    var geojson_data_source_1 = require(460) /* ./geojson_data_source */;
    __esExport("GeoJSONDataSource", geojson_data_source_1.GeoJSONDataSource);
    var web_data_source_1 = require(458) /* ./web_data_source */;
    __esExport("WebDataSource", web_data_source_1.WebDataSource);
},
/* models/sources/server_sent_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var web_data_source_1 = require(458) /* ./web_data_source */;
    var ServerSentDataSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ServerSentDataSource, _super);
        function ServerSentDataSource(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.initialized = false;
            return _this;
        }
        ServerSentDataSource.prototype.setup = function () {
            var _this = this;
            if (!this.initialized) {
                this.initialized = true;
                var source = new EventSource(this.data_url);
                source.onmessage = function (event) {
                    var _a;
                    _this.load_data(JSON.parse(event.data), _this.mode, (_a = _this.max_size) !== null && _a !== void 0 ? _a : undefined);
                };
            }
        };
        return ServerSentDataSource;
    }(web_data_source_1.WebDataSource));
    exports.ServerSentDataSource = ServerSentDataSource;
    ServerSentDataSource.__name__ = "ServerSentDataSource";
},
/* models/sources/web_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var column_data_source_1 = require(190) /* ./column_data_source */;
    var enums_1 = require(135) /* ../../core/enums */;
    var WebDataSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WebDataSource, _super);
        function WebDataSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        WebDataSource.prototype.get_column = function (colname) {
            var column = this.data[colname];
            return column != null ? column : [];
        };
        WebDataSource.prototype.get_length = function () {
            var _b;
            return (_b = _super.prototype.get_length.call(this)) !== null && _b !== void 0 ? _b : 0;
        };
        WebDataSource.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.setup();
        };
        WebDataSource.prototype.load_data = function (raw_data, mode, max_size) {
            var e_1, _b;
            var adapter = this.adapter;
            var data;
            if (adapter != null)
                data = adapter.execute(this, { response: raw_data });
            else
                data = raw_data;
            switch (mode) {
                case "replace": {
                    this.data = data;
                    break;
                }
                case "append": {
                    var original_data = this.data;
                    try {
                        for (var _c = (0, tslib_1.__values)(this.columns()), _d = _c.next(); !_d.done; _d = _c.next()) {
                            var column = _d.value;
                            // XXX: support typed arrays
                            var old_col = Array.from(original_data[column]);
                            var new_col = Array.from(data[column]);
                            var array = old_col.concat(new_col);
                            data[column] = max_size != null ? array.slice(-max_size) : array;
                        }
                    }
                    catch (e_1_1) {
                        e_1 = { error: e_1_1 };
                    }
                    finally {
                        try {
                            if (_d && !_d.done && (_b = _c.return))
                                _b.call(_c);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                    }
                    this.data = data;
                    break;
                }
            }
        };
        return WebDataSource;
    }(column_data_source_1.ColumnDataSource));
    exports.WebDataSource = WebDataSource;
    _a = WebDataSource;
    WebDataSource.__name__ = "WebDataSource";
    (function () {
        _a.define(function (_b) {
            var Any = _b.Any, Int = _b.Int, String = _b.String, Nullable = _b.Nullable;
            return ({
                max_size: [Nullable(Int), null],
                mode: [enums_1.UpdateMode, "replace"],
                adapter: [Nullable(Any /*TODO*/), null],
                data_url: [String],
            });
        });
    })();
},
/* models/sources/ajax_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var web_data_source_1 = require(458) /* ./web_data_source */;
    var enums_1 = require(135) /* ../../core/enums */;
    var logging_1 = require(134) /* ../../core/logging */;
    var object_1 = require(128) /* ../../core/util/object */;
    var AjaxDataSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(AjaxDataSource, _super);
        function AjaxDataSource(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.interval = null;
            _this.initialized = false;
            return _this;
        }
        AjaxDataSource.prototype.destroy = function () {
            if (this.interval != null)
                clearInterval(this.interval);
            _super.prototype.destroy.call(this);
        };
        AjaxDataSource.prototype.setup = function () {
            var _this = this;
            if (!this.initialized) {
                this.initialized = true;
                this.get_data(this.mode);
                if (this.polling_interval != null) {
                    var callback = function () { return _this.get_data(_this.mode, _this.max_size, _this.if_modified); };
                    this.interval = setInterval(callback, this.polling_interval);
                }
            }
        };
        AjaxDataSource.prototype.get_data = function (mode, max_size, _if_modified) {
            var _this = this;
            if (max_size === void 0) {
                max_size = null;
            }
            if (_if_modified === void 0) {
                _if_modified = false;
            }
            var xhr = this.prepare_request();
            // TODO: if_modified
            xhr.addEventListener("load", function () { return _this.do_load(xhr, mode, max_size !== null && max_size !== void 0 ? max_size : undefined); });
            xhr.addEventListener("error", function () { return _this.do_error(xhr); });
            xhr.send();
        };
        AjaxDataSource.prototype.prepare_request = function () {
            var e_1, _b;
            var xhr = new XMLHttpRequest();
            xhr.open(this.method, this.data_url, true);
            xhr.withCredentials = false;
            xhr.setRequestHeader("Content-Type", this.content_type);
            var http_headers = this.http_headers;
            try {
                for (var _c = (0, tslib_1.__values)((0, object_1.entries)(http_headers)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), name = _e[0], value = _e[1];
                    xhr.setRequestHeader(name, value);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return xhr;
        };
        AjaxDataSource.prototype.do_load = function (xhr, mode, max_size) {
            if (xhr.status === 200) {
                var raw_data = JSON.parse(xhr.responseText);
                this.load_data(raw_data, mode, max_size);
            }
        };
        AjaxDataSource.prototype.do_error = function (xhr) {
            logging_1.logger.error("Failed to fetch JSON from " + this.data_url + " with code " + xhr.status);
        };
        return AjaxDataSource;
    }(web_data_source_1.WebDataSource));
    exports.AjaxDataSource = AjaxDataSource;
    _a = AjaxDataSource;
    AjaxDataSource.__name__ = "AjaxDataSource";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Int = _b.Int, String = _b.String, Dict = _b.Dict, Nullable = _b.Nullable;
            return ({
                polling_interval: [Nullable(Int), null],
                content_type: [String, "application/json"],
                http_headers: [Dict(String), {}],
                method: [enums_1.HTTPMethod, "POST"],
                if_modified: [Boolean, false],
            });
        });
    })();
},
/* models/sources/geojson_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var columnar_data_source_1 = require(185) /* ./columnar_data_source */;
    var logging_1 = require(134) /* ../../core/logging */;
    var array_1 = require(126) /* ../../core/util/array */;
    var object_1 = require(128) /* ../../core/util/object */;
    function orNaN(v) {
        return v != null ? v : NaN;
    }
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var GeoJSONDataSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(GeoJSONDataSource, _super);
        function GeoJSONDataSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        GeoJSONDataSource.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._update_data();
        };
        GeoJSONDataSource.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.properties.geojson.change, function () { return _this._update_data(); });
        };
        GeoJSONDataSource.prototype._update_data = function () {
            this.data = this.geojson_to_column_data();
        };
        GeoJSONDataSource.prototype._get_new_list_array = function (length) {
            return (0, array_1.range)(0, length).map(function (_i) { return []; });
        };
        GeoJSONDataSource.prototype._get_new_nan_array = function (length) {
            return (0, array_1.range)(0, length).map(function (_i) { return NaN; });
        };
        GeoJSONDataSource.prototype._add_properties = function (item, data, i, item_count) {
            var e_1, _b;
            var _c;
            var properties = (_c = item.properties) !== null && _c !== void 0 ? _c : {};
            try {
                for (var _d = (0, tslib_1.__values)((0, object_1.entries)(properties)), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var _f = (0, tslib_1.__read)(_e.value, 2), property = _f[0], value = _f[1];
                    if (!hasOwnProperty.call(data, property))
                        data[property] = this._get_new_nan_array(item_count);
                    // orNaN necessary here to prevent null values from ending up in the column
                    data[property][i] = orNaN(value);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        GeoJSONDataSource.prototype._add_geometry = function (geometry, data, i) {
            var e_2, _b;
            function flatten(acc, item) {
                return acc.concat([[NaN, NaN, NaN]]).concat(item);
            }
            switch (geometry.type) {
                case "Point": {
                    var _c = (0, tslib_1.__read)(geometry.coordinates, 3), x = _c[0], y = _c[1], z = _c[2];
                    data.x[i] = x;
                    data.y[i] = y;
                    data.z[i] = orNaN(z);
                    break;
                }
                case "LineString": {
                    var coordinates = geometry.coordinates;
                    for (var j = 0; j < coordinates.length; j++) {
                        var _d = (0, tslib_1.__read)(coordinates[j], 3), x = _d[0], y = _d[1], z = _d[2];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "Polygon": {
                    if (geometry.coordinates.length > 1)
                        logging_1.logger.warn("Bokeh does not support Polygons with holes in, only exterior ring used.");
                    var exterior_ring = geometry.coordinates[0];
                    for (var j = 0; j < exterior_ring.length; j++) {
                        var _e = (0, tslib_1.__read)(exterior_ring[j], 3), x = _e[0], y = _e[1], z = _e[2];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "MultiPoint": {
                    logging_1.logger.warn("MultiPoint not supported in Bokeh");
                    break;
                }
                case "MultiLineString": {
                    var coordinates = geometry.coordinates.reduce(flatten);
                    for (var j = 0; j < coordinates.length; j++) {
                        var _f = (0, tslib_1.__read)(coordinates[j], 3), x = _f[0], y = _f[1], z = _f[2];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "MultiPolygon": {
                    var exterior_rings = [];
                    try {
                        for (var _g = (0, tslib_1.__values)(geometry.coordinates), _h = _g.next(); !_h.done; _h = _g.next()) {
                            var polygon = _h.value;
                            if (polygon.length > 1)
                                logging_1.logger.warn("Bokeh does not support Polygons with holes in, only exterior ring used.");
                            exterior_rings.push(polygon[0]);
                        }
                    }
                    catch (e_2_1) {
                        e_2 = { error: e_2_1 };
                    }
                    finally {
                        try {
                            if (_h && !_h.done && (_b = _g.return))
                                _b.call(_g);
                        }
                        finally {
                            if (e_2)
                                throw e_2.error;
                        }
                    }
                    var coordinates = exterior_rings.reduce(flatten);
                    for (var j = 0; j < coordinates.length; j++) {
                        var _j = (0, tslib_1.__read)(coordinates[j], 3), x = _j[0], y = _j[1], z = _j[2];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                default:
                    throw new Error("Invalid GeoJSON geometry type: " + geometry.type);
            }
        };
        GeoJSONDataSource.prototype.geojson_to_column_data = function () {
            var e_3, _b, e_4, _c, e_5, _d;
            var geojson = JSON.parse(this.geojson);
            var items;
            switch (geojson.type) {
                case "GeometryCollection": {
                    if (geojson.geometries == null)
                        throw new Error("No geometries found in GeometryCollection");
                    if (geojson.geometries.length === 0)
                        throw new Error("geojson.geometries must have one or more items");
                    items = geojson.geometries;
                    break;
                }
                case "FeatureCollection": {
                    if (geojson.features == null)
                        throw new Error("No features found in FeaturesCollection");
                    if (geojson.features.length == 0)
                        throw new Error("geojson.features must have one or more items");
                    items = geojson.features;
                    break;
                }
                default:
                    throw new Error("Bokeh only supports type GeometryCollection and FeatureCollection at top level");
            }
            var item_count = 0;
            try {
                for (var items_1 = (0, tslib_1.__values)(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
                    var item = items_1_1.value;
                    var geometry = item.type === "Feature" ? item.geometry : item;
                    if (geometry.type == "GeometryCollection")
                        item_count += geometry.geometries.length;
                    else
                        item_count += 1;
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (items_1_1 && !items_1_1.done && (_b = items_1.return))
                        _b.call(items_1);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            var data = {
                x: this._get_new_nan_array(item_count),
                y: this._get_new_nan_array(item_count),
                z: this._get_new_nan_array(item_count),
                xs: this._get_new_list_array(item_count),
                ys: this._get_new_list_array(item_count),
                zs: this._get_new_list_array(item_count),
            };
            var arr_index = 0;
            try {
                for (var items_2 = (0, tslib_1.__values)(items), items_2_1 = items_2.next(); !items_2_1.done; items_2_1 = items_2.next()) {
                    var item = items_2_1.value;
                    var geometry = item.type == "Feature" ? item.geometry : item;
                    if (geometry.type == "GeometryCollection") {
                        try {
                            for (var _e = (e_5 = void 0, (0, tslib_1.__values)(geometry.geometries)), _f = _e.next(); !_f.done; _f = _e.next()) {
                                var g = _f.value;
                                this._add_geometry(g, data, arr_index);
                                if (item.type === "Feature")
                                    this._add_properties(item, data, arr_index, item_count);
                                arr_index += 1;
                            }
                        }
                        catch (e_5_1) {
                            e_5 = { error: e_5_1 };
                        }
                        finally {
                            try {
                                if (_f && !_f.done && (_d = _e.return))
                                    _d.call(_e);
                            }
                            finally {
                                if (e_5)
                                    throw e_5.error;
                            }
                        }
                    }
                    else {
                        this._add_geometry(geometry, data, arr_index);
                        if (item.type === "Feature")
                            this._add_properties(item, data, arr_index, item_count);
                        arr_index += 1;
                    }
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (items_2_1 && !items_2_1.done && (_c = items_2.return))
                        _c.call(items_2);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            return data;
        };
        return GeoJSONDataSource;
    }(columnar_data_source_1.ColumnarDataSource));
    exports.GeoJSONDataSource = GeoJSONDataSource;
    _a = GeoJSONDataSource;
    GeoJSONDataSource.__name__ = "GeoJSONDataSource";
    (function () {
        _a.define(function (_b) {
            var String = _b.String;
            return ({
                geojson: [String],
            });
        });
        _a.internal(function (_b) {
            var Dict = _b.Dict, Arrayable = _b.Arrayable;
            return ({
                data: [Dict(Arrayable), {}],
            });
        });
    })();
},
/* models/tiles/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var bbox_tile_source_1 = require(462) /* ./bbox_tile_source */;
    __esExport("BBoxTileSource", bbox_tile_source_1.BBoxTileSource);
    var mercator_tile_source_1 = require(463) /* ./mercator_tile_source */;
    __esExport("MercatorTileSource", mercator_tile_source_1.MercatorTileSource);
    var quadkey_tile_source_1 = require(466) /* ./quadkey_tile_source */;
    __esExport("QUADKEYTileSource", quadkey_tile_source_1.QUADKEYTileSource);
    var tile_renderer_1 = require(467) /* ./tile_renderer */;
    __esExport("TileRenderer", tile_renderer_1.TileRenderer);
    var tile_source_1 = require(464) /* ./tile_source */;
    __esExport("TileSource", tile_source_1.TileSource);
    var tms_tile_source_1 = require(470) /* ./tms_tile_source */;
    __esExport("TMSTileSource", tms_tile_source_1.TMSTileSource);
    var wmts_tile_source_1 = require(468) /* ./wmts_tile_source */;
    __esExport("WMTSTileSource", wmts_tile_source_1.WMTSTileSource);
},
/* models/tiles/bbox_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var mercator_tile_source_1 = require(463) /* ./mercator_tile_source */;
    var BBoxTileSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BBoxTileSource, _super);
        function BBoxTileSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        BBoxTileSource.prototype.get_image_url = function (x, y, z) {
            var _b, _c;
            var image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            var xmax, xmin, ymax, ymin;
            if (this.use_latlon)
                _b = (0, tslib_1.__read)(this.get_tile_geographic_bounds(x, y, z), 4), xmin = _b[0], ymin = _b[1], xmax = _b[2], ymax = _b[3];
            else
                _c = (0, tslib_1.__read)(this.get_tile_meter_bounds(x, y, z), 4), xmin = _c[0], ymin = _c[1], xmax = _c[2], ymax = _c[3];
            return image_url
                .replace("{XMIN}", xmin.toString())
                .replace("{YMIN}", ymin.toString())
                .replace("{XMAX}", xmax.toString())
                .replace("{YMAX}", ymax.toString());
        };
        return BBoxTileSource;
    }(mercator_tile_source_1.MercatorTileSource));
    exports.BBoxTileSource = BBoxTileSource;
    _a = BBoxTileSource;
    BBoxTileSource.__name__ = "BBoxTileSource";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                use_latlon: [Boolean, false],
            });
        });
    })();
},
/* models/tiles/mercator_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var tile_source_1 = require(464) /* ./tile_source */;
    var array_1 = require(126) /* ../../core/util/array */;
    var tile_utils_1 = require(465) /* ./tile_utils */;
    var MercatorTileSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(MercatorTileSource, _super);
        function MercatorTileSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        MercatorTileSource.prototype.initialize = function () {
            var _this = this;
            _super.prototype.initialize.call(this);
            this._resolutions = (0, array_1.range)(this.min_zoom, this.max_zoom + 1).map(function (z) { return _this.get_resolution(z); });
        };
        MercatorTileSource.prototype._computed_initial_resolution = function () {
            if (this.initial_resolution != null)
                return this.initial_resolution;
            else {
                // TODO testing 2015-11-17, if this codepath is used it seems
                // to use 100% cpu and wedge Chrome
                return (2 * Math.PI * 6378137) / this.tile_size;
            }
        };
        MercatorTileSource.prototype.is_valid_tile = function (x, y, z) {
            if (!this.wrap_around) {
                if (x < 0 || x >= Math.pow(2, z))
                    return false;
            }
            if (y < 0 || y >= Math.pow(2, z))
                return false;
            return true;
        };
        MercatorTileSource.prototype.parent_by_tile_xyz = function (x, y, z) {
            var quadkey = this.tile_xyz_to_quadkey(x, y, z);
            var parent_quadkey = quadkey.substring(0, quadkey.length - 1);
            return this.quadkey_to_tile_xyz(parent_quadkey);
        };
        MercatorTileSource.prototype.get_resolution = function (level) {
            return this._computed_initial_resolution() / Math.pow(2, level);
        };
        MercatorTileSource.prototype.get_resolution_by_extent = function (extent, height, width) {
            var x_rs = (extent[2] - extent[0]) / width;
            var y_rs = (extent[3] - extent[1]) / height;
            return [x_rs, y_rs];
        };
        MercatorTileSource.prototype.get_level_by_extent = function (extent, height, width) {
            var e_1, _b;
            var x_rs = (extent[2] - extent[0]) / width;
            var y_rs = (extent[3] - extent[1]) / height;
            var resolution = Math.max(x_rs, y_rs);
            var i = 0;
            try {
                for (var _c = (0, tslib_1.__values)(this._resolutions), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var r = _d.value;
                    if (resolution > r) {
                        if (i == 0)
                            return 0;
                        if (i > 0)
                            return i - 1;
                    }
                    i += 1;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            // otherwise return the highest available resolution
            return (i - 1);
        };
        MercatorTileSource.prototype.get_closest_level_by_extent = function (extent, height, width) {
            var x_rs = (extent[2] - extent[0]) / width;
            var y_rs = (extent[3] - extent[1]) / height;
            var resolution = Math.max(x_rs, y_rs);
            var closest = this._resolutions.reduce(function (previous, current) {
                if (Math.abs(current - resolution) < Math.abs(previous - resolution))
                    return current;
                else
                    return previous;
            });
            return this._resolutions.indexOf(closest);
        };
        MercatorTileSource.prototype.snap_to_zoom_level = function (extent, height, width, level) {
            var _b = (0, tslib_1.__read)(extent, 4), xmin = _b[0], ymin = _b[1], xmax = _b[2], ymax = _b[3];
            var desired_res = this._resolutions[level];
            var desired_x_delta = width * desired_res;
            var desired_y_delta = height * desired_res;
            if (!this.snap_to_zoom) {
                var xscale = (xmax - xmin) / desired_x_delta;
                var yscale = (ymax - ymin) / desired_y_delta;
                if (xscale > yscale) {
                    desired_x_delta = (xmax - xmin);
                    desired_y_delta = desired_y_delta * xscale;
                }
                else {
                    desired_x_delta = desired_x_delta * yscale;
                    desired_y_delta = (ymax - ymin);
                }
            }
            var x_adjust = (desired_x_delta - (xmax - xmin)) / 2;
            var y_adjust = (desired_y_delta - (ymax - ymin)) / 2;
            return [xmin - x_adjust, ymin - y_adjust, xmax + x_adjust, ymax + y_adjust];
        };
        MercatorTileSource.prototype.tms_to_wmts = function (x, y, z) {
            // Note this works both ways
            return [x, Math.pow(2, z) - 1 - y, z];
        };
        MercatorTileSource.prototype.wmts_to_tms = function (x, y, z) {
            // Note this works both ways
            return [x, Math.pow(2, z) - 1 - y, z];
        };
        MercatorTileSource.prototype.pixels_to_meters = function (px, py, level) {
            var res = this.get_resolution(level);
            var mx = (px * res) - this.x_origin_offset;
            var my = (py * res) - this.y_origin_offset;
            return [mx, my];
        };
        MercatorTileSource.prototype.meters_to_pixels = function (mx, my, level) {
            var res = this.get_resolution(level);
            var px = (mx + this.x_origin_offset) / res;
            var py = (my + this.y_origin_offset) / res;
            return [px, py];
        };
        MercatorTileSource.prototype.pixels_to_tile = function (px, py) {
            var tx = Math.ceil(px / this.tile_size);
            tx = tx === 0 ? tx : tx - 1;
            var ty = Math.max(Math.ceil(py / this.tile_size) - 1, 0);
            return [tx, ty];
        };
        MercatorTileSource.prototype.pixels_to_raster = function (px, py, level) {
            var mapSize = this.tile_size << level;
            return [px, mapSize - py];
        };
        MercatorTileSource.prototype.meters_to_tile = function (mx, my, level) {
            var _b = (0, tslib_1.__read)(this.meters_to_pixels(mx, my, level), 2), px = _b[0], py = _b[1];
            return this.pixels_to_tile(px, py);
        };
        MercatorTileSource.prototype.get_tile_meter_bounds = function (tx, ty, level) {
            // expects tms styles coordinates (bottom-left origin)
            var _b = (0, tslib_1.__read)(this.pixels_to_meters(tx * this.tile_size, ty * this.tile_size, level), 2), xmin = _b[0], ymin = _b[1];
            var _c = (0, tslib_1.__read)(this.pixels_to_meters((tx + 1) * this.tile_size, (ty + 1) * this.tile_size, level), 2), xmax = _c[0], ymax = _c[1];
            return [xmin, ymin, xmax, ymax];
        };
        MercatorTileSource.prototype.get_tile_geographic_bounds = function (tx, ty, level) {
            var bounds = this.get_tile_meter_bounds(tx, ty, level);
            var _b = (0, tslib_1.__read)((0, tile_utils_1.meters_extent_to_geographic)(bounds), 4), minLon = _b[0], minLat = _b[1], maxLon = _b[2], maxLat = _b[3];
            return [minLon, minLat, maxLon, maxLat];
        };
        MercatorTileSource.prototype.get_tiles_by_extent = function (extent, level, tile_border) {
            if (tile_border === void 0) {
                tile_border = 1;
            }
            // unpack extent and convert to tile coordinates
            var _b = (0, tslib_1.__read)(extent, 4), xmin = _b[0], ymin = _b[1], xmax = _b[2], ymax = _b[3];
            var _c = (0, tslib_1.__read)(this.meters_to_tile(xmin, ymin, level), 2), txmin = _c[0], tymin = _c[1];
            var _d = (0, tslib_1.__read)(this.meters_to_tile(xmax, ymax, level), 2), txmax = _d[0], tymax = _d[1];
            // add tiles which border
            txmin -= tile_border;
            tymin -= tile_border;
            txmax += tile_border;
            tymax += tile_border;
            var tiles = [];
            for (var ty = tymax; ty >= tymin; ty--) {
                for (var tx = txmin; tx <= txmax; tx++) {
                    if (this.is_valid_tile(tx, ty, level))
                        tiles.push([tx, ty, level, this.get_tile_meter_bounds(tx, ty, level)]);
                }
            }
            this.sort_tiles_from_center(tiles, [txmin, tymin, txmax, tymax]);
            return tiles;
        };
        MercatorTileSource.prototype.quadkey_to_tile_xyz = function (quadKey) {
            /**
             * Computes tile x, y and z values based on quadKey.
             */
            var tileX = 0;
            var tileY = 0;
            var tileZ = quadKey.length;
            for (var i = tileZ; i > 0; i--) {
                var value = quadKey.charAt(tileZ - i);
                var mask = 1 << (i - 1);
                switch (value) {
                    case "0":
                        continue;
                    case "1":
                        tileX |= mask;
                        break;
                    case "2":
                        tileY |= mask;
                        break;
                    case "3":
                        tileX |= mask;
                        tileY |= mask;
                        break;
                    default:
                        throw new TypeError("Invalid Quadkey: " + quadKey);
                }
            }
            return [tileX, tileY, tileZ];
        };
        MercatorTileSource.prototype.tile_xyz_to_quadkey = function (x, y, z) {
            /*
             * Computes quadkey value based on tile x, y and z values.
             */
            var quadkey = "";
            for (var i = z; i > 0; i--) {
                var mask = 1 << (i - 1);
                var digit = 0;
                if ((x & mask) !== 0) {
                    digit += 1;
                }
                if ((y & mask) !== 0) {
                    digit += 2;
                }
                quadkey += digit.toString();
            }
            return quadkey;
        };
        MercatorTileSource.prototype.children_by_tile_xyz = function (x, y, z) {
            var quadkey = this.tile_xyz_to_quadkey(x, y, z);
            var child_tile_xyz = [];
            for (var i = 0; i <= 3; i++) {
                var _b = (0, tslib_1.__read)(this.quadkey_to_tile_xyz(quadkey + i.toString()), 3), x_1 = _b[0], y_1 = _b[1], z_1 = _b[2];
                var b = this.get_tile_meter_bounds(x_1, y_1, z_1);
                child_tile_xyz.push([x_1, y_1, z_1, b]);
            }
            return child_tile_xyz;
        };
        MercatorTileSource.prototype.get_closest_parent_by_tile_xyz = function (x, y, z) {
            var _b, _c, _d;
            var world_x = this.calculate_world_x_by_tile_xyz(x, y, z);
            _b = (0, tslib_1.__read)(this.normalize_xyz(x, y, z), 3), x = _b[0], y = _b[1], z = _b[2];
            var quadkey = this.tile_xyz_to_quadkey(x, y, z);
            while (quadkey.length > 0) {
                quadkey = quadkey.substring(0, quadkey.length - 1);
                _c = (0, tslib_1.__read)(this.quadkey_to_tile_xyz(quadkey), 3), x = _c[0], y = _c[1], z = _c[2];
                _d = (0, tslib_1.__read)(this.denormalize_xyz(x, y, z, world_x), 3), x = _d[0], y = _d[1], z = _d[2];
                if (this.tiles.has(this.tile_xyz_to_key(x, y, z)))
                    return [x, y, z];
            }
            return [0, 0, 0];
        };
        MercatorTileSource.prototype.normalize_xyz = function (x, y, z) {
            if (this.wrap_around) {
                var tile_count = Math.pow(2, z);
                return [((x % tile_count) + tile_count) % tile_count, y, z];
            }
            else {
                return [x, y, z];
            }
        };
        MercatorTileSource.prototype.denormalize_xyz = function (x, y, z, world_x) {
            return [x + (world_x * Math.pow(2, z)), y, z];
        };
        MercatorTileSource.prototype.denormalize_meters = function (meters_x, meters_y, _level, world_x) {
            return [meters_x + (world_x * 2 * Math.PI * 6378137), meters_y];
        };
        MercatorTileSource.prototype.calculate_world_x_by_tile_xyz = function (x, _y, z) {
            return Math.floor(x / Math.pow(2, z));
        };
        return MercatorTileSource;
    }(tile_source_1.TileSource));
    exports.MercatorTileSource = MercatorTileSource;
    _a = MercatorTileSource;
    MercatorTileSource.__name__ = "MercatorTileSource";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                snap_to_zoom: [Boolean, false],
                wrap_around: [Boolean, true],
            });
        });
        _a.override({
            x_origin_offset: 20037508.34,
            y_origin_offset: 20037508.34,
            initial_resolution: 156543.03392804097,
        });
    })();
},
/* models/tiles/tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var object_1 = require(128) /* ../../core/util/object */;
    var TileSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TileSource, _super);
        function TileSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        TileSource.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.tiles = new Map();
            this._normalize_case();
        };
        TileSource.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.change, function () { return _this._clear_cache(); });
        };
        TileSource.prototype.string_lookup_replace = function (str, lookup) {
            var e_1, _b;
            var result_str = str;
            try {
                for (var _c = (0, tslib_1.__values)((0, object_1.entries)(lookup)), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), key = _e[0], value = _e[1];
                    result_str = result_str.replace("{" + key + "}", value);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return result_str;
        };
        TileSource.prototype._normalize_case = function () {
            /*
             * Note: should probably be refactored into subclasses.
             */
            var url = this.url
                .replace("{x}", "{X}")
                .replace("{y}", "{Y}")
                .replace("{z}", "{Z}")
                .replace("{q}", "{Q}")
                .replace("{xmin}", "{XMIN}")
                .replace("{ymin}", "{YMIN}")
                .replace("{xmax}", "{XMAX}")
                .replace("{ymax}", "{YMAX}");
            this.url = url;
        };
        TileSource.prototype._clear_cache = function () {
            this.tiles = new Map();
        };
        TileSource.prototype.tile_xyz_to_key = function (x, y, z) {
            return x + ":" + y + ":" + z;
        };
        TileSource.prototype.key_to_tile_xyz = function (key) {
            var _b = (0, tslib_1.__read)(key.split(":").map(function (c) { return parseInt(c); }), 3), x = _b[0], y = _b[1], z = _b[2];
            return [x, y, z];
        };
        TileSource.prototype.sort_tiles_from_center = function (tiles, tile_extent) {
            var _b = (0, tslib_1.__read)(tile_extent, 4), txmin = _b[0], tymin = _b[1], txmax = _b[2], tymax = _b[3];
            var center_x = ((txmax - txmin) / 2) + txmin;
            var center_y = ((tymax - tymin) / 2) + tymin;
            tiles.sort(function (a, b) {
                var a_distance = Math.sqrt(Math.pow((center_x - a[0]), 2) + Math.pow((center_y - a[1]), 2));
                var b_distance = Math.sqrt(Math.pow((center_x - b[0]), 2) + Math.pow((center_y - b[1]), 2));
                return a_distance - b_distance;
            });
        };
        TileSource.prototype.get_image_url = function (x, y, z) {
            var image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            return image_url
                .replace("{X}", x.toString())
                .replace("{Y}", y.toString())
                .replace("{Z}", z.toString());
        };
        return TileSource;
    }(model_1.Model));
    exports.TileSource = TileSource;
    _a = TileSource;
    TileSource.__name__ = "TileSource";
    (function () {
        _a.define(function (_b) {
            var Number = _b.Number, String = _b.String, Dict = _b.Dict, Nullable = _b.Nullable;
            return ({
                url: [String, ""],
                tile_size: [Number, 256],
                max_zoom: [Number, 30],
                min_zoom: [Number, 0],
                extra_url_vars: [Dict(String), {}],
                attribution: [String, ""],
                x_origin_offset: [Number],
                y_origin_offset: [Number],
                initial_resolution: [Nullable(Number), null],
            });
        });
    })();
},
/* models/tiles/tile_utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var projections_1 = require(193) /* ../../core/util/projections */;
    function geographic_to_meters(x_lon, y_lat) {
        return projections_1.wgs84_mercator.compute(x_lon, y_lat);
    }
    exports.geographic_to_meters = geographic_to_meters;
    function meters_to_geographic(mx, my) {
        return projections_1.wgs84_mercator.invert(mx, my);
    }
    exports.meters_to_geographic = meters_to_geographic;
    function geographic_extent_to_meters(extent) {
        var _a = (0, tslib_1.__read)(extent, 4), g_xmin = _a[0], g_ymin = _a[1], g_xmax = _a[2], g_ymax = _a[3];
        var _b = (0, tslib_1.__read)(geographic_to_meters(g_xmin, g_ymin), 2), m_xmin = _b[0], m_ymin = _b[1];
        var _c = (0, tslib_1.__read)(geographic_to_meters(g_xmax, g_ymax), 2), m_xmax = _c[0], m_ymax = _c[1];
        return [m_xmin, m_ymin, m_xmax, m_ymax];
    }
    exports.geographic_extent_to_meters = geographic_extent_to_meters;
    function meters_extent_to_geographic(extent) {
        var _a = (0, tslib_1.__read)(extent, 4), m_xmin = _a[0], m_ymin = _a[1], m_xmax = _a[2], m_ymax = _a[3];
        var _b = (0, tslib_1.__read)(meters_to_geographic(m_xmin, m_ymin), 2), g_xmin = _b[0], g_ymin = _b[1];
        var _c = (0, tslib_1.__read)(meters_to_geographic(m_xmax, m_ymax), 2), g_xmax = _c[0], g_ymax = _c[1];
        return [g_xmin, g_ymin, g_xmax, g_ymax];
    }
    exports.meters_extent_to_geographic = meters_extent_to_geographic;
},
/* models/tiles/quadkey_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var mercator_tile_source_1 = require(463) /* ./mercator_tile_source */;
    var QUADKEYTileSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(QUADKEYTileSource, _super);
        function QUADKEYTileSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        QUADKEYTileSource.prototype.get_image_url = function (x, y, z) {
            var image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            var _a = (0, tslib_1.__read)(this.tms_to_wmts(x, y, z), 3), wx = _a[0], wy = _a[1], wz = _a[2];
            var quadKey = this.tile_xyz_to_quadkey(wx, wy, wz);
            return image_url.replace("{Q}", quadKey);
        };
        return QUADKEYTileSource;
    }(mercator_tile_source_1.MercatorTileSource));
    exports.QUADKEYTileSource = QUADKEYTileSource;
    QUADKEYTileSource.__name__ = "QUADKEYTileSource";
},
/* models/tiles/tile_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var tile_source_1 = require(464) /* ./tile_source */;
    var wmts_tile_source_1 = require(468) /* ./wmts_tile_source */;
    var renderer_1 = require(156) /* ../renderers/renderer */;
    var range1d_1 = require(173) /* ../ranges/range1d */;
    var dom_1 = require(158) /* ../../core/dom */;
    var image_1 = require(251) /* ../../core/util/image */;
    var array_1 = require(126) /* ../../core/util/array */;
    var types_1 = require(125) /* ../../core/util/types */;
    var tiles_css_1 = (0, tslib_1.__importStar)(require(469) /* ../../styles/tiles.css */);
    var TileRendererView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TileRendererView, _super);
        function TileRendererView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TileRendererView.prototype.initialize = function () {
            this._tiles = [];
            _super.prototype.initialize.call(this);
        };
        TileRendererView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.change, function () { return _this.request_render(); });
            this.connect(this.model.tile_source.change, function () { return _this.request_render(); });
        };
        TileRendererView.prototype.remove = function () {
            if (this.attribution_el != null)
                (0, dom_1.removeElement)(this.attribution_el);
            _super.prototype.remove.call(this);
        };
        TileRendererView.prototype.styles = function () {
            return (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(_super.prototype.styles.call(this)), false), [tiles_css_1.default], false);
        };
        TileRendererView.prototype.get_extent = function () {
            return [this.x_range.start, this.y_range.start, this.x_range.end, this.y_range.end];
        };
        Object.defineProperty(TileRendererView.prototype, "map_plot", {
            get: function () {
                return this.plot_model;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(TileRendererView.prototype, "map_canvas", {
            get: function () {
                return this.layer.ctx;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(TileRendererView.prototype, "map_frame", {
            get: function () {
                return this.plot_view.frame;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(TileRendererView.prototype, "x_range", {
            get: function () {
                return this.map_plot.x_range;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(TileRendererView.prototype, "y_range", {
            get: function () {
                return this.map_plot.y_range;
            },
            enumerable: false,
            configurable: true
        });
        TileRendererView.prototype._set_data = function () {
            this.extent = this.get_extent();
            this._last_height = undefined;
            this._last_width = undefined;
        };
        TileRendererView.prototype._update_attribution = function () {
            if (this.attribution_el != null)
                (0, dom_1.removeElement)(this.attribution_el);
            var attribution = this.model.tile_source.attribution;
            if ((0, types_1.isString)(attribution) && attribution.length > 0) {
                var _b = this.plot_view, layout = _b.layout, frame = _b.frame;
                var offset_right = layout.bbox.width - frame.bbox.right;
                var offset_bottom = layout.bbox.height - frame.bbox.bottom;
                var max_width = frame.bbox.width;
                this.attribution_el = (0, dom_1.div)({
                    class: tiles_css_1.tile_attribution,
                    style: {
                        position: "absolute",
                        right: offset_right + "px",
                        bottom: offset_bottom + "px",
                        "max-width": max_width - 4 /*padding*/ + "px",
                        padding: "2px",
                        "background-color": "rgba(255,255,255,0.5)",
                        "font-size": "9px",
                        "line-height": "1.05",
                        "white-space": "nowrap",
                        overflow: "hidden",
                        "text-overflow": "ellipsis",
                    },
                });
                this.plot_view.canvas_view.add_event(this.attribution_el);
                this.attribution_el.innerHTML = attribution;
                this.attribution_el.title = this.attribution_el.textContent.replace(/\s*\n\s*/g, " ");
            }
        };
        TileRendererView.prototype._map_data = function () {
            this.initial_extent = this.get_extent();
            var zoom_level = this.model.tile_source.get_level_by_extent(this.initial_extent, this.map_frame.bbox.height, this.map_frame.bbox.width);
            var new_extent = this.model.tile_source.snap_to_zoom_level(this.initial_extent, this.map_frame.bbox.height, this.map_frame.bbox.width, zoom_level);
            this.x_range.start = new_extent[0];
            this.y_range.start = new_extent[1];
            this.x_range.end = new_extent[2];
            this.y_range.end = new_extent[3];
            if (this.x_range instanceof range1d_1.Range1d) {
                this.x_range.reset_start = new_extent[0];
                this.x_range.reset_end = new_extent[2];
            }
            if (this.y_range instanceof range1d_1.Range1d) {
                this.y_range.reset_start = new_extent[1];
                this.y_range.reset_end = new_extent[3];
            }
            this._update_attribution();
        };
        TileRendererView.prototype._create_tile = function (x, y, z, bounds, cache_only) {
            var _this = this;
            if (cache_only === void 0) {
                cache_only = false;
            }
            var quadkey = this.model.tile_source.tile_xyz_to_quadkey(x, y, z);
            var cache_key = this.model.tile_source.tile_xyz_to_key(x, y, z);
            if (this.model.tile_source.tiles.has(cache_key))
                return;
            var _b = (0, tslib_1.__read)(this.model.tile_source.normalize_xyz(x, y, z), 3), nx = _b[0], ny = _b[1], nz = _b[2];
            var src = this.model.tile_source.get_image_url(nx, ny, nz);
            var tile = {
                img: undefined,
                tile_coords: [x, y, z],
                normalized_coords: [nx, ny, nz],
                quadkey: quadkey,
                cache_key: cache_key,
                bounds: bounds,
                loaded: false,
                finished: false,
                x_coord: bounds[0],
                y_coord: bounds[3],
            };
            this.model.tile_source.tiles.set(cache_key, tile);
            this._tiles.push(tile);
            new image_1.ImageLoader(src, {
                loaded: function (img) {
                    Object.assign(tile, { img: img, loaded: true });
                    if (cache_only) {
                        tile.finished = true;
                        _this.notify_finished();
                    }
                    else
                        _this.request_render();
                },
                failed: function () {
                    tile.finished = true;
                },
            });
        };
        TileRendererView.prototype._enforce_aspect_ratio = function () {
            // brute force way of handling resize or sizing_mode event -------------------------------------------------------------
            if ((this._last_height !== this.map_frame.bbox.height) || (this._last_width !== this.map_frame.bbox.width)) {
                var extent = this.get_extent();
                var zoom_level = this.model.tile_source.get_level_by_extent(extent, this.map_frame.bbox.height, this.map_frame.bbox.width);
                var new_extent = this.model.tile_source.snap_to_zoom_level(extent, this.map_frame.bbox.height, this.map_frame.bbox.width, zoom_level);
                this.x_range.setv({ start: new_extent[0], end: new_extent[2] });
                this.y_range.setv({ start: new_extent[1], end: new_extent[3] });
                this.extent = new_extent;
                this._last_height = this.map_frame.bbox.height;
                this._last_width = this.map_frame.bbox.width;
            }
        };
        TileRendererView.prototype.has_finished = function () {
            var e_1, _b;
            if (!_super.prototype.has_finished.call(this))
                return false;
            if (this._tiles.length == 0)
                return false;
            try {
                for (var _c = (0, tslib_1.__values)(this._tiles), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var tile = _d.value;
                    if (!tile.finished)
                        return false;
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return true;
        };
        TileRendererView.prototype._render = function () {
            if (this.map_initialized == null) {
                this._set_data();
                this._map_data();
                this.map_initialized = true;
            }
            this._enforce_aspect_ratio();
            this._update();
            if (this.prefetch_timer != null) {
                clearTimeout(this.prefetch_timer);
            }
            this.prefetch_timer = setTimeout(this._prefetch_tiles.bind(this), 500);
            if (this.has_finished()) {
                this.notify_finished();
            }
        };
        TileRendererView.prototype._draw_tile = function (tile_key) {
            var tile_data = this.model.tile_source.tiles.get(tile_key);
            if (tile_data != null && tile_data.loaded) {
                var _b = (0, tslib_1.__read)(this.coordinates.map_to_screen([tile_data.bounds[0]], [tile_data.bounds[3]]), 2), _c = (0, tslib_1.__read)(_b[0], 1), sxmin = _c[0], _d = (0, tslib_1.__read)(_b[1], 1), symin = _d[0];
                var _e = (0, tslib_1.__read)(this.coordinates.map_to_screen([tile_data.bounds[2]], [tile_data.bounds[1]]), 2), _f = (0, tslib_1.__read)(_e[0], 1), sxmax = _f[0], _g = (0, tslib_1.__read)(_e[1], 1), symax = _g[0];
                var sw = sxmax - sxmin;
                var sh = symax - symin;
                var sx = sxmin;
                var sy = symin;
                var old_smoothing = this.map_canvas.getImageSmoothingEnabled();
                this.map_canvas.setImageSmoothingEnabled(this.model.smoothing);
                this.map_canvas.drawImage(tile_data.img, sx, sy, sw, sh);
                this.map_canvas.setImageSmoothingEnabled(old_smoothing);
                tile_data.finished = true;
            }
        };
        TileRendererView.prototype._set_rect = function () {
            var outline_width = this.plot_model.outline_line_width;
            var l = this.map_frame.bbox.left + (outline_width / 2);
            var t = this.map_frame.bbox.top + (outline_width / 2);
            var w = this.map_frame.bbox.width - outline_width;
            var h = this.map_frame.bbox.height - outline_width;
            this.map_canvas.rect(l, t, w, h);
            this.map_canvas.clip();
        };
        TileRendererView.prototype._render_tiles = function (tile_keys) {
            var e_2, _b;
            this.map_canvas.save();
            this._set_rect();
            this.map_canvas.globalAlpha = this.model.alpha;
            try {
                for (var tile_keys_1 = (0, tslib_1.__values)(tile_keys), tile_keys_1_1 = tile_keys_1.next(); !tile_keys_1_1.done; tile_keys_1_1 = tile_keys_1.next()) {
                    var tile_key = tile_keys_1_1.value;
                    this._draw_tile(tile_key);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (tile_keys_1_1 && !tile_keys_1_1.done && (_b = tile_keys_1.return))
                        _b.call(tile_keys_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            this.map_canvas.restore();
        };
        TileRendererView.prototype._prefetch_tiles = function () {
            var e_3, _b;
            var tile_source = this.model.tile_source;
            var extent = this.get_extent();
            var h = this.map_frame.bbox.height;
            var w = this.map_frame.bbox.width;
            var zoom_level = this.model.tile_source.get_level_by_extent(extent, h, w);
            var tiles = this.model.tile_source.get_tiles_by_extent(extent, zoom_level);
            for (var t = 0, end = Math.min(10, tiles.length); t < end; t++) {
                var _c = (0, tslib_1.__read)(tiles[t], 3), x = _c[0], y = _c[1], z = _c[2];
                var children = this.model.tile_source.children_by_tile_xyz(x, y, z);
                try {
                    for (var children_1 = (e_3 = void 0, (0, tslib_1.__values)(children)), children_1_1 = children_1.next(); !children_1_1.done; children_1_1 = children_1.next()) {
                        var c = children_1_1.value;
                        var _d = (0, tslib_1.__read)(c, 4), cx = _d[0], cy = _d[1], cz = _d[2], cbounds = _d[3];
                        if (tile_source.tiles.has(tile_source.tile_xyz_to_key(cx, cy, cz))) {
                            continue;
                        }
                        else {
                            this._create_tile(cx, cy, cz, cbounds, true);
                        }
                    }
                }
                catch (e_3_1) {
                    e_3 = { error: e_3_1 };
                }
                finally {
                    try {
                        if (children_1_1 && !children_1_1.done && (_b = children_1.return))
                            _b.call(children_1);
                    }
                    finally {
                        if (e_3)
                            throw e_3.error;
                    }
                }
            }
        };
        TileRendererView.prototype._fetch_tiles = function (tiles) {
            var e_4, _b;
            try {
                for (var tiles_1 = (0, tslib_1.__values)(tiles), tiles_1_1 = tiles_1.next(); !tiles_1_1.done; tiles_1_1 = tiles_1.next()) {
                    var tile = tiles_1_1.value;
                    var _c = (0, tslib_1.__read)(tile, 4), x = _c[0], y = _c[1], z = _c[2], bounds = _c[3];
                    this._create_tile(x, y, z, bounds);
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (tiles_1_1 && !tiles_1_1.done && (_b = tiles_1.return))
                        _b.call(tiles_1);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
        };
        TileRendererView.prototype._update = function () {
            var e_5, _b, e_6, _c;
            var _this = this;
            var tile_source = this.model.tile_source;
            var min_zoom = tile_source.min_zoom;
            var max_zoom = tile_source.max_zoom;
            var extent = this.get_extent();
            var zooming_out = (this.extent[2] - this.extent[0]) < (extent[2] - extent[0]);
            var h = this.map_frame.bbox.height;
            var w = this.map_frame.bbox.width;
            var zoom_level = tile_source.get_level_by_extent(extent, h, w);
            var snap_back = false;
            if (zoom_level < min_zoom) {
                extent = this.extent;
                zoom_level = min_zoom;
                snap_back = true;
            }
            else if (zoom_level > max_zoom) {
                extent = this.extent;
                zoom_level = max_zoom;
                snap_back = true;
            }
            if (snap_back) {
                this.x_range.setv({ start: extent[0], end: extent[2] });
                this.y_range.setv({ start: extent[1], end: extent[3] });
            }
            this.extent = extent;
            var tiles = tile_source.get_tiles_by_extent(extent, zoom_level);
            var need_load = [];
            var cached = [];
            var parents = [];
            var children = [];
            try {
                for (var tiles_2 = (0, tslib_1.__values)(tiles), tiles_2_1 = tiles_2.next(); !tiles_2_1.done; tiles_2_1 = tiles_2.next()) {
                    var t = tiles_2_1.value;
                    var _d = (0, tslib_1.__read)(t, 3), x = _d[0], y = _d[1], z = _d[2];
                    var key = tile_source.tile_xyz_to_key(x, y, z);
                    var tile = tile_source.tiles.get(key);
                    if (tile != null && tile.loaded) {
                        cached.push(key);
                    }
                    else {
                        if (this.model.render_parents) {
                            var _e = (0, tslib_1.__read)(tile_source.get_closest_parent_by_tile_xyz(x, y, z), 3), px = _e[0], py = _e[1], pz = _e[2];
                            var parent_key = tile_source.tile_xyz_to_key(px, py, pz);
                            var parent_tile = tile_source.tiles.get(parent_key);
                            if ((parent_tile != null) && parent_tile.loaded && !(0, array_1.includes)(parents, parent_key)) {
                                parents.push(parent_key);
                            }
                            if (zooming_out) {
                                var child_tiles = tile_source.children_by_tile_xyz(x, y, z);
                                try {
                                    for (var child_tiles_1 = (e_6 = void 0, (0, tslib_1.__values)(child_tiles)), child_tiles_1_1 = child_tiles_1.next(); !child_tiles_1_1.done; child_tiles_1_1 = child_tiles_1.next()) {
                                        var _f = (0, tslib_1.__read)(child_tiles_1_1.value, 3), cx = _f[0], cy = _f[1], cz = _f[2];
                                        var child_key = tile_source.tile_xyz_to_key(cx, cy, cz);
                                        if (tile_source.tiles.has(child_key))
                                            children.push(child_key);
                                    }
                                }
                                catch (e_6_1) {
                                    e_6 = { error: e_6_1 };
                                }
                                finally {
                                    try {
                                        if (child_tiles_1_1 && !child_tiles_1_1.done && (_c = child_tiles_1.return))
                                            _c.call(child_tiles_1);
                                    }
                                    finally {
                                        if (e_6)
                                            throw e_6.error;
                                    }
                                }
                            }
                        }
                    }
                    if (tile == null)
                        need_load.push(t);
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (tiles_2_1 && !tiles_2_1.done && (_b = tiles_2.return))
                        _b.call(tiles_2);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            // draw stand-in parents ----------
            this._render_tiles(parents);
            this._render_tiles(children);
            // draw cached ----------
            this._render_tiles(cached);
            // fetch missing -------
            if (this.render_timer != null) {
                clearTimeout(this.render_timer);
            }
            this.render_timer = setTimeout((function () { return _this._fetch_tiles(need_load); }), 65);
        };
        return TileRendererView;
    }(renderer_1.RendererView));
    exports.TileRendererView = TileRendererView;
    TileRendererView.__name__ = "TileRendererView";
    var TileRenderer = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TileRenderer, _super);
        function TileRenderer(attrs) {
            return _super.call(this, attrs) || this;
        }
        return TileRenderer;
    }(renderer_1.Renderer));
    exports.TileRenderer = TileRenderer;
    _a = TileRenderer;
    TileRenderer.__name__ = "TileRenderer";
    (function () {
        _a.prototype.default_view = TileRendererView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Number = _b.Number, Ref = _b.Ref;
            return ({
                alpha: [Number, 1.0],
                smoothing: [Boolean, true],
                tile_source: [Ref(tile_source_1.TileSource), function () { return new wmts_tile_source_1.WMTSTileSource(); }],
                render_parents: [Boolean, true],
            });
        });
        _a.override({
            level: "image",
        });
    })();
},
/* models/tiles/wmts_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var mercator_tile_source_1 = require(463) /* ./mercator_tile_source */;
    var WMTSTileSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WMTSTileSource, _super);
        function WMTSTileSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        WMTSTileSource.prototype.get_image_url = function (x, y, z) {
            var image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            var _a = (0, tslib_1.__read)(this.tms_to_wmts(x, y, z), 3), wx = _a[0], wy = _a[1], wz = _a[2];
            return image_url
                .replace("{X}", wx.toString())
                .replace("{Y}", wy.toString())
                .replace("{Z}", wz.toString());
        };
        return WMTSTileSource;
    }(mercator_tile_source_1.MercatorTileSource));
    exports.WMTSTileSource = WMTSTileSource;
    WMTSTileSource.__name__ = "WMTSTileSource";
},
/* styles/tiles.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tile_attribution = "bk-tile-attribution";
    exports.default = ".bk-root .bk-tile-attribution a{color:black;}";
},
/* models/tiles/tms_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var mercator_tile_source_1 = require(463) /* ./mercator_tile_source */;
    var TMSTileSource = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TMSTileSource, _super);
        function TMSTileSource(attrs) {
            return _super.call(this, attrs) || this;
        }
        TMSTileSource.prototype.get_image_url = function (x, y, z) {
            var image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            return image_url
                .replace("{X}", x.toString())
                .replace("{Y}", y.toString())
                .replace("{Z}", z.toString());
        };
        return TMSTileSource;
    }(mercator_tile_source_1.MercatorTileSource));
    exports.TMSTileSource = TMSTileSource;
    TMSTileSource.__name__ = "TMSTileSource";
},
/* models/textures/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var canvas_texture_1 = require(472) /* ./canvas_texture */;
    __esExport("CanvasTexture", canvas_texture_1.CanvasTexture);
    var image_url_texture_1 = require(474) /* ./image_url_texture */;
    __esExport("ImageURLTexture", image_url_texture_1.ImageURLTexture);
    var texture_1 = require(473) /* ./texture */;
    __esExport("Texture", texture_1.Texture);
},
/* models/textures/canvas_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var texture_1 = require(473) /* ./texture */;
    var string_1 = require(149) /* ../../core/util/string */;
    var CanvasTexture = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CanvasTexture, _super);
        function CanvasTexture(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CanvasTexture.prototype, "func", {
            get: function () {
                var code = (0, string_1.use_strict)(this.code);
                return new Function("ctx", "color", "scale", "weight", code);
            },
            enumerable: false,
            configurable: true
        });
        CanvasTexture.prototype.get_pattern = function (color, scale, weight) {
            var canvas = document.createElement("canvas");
            canvas.width = scale;
            canvas.height = scale;
            var pattern_ctx = canvas.getContext("2d");
            this.func.call(this, pattern_ctx, color, scale, weight);
            return canvas;
        };
        return CanvasTexture;
    }(texture_1.Texture));
    exports.CanvasTexture = CanvasTexture;
    _a = CanvasTexture;
    CanvasTexture.__name__ = "CanvasTexture";
    (function () {
        _a.define(function (_b) {
            var String = _b.String;
            return ({
                code: [String],
            });
        });
    })();
},
/* models/textures/texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var enums_1 = require(135) /* ../../core/enums */;
    var Texture = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Texture, _super);
        function Texture(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Texture;
    }(model_1.Model));
    exports.Texture = Texture;
    _a = Texture;
    Texture.__name__ = "Texture";
    (function () {
        _a.define(function () {
            return ({
                repetition: [enums_1.TextureRepetition, "repeat"],
            });
        });
    })();
},
/* models/textures/image_url_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var texture_1 = require(473) /* ./texture */;
    var image_1 = require(251) /* ../../core/util/image */;
    var ImageURLTexture = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ImageURLTexture, _super);
        function ImageURLTexture(attrs) {
            return _super.call(this, attrs) || this;
        }
        ImageURLTexture.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._loader = new image_1.ImageLoader(this.url);
        };
        ImageURLTexture.prototype.get_pattern = function (_color, _scale, _weight) {
            var _loader = this._loader;
            return this._loader.finished ? _loader.image : _loader.promise;
        };
        return ImageURLTexture;
    }(texture_1.Texture));
    exports.ImageURLTexture = ImageURLTexture;
    _a = ImageURLTexture;
    ImageURLTexture.__name__ = "ImageURLTexture";
    (function () {
        _a.define(function (_b) {
            var String = _b.String;
            return ({
                url: [String],
            });
        });
    })();
},
/* models/tools/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var action_tool_1 = require(353) /* ./actions/action_tool */;
    __esExport("ActionTool", action_tool_1.ActionTool);
    var custom_action_1 = require(476) /* ./actions/custom_action */;
    __esExport("CustomAction", custom_action_1.CustomAction);
    var help_tool_1 = require(354) /* ./actions/help_tool */;
    __esExport("HelpTool", help_tool_1.HelpTool);
    var redo_tool_1 = require(477) /* ./actions/redo_tool */;
    __esExport("RedoTool", redo_tool_1.RedoTool);
    var reset_tool_1 = require(478) /* ./actions/reset_tool */;
    __esExport("ResetTool", reset_tool_1.ResetTool);
    var save_tool_1 = require(479) /* ./actions/save_tool */;
    __esExport("SaveTool", save_tool_1.SaveTool);
    var undo_tool_1 = require(480) /* ./actions/undo_tool */;
    __esExport("UndoTool", undo_tool_1.UndoTool);
    var zoom_in_tool_1 = require(481) /* ./actions/zoom_in_tool */;
    __esExport("ZoomInTool", zoom_in_tool_1.ZoomInTool);
    var zoom_out_tool_1 = require(484) /* ./actions/zoom_out_tool */;
    __esExport("ZoomOutTool", zoom_out_tool_1.ZoomOutTool);
    var button_tool_1 = require(339) /* ./button_tool */;
    __esExport("ButtonTool", button_tool_1.ButtonTool);
    var edit_tool_1 = require(485) /* ./edit/edit_tool */;
    __esExport("EditTool", edit_tool_1.EditTool);
    var box_edit_tool_1 = require(486) /* ./edit/box_edit_tool */;
    __esExport("BoxEditTool", box_edit_tool_1.BoxEditTool);
    var freehand_draw_tool_1 = require(487) /* ./edit/freehand_draw_tool */;
    __esExport("FreehandDrawTool", freehand_draw_tool_1.FreehandDrawTool);
    var point_draw_tool_1 = require(488) /* ./edit/point_draw_tool */;
    __esExport("PointDrawTool", point_draw_tool_1.PointDrawTool);
    var poly_draw_tool_1 = require(489) /* ./edit/poly_draw_tool */;
    __esExport("PolyDrawTool", poly_draw_tool_1.PolyDrawTool);
    var poly_tool_1 = require(490) /* ./edit/poly_tool */;
    __esExport("PolyTool", poly_tool_1.PolyTool);
    var poly_edit_tool_1 = require(491) /* ./edit/poly_edit_tool */;
    __esExport("PolyEditTool", poly_edit_tool_1.PolyEditTool);
    var box_select_tool_1 = require(492) /* ./gestures/box_select_tool */;
    __esExport("BoxSelectTool", box_select_tool_1.BoxSelectTool);
    var box_zoom_tool_1 = require(494) /* ./gestures/box_zoom_tool */;
    __esExport("BoxZoomTool", box_zoom_tool_1.BoxZoomTool);
    var gesture_tool_1 = require(338) /* ./gestures/gesture_tool */;
    __esExport("GestureTool", gesture_tool_1.GestureTool);
    var lasso_select_tool_1 = require(495) /* ./gestures/lasso_select_tool */;
    __esExport("LassoSelectTool", lasso_select_tool_1.LassoSelectTool);
    var line_edit_tool_1 = require(497) /* ./edit/line_edit_tool */;
    __esExport("LineEditTool", line_edit_tool_1.LineEditTool);
    var pan_tool_1 = require(499) /* ./gestures/pan_tool */;
    __esExport("PanTool", pan_tool_1.PanTool);
    var poly_select_tool_1 = require(496) /* ./gestures/poly_select_tool */;
    __esExport("PolySelectTool", poly_select_tool_1.PolySelectTool);
    var range_tool_1 = require(500) /* ./gestures/range_tool */;
    __esExport("RangeTool", range_tool_1.RangeTool);
    var select_tool_1 = require(493) /* ./gestures/select_tool */;
    __esExport("SelectTool", select_tool_1.SelectTool);
    var tap_tool_1 = require(501) /* ./gestures/tap_tool */;
    __esExport("TapTool", tap_tool_1.TapTool);
    var wheel_pan_tool_1 = require(502) /* ./gestures/wheel_pan_tool */;
    __esExport("WheelPanTool", wheel_pan_tool_1.WheelPanTool);
    var wheel_zoom_tool_1 = require(503) /* ./gestures/wheel_zoom_tool */;
    __esExport("WheelZoomTool", wheel_zoom_tool_1.WheelZoomTool);
    var crosshair_tool_1 = require(504) /* ./inspectors/crosshair_tool */;
    __esExport("CrosshairTool", crosshair_tool_1.CrosshairTool);
    var customjs_hover_1 = require(505) /* ./inspectors/customjs_hover */;
    __esExport("CustomJSHover", customjs_hover_1.CustomJSHover);
    var hover_tool_1 = require(506) /* ./inspectors/hover_tool */;
    __esExport("HoverTool", hover_tool_1.HoverTool);
    var inspect_tool_1 = require(347) /* ./inspectors/inspect_tool */;
    __esExport("InspectTool", inspect_tool_1.InspectTool);
    var tool_1 = require(337) /* ./tool */;
    __esExport("Tool", tool_1.Tool);
    var tool_proxy_1 = require(509) /* ./tool_proxy */;
    __esExport("ToolProxy", tool_proxy_1.ToolProxy);
    var toolbar_1 = require(336) /* ./toolbar */;
    __esExport("Toolbar", toolbar_1.Toolbar);
    var toolbar_base_1 = require(348) /* ./toolbar_base */;
    __esExport("ToolbarBase", toolbar_base_1.ToolbarBase);
    var toolbar_box_1 = require(510) /* ./toolbar_box */;
    __esExport("ProxyToolbar", toolbar_box_1.ProxyToolbar);
    var toolbar_box_2 = require(510) /* ./toolbar_box */;
    __esExport("ToolbarBox", toolbar_box_2.ToolbarBox);
},
/* models/tools/actions/custom_action.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var action_tool_1 = require(353) /* ./action_tool */;
    var CustomActionButtonView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomActionButtonView, _super);
        function CustomActionButtonView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CustomActionButtonView.prototype.css_classes = function () {
            return _super.prototype.css_classes.call(this).concat("bk-toolbar-button-custom-action");
        };
        return CustomActionButtonView;
    }(action_tool_1.ActionToolButtonView));
    exports.CustomActionButtonView = CustomActionButtonView;
    CustomActionButtonView.__name__ = "CustomActionButtonView";
    var CustomActionView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomActionView, _super);
        function CustomActionView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CustomActionView.prototype.doit = function () {
            var _b;
            (_b = this.model.callback) === null || _b === void 0 ? void 0 : _b.execute(this.model);
        };
        return CustomActionView;
    }(action_tool_1.ActionToolView));
    exports.CustomActionView = CustomActionView;
    CustomActionView.__name__ = "CustomActionView";
    var CustomAction = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomAction, _super);
        function CustomAction(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Custom Action";
            _this.button_view = CustomActionButtonView;
            return _this;
        }
        return CustomAction;
    }(action_tool_1.ActionTool));
    exports.CustomAction = CustomAction;
    _a = CustomAction;
    CustomAction.__name__ = "CustomAction";
    (function () {
        _a.prototype.default_view = CustomActionView;
        _a.define(function (_b) {
            var Any = _b.Any, String = _b.String, Nullable = _b.Nullable;
            return ({
                callback: [Nullable(Any /*TODO*/)],
                icon: [String],
            });
        });
        _a.override({
            description: "Perform a Custom Action",
        });
    })();
},
/* models/tools/actions/redo_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var action_tool_1 = require(353) /* ./action_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var RedoToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RedoToolView, _super);
        function RedoToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RedoToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.plot_view.state.changed, function () { return _this.model.disabled = !_this.plot_view.state.can_redo; });
        };
        RedoToolView.prototype.doit = function () {
            var state = this.plot_view.state.redo();
            if ((state === null || state === void 0 ? void 0 : state.range) != null) {
                this.plot_view.trigger_ranges_update_event();
            }
        };
        return RedoToolView;
    }(action_tool_1.ActionToolView));
    exports.RedoToolView = RedoToolView;
    RedoToolView.__name__ = "RedoToolView";
    var RedoTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RedoTool, _super);
        function RedoTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Redo";
            _this.icon = icons_css_1.tool_icon_redo;
            return _this;
        }
        return RedoTool;
    }(action_tool_1.ActionTool));
    exports.RedoTool = RedoTool;
    _a = RedoTool;
    RedoTool.__name__ = "RedoTool";
    (function () {
        _a.prototype.default_view = RedoToolView;
        _a.override({
            disabled: true,
        });
        _a.register_alias("redo", function () { return new RedoTool(); });
    })();
},
/* models/tools/actions/reset_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var action_tool_1 = require(353) /* ./action_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var ResetToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ResetToolView, _super);
        function ResetToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ResetToolView.prototype.doit = function () {
            // reset() issues the RangesUpdate event
            this.plot_view.reset();
        };
        return ResetToolView;
    }(action_tool_1.ActionToolView));
    exports.ResetToolView = ResetToolView;
    ResetToolView.__name__ = "ResetToolView";
    var ResetTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ResetTool, _super);
        function ResetTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Reset";
            _this.icon = icons_css_1.tool_icon_reset;
            return _this;
        }
        return ResetTool;
    }(action_tool_1.ActionTool));
    exports.ResetTool = ResetTool;
    _a = ResetTool;
    ResetTool.__name__ = "ResetTool";
    (function () {
        _a.prototype.default_view = ResetToolView;
        _a.register_alias("reset", function () { return new ResetTool(); });
    })();
},
/* models/tools/actions/save_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var action_tool_1 = require(353) /* ./action_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var SaveToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SaveToolView, _super);
        function SaveToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SaveToolView.prototype.copy = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var blob, item;
                var _b;
                return (0, tslib_1.__generator)(this, function (_c) {
                    switch (_c.label) {
                        case 0: return [4 /*yield*/, this.plot_view.to_blob()];
                        case 1:
                            blob = _c.sent();
                            item = new ClipboardItem((_b = {}, _b[blob.type] = Promise.resolve(blob), _b));
                            return [4 /*yield*/, navigator.clipboard.write([item])];
                        case 2:
                            _c.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        SaveToolView.prototype.save = function (name) {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var blob, link;
                return (0, tslib_1.__generator)(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4 /*yield*/, this.plot_view.to_blob()];
                        case 1:
                            blob = _b.sent();
                            link = document.createElement("a");
                            link.href = URL.createObjectURL(blob);
                            link.download = name; // + ".png" | "svg" (inferred from MIME type)
                            link.target = "_blank";
                            link.dispatchEvent(new MouseEvent("click"));
                            return [2 /*return*/];
                    }
                });
            });
        };
        SaveToolView.prototype.doit = function (action) {
            if (action === void 0) {
                action = "save";
            }
            switch (action) {
                case "save":
                    this.save("bokeh_plot");
                    break;
                case "copy":
                    this.copy();
                    break;
            }
        };
        return SaveToolView;
    }(action_tool_1.ActionToolView));
    exports.SaveToolView = SaveToolView;
    SaveToolView.__name__ = "SaveToolView";
    var SaveTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SaveTool, _super);
        function SaveTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Save";
            _this.icon = icons_css_1.tool_icon_save;
            return _this;
        }
        Object.defineProperty(SaveTool.prototype, "menu", {
            get: function () {
                var _this = this;
                return [
                    {
                        icon: "bk-tool-icon-copy-to-clipboard",
                        tooltip: "Copy image to clipboard",
                        if: function () { return typeof ClipboardItem !== "undefined"; },
                        handler: function () {
                            _this.do.emit("copy");
                        },
                    },
                ];
            },
            enumerable: false,
            configurable: true
        });
        return SaveTool;
    }(action_tool_1.ActionTool));
    exports.SaveTool = SaveTool;
    _a = SaveTool;
    SaveTool.__name__ = "SaveTool";
    (function () {
        _a.prototype.default_view = SaveToolView;
        _a.register_alias("save", function () { return new SaveTool(); });
    })();
},
/* models/tools/actions/undo_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var action_tool_1 = require(353) /* ./action_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var UndoToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UndoToolView, _super);
        function UndoToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        UndoToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.plot_view.state.changed, function () { return _this.model.disabled = !_this.plot_view.state.can_undo; });
        };
        UndoToolView.prototype.doit = function () {
            var state = this.plot_view.state.undo();
            if ((state === null || state === void 0 ? void 0 : state.range) != null) {
                this.plot_view.trigger_ranges_update_event();
            }
        };
        return UndoToolView;
    }(action_tool_1.ActionToolView));
    exports.UndoToolView = UndoToolView;
    UndoToolView.__name__ = "UndoToolView";
    var UndoTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(UndoTool, _super);
        function UndoTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Undo";
            _this.icon = icons_css_1.tool_icon_undo;
            return _this;
        }
        return UndoTool;
    }(action_tool_1.ActionTool));
    exports.UndoTool = UndoTool;
    _a = UndoTool;
    UndoTool.__name__ = "UndoTool";
    (function () {
        _a.prototype.default_view = UndoToolView;
        _a.override({
            disabled: true,
        });
        _a.register_alias("undo", function () { return new UndoTool(); });
    })();
},
/* models/tools/actions/zoom_in_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var zoom_base_tool_1 = require(482) /* ./zoom_base_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var ZoomInToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ZoomInToolView, _super);
        function ZoomInToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ZoomInToolView;
    }(zoom_base_tool_1.ZoomBaseToolView));
    exports.ZoomInToolView = ZoomInToolView;
    ZoomInToolView.__name__ = "ZoomInToolView";
    var ZoomInTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ZoomInTool, _super);
        function ZoomInTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.sign = 1;
            _this.tool_name = "Zoom In";
            _this.icon = icons_css_1.tool_icon_zoom_in;
            return _this;
        }
        return ZoomInTool;
    }(zoom_base_tool_1.ZoomBaseTool));
    exports.ZoomInTool = ZoomInTool;
    _a = ZoomInTool;
    ZoomInTool.__name__ = "ZoomInTool";
    (function () {
        _a.prototype.default_view = ZoomInToolView;
        _a.register_alias("zoom_in", function () { return new ZoomInTool({ dimensions: "both" }); });
        _a.register_alias("xzoom_in", function () { return new ZoomInTool({ dimensions: "width" }); });
        _a.register_alias("yzoom_in", function () { return new ZoomInTool({ dimensions: "height" }); });
    })();
},
/* models/tools/actions/zoom_base_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var action_tool_1 = require(353) /* ./action_tool */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var zoom_1 = require(483) /* ../../../core/util/zoom */;
    var ZoomBaseToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ZoomBaseToolView, _super);
        function ZoomBaseToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ZoomBaseToolView.prototype.doit = function () {
            var _b;
            var frame = this.plot_view.frame;
            var dims = this.model.dimensions;
            // restrict to axis configured in tool's dimensions property
            var h_axis = dims == "width" || dims == "both";
            var v_axis = dims == "height" || dims == "both";
            var zoom_info = (0, zoom_1.scale_range)(frame, this.model.sign * this.model.factor, h_axis, v_axis);
            this.plot_view.state.push("zoom_out", { range: zoom_info });
            this.plot_view.update_range(zoom_info, { scrolling: true, maintain_focus: this.model.maintain_focus });
            (_b = this.model.document) === null || _b === void 0 ? void 0 : _b.interactive_start(this.plot_model);
            this.plot_view.trigger_ranges_update_event();
        };
        return ZoomBaseToolView;
    }(action_tool_1.ActionToolView));
    exports.ZoomBaseToolView = ZoomBaseToolView;
    ZoomBaseToolView.__name__ = "ZoomBaseToolView";
    var ZoomBaseTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ZoomBaseTool, _super);
        function ZoomBaseTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.maintain_focus = true;
            return _this;
        }
        Object.defineProperty(ZoomBaseTool.prototype, "tooltip", {
            get: function () {
                return this._get_dim_tooltip(this.dimensions);
            },
            enumerable: false,
            configurable: true
        });
        return ZoomBaseTool;
    }(action_tool_1.ActionTool));
    exports.ZoomBaseTool = ZoomBaseTool;
    _a = ZoomBaseTool;
    ZoomBaseTool.__name__ = "ZoomBaseTool";
    (function () {
        _a.define(function (_b) {
            var Percent = _b.Percent;
            return ({
                factor: [Percent, 0.1],
                dimensions: [enums_1.Dimensions, "both"],
            });
        });
    })();
},
/* core/util/zoom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var math_1 = require(117) /* ./math */;
    // Module for zoom-related functions
    function scale_highlow(range, factor, center) {
        var _a = (0, tslib_1.__read)([range.start, range.end], 2), low = _a[0], high = _a[1];
        var x = center != null ? center : (high + low) / 2.0;
        var x0 = low - (low - x) * factor;
        var x1 = high - (high - x) * factor;
        return [x0, x1];
    }
    exports.scale_highlow = scale_highlow;
    function get_info(scales, _a) {
        var e_1, _b;
        var _c = (0, tslib_1.__read)(_a, 2), sxy0 = _c[0], sxy1 = _c[1];
        var info = new Map();
        try {
            for (var scales_1 = (0, tslib_1.__values)(scales), scales_1_1 = scales_1.next(); !scales_1_1.done; scales_1_1 = scales_1.next()) {
                var _d = (0, tslib_1.__read)(scales_1_1.value, 2), name = _d[0], scale = _d[1];
                var _e = (0, tslib_1.__read)(scale.r_invert(sxy0, sxy1), 2), start = _e[0], end = _e[1];
                info.set(name, { start: start, end: end });
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (scales_1_1 && !scales_1_1.done && (_b = scales_1.return))
                    _b.call(scales_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return info;
    }
    exports.get_info = get_info;
    function scale_range(frame, factor, h_axis, v_axis, center) {
        if (h_axis === void 0) {
            h_axis = true;
        }
        if (v_axis === void 0) {
            v_axis = true;
        }
        /*
         * Utility function for zoom tools to calculate/create the zoom_info object
         * of the form required by ``PlotView.update_range``
         *
         * Parameters:
         *   frame : CartesianFrame
         *   factor : Number
         *   h_axis : Boolean, optional
         *     whether to zoom the horizontal axis (default = true)
         *   v_axis : Boolean, optional
         *     whether to zoom the horizontal axis (default = true)
         *   center : object, optional
         *     of form {'x': Number, 'y', Number}
         *
         * Returns:
         *   object:
         */
        // clamp the  magnitude of factor, if it is > 1 bad things happen
        factor = (0, math_1.clamp)(factor, -0.9, 0.9);
        var hfactor = h_axis ? factor : 0;
        var _a = (0, tslib_1.__read)(scale_highlow(frame.bbox.h_range, hfactor, center != null ? center.x : undefined), 2), sx0 = _a[0], sx1 = _a[1];
        var xrs = get_info(frame.x_scales, [sx0, sx1]);
        var vfactor = v_axis ? factor : 0;
        var _b = (0, tslib_1.__read)(scale_highlow(frame.bbox.v_range, vfactor, center != null ? center.y : undefined), 2), sy0 = _b[0], sy1 = _b[1];
        var yrs = get_info(frame.y_scales, [sy0, sy1]);
        // OK this sucks we can't set factor independently in each direction. It is used
        // for GMap plots, and GMap plots always preserve aspect, so effective the value
        // of 'dimensions' is ignored.
        return { xrs: xrs, yrs: yrs, factor: factor };
    }
    exports.scale_range = scale_range;
},
/* models/tools/actions/zoom_out_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var zoom_base_tool_1 = require(482) /* ./zoom_base_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var ZoomOutToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ZoomOutToolView, _super);
        function ZoomOutToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ZoomOutToolView;
    }(zoom_base_tool_1.ZoomBaseToolView));
    exports.ZoomOutToolView = ZoomOutToolView;
    ZoomOutToolView.__name__ = "ZoomOutToolView";
    var ZoomOutTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ZoomOutTool, _super);
        function ZoomOutTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.sign = -1;
            _this.tool_name = "Zoom Out";
            _this.icon = icons_css_1.tool_icon_zoom_out;
            return _this;
        }
        return ZoomOutTool;
    }(zoom_base_tool_1.ZoomBaseTool));
    exports.ZoomOutTool = ZoomOutTool;
    _a = ZoomOutTool;
    ZoomOutTool.__name__ = "ZoomOutTool";
    (function () {
        _a.prototype.default_view = ZoomOutToolView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean;
            return ({
                maintain_focus: [Boolean, true],
            });
        });
        _a.register_alias("zoom_out", function () { return new ZoomOutTool({ dimensions: "both" }); });
        _a.register_alias("xzoom_out", function () { return new ZoomOutTool({ dimensions: "width" }); });
        _a.register_alias("yzoom_out", function () { return new ZoomOutTool({ dimensions: "height" }); });
    })();
},
/* models/tools/edit/edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var array_1 = require(126) /* ../../../core/util/array */;
    var types_1 = require(125) /* ../../../core/util/types */;
    var assert_1 = require(127) /* ../../../core/util/assert */;
    var glyph_renderer_1 = require(290) /* ../../renderers/glyph_renderer */;
    var gesture_tool_1 = require(338) /* ../gestures/gesture_tool */;
    var EditToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EditToolView, _super);
        function EditToolView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._mouse_in_frame = true;
            return _this;
        }
        EditToolView.prototype._select_mode = function (ev) {
            var shiftKey = ev.shiftKey, ctrlKey = ev.ctrlKey;
            if (!shiftKey && !ctrlKey)
                return "replace";
            else if (shiftKey && !ctrlKey)
                return "append";
            else if (!shiftKey && ctrlKey)
                return "intersect";
            else if (shiftKey && ctrlKey)
                return "subtract";
            else
                (0, assert_1.unreachable)();
        };
        EditToolView.prototype._move_enter = function (_e) {
            this._mouse_in_frame = true;
        };
        EditToolView.prototype._move_exit = function (_e) {
            this._mouse_in_frame = false;
        };
        EditToolView.prototype._map_drag = function (sx, sy, renderer) {
            // Maps screen to data coordinates
            var frame = this.plot_view.frame;
            if (!frame.bbox.contains(sx, sy)) {
                return null;
            }
            var renderer_view = this.plot_view.renderer_view(renderer);
            if (renderer_view == null)
                return null;
            var x = renderer_view.coordinates.x_scale.invert(sx);
            var y = renderer_view.coordinates.y_scale.invert(sy);
            return [x, y];
        };
        EditToolView.prototype._delete_selected = function (renderer) {
            var e_1, _b;
            // Deletes all selected rows in the ColumnDataSource
            var cds = renderer.data_source;
            var indices = cds.selected.indices;
            indices.sort();
            try {
                for (var _c = (0, tslib_1.__values)(cds.columns()), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var column = _d.value;
                    var values = cds.get_array(column);
                    for (var index = 0; index < indices.length; index++) {
                        var ind = indices[index];
                        values.splice(ind - index, 1);
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            this._emit_cds_changes(cds);
        };
        EditToolView.prototype._pop_glyphs = function (cds, num_objects) {
            var e_2, _b;
            // Pops rows in the CDS until only num_objects are left
            var columns = cds.columns();
            if (!num_objects || !columns.length)
                return;
            try {
                for (var columns_1 = (0, tslib_1.__values)(columns), columns_1_1 = columns_1.next(); !columns_1_1.done; columns_1_1 = columns_1.next()) {
                    var column = columns_1_1.value;
                    var array = cds.get_array(column);
                    var drop = array.length - num_objects + 1;
                    if (drop < 1)
                        continue;
                    if (!(0, types_1.isArray)(array)) {
                        array = Array.from(array);
                        cds.data[column] = array;
                    }
                    array.splice(0, drop);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (columns_1_1 && !columns_1_1.done && (_b = columns_1.return))
                        _b.call(columns_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        };
        EditToolView.prototype._emit_cds_changes = function (cds, redraw, clear, emit) {
            if (redraw === void 0) {
                redraw = true;
            }
            if (clear === void 0) {
                clear = true;
            }
            if (emit === void 0) {
                emit = true;
            }
            if (clear)
                cds.selection_manager.clear();
            if (redraw)
                cds.change.emit();
            if (emit) {
                cds.data = cds.data;
                cds.properties.data.change.emit();
            }
        };
        EditToolView.prototype._drag_points = function (ev, renderers, dim) {
            var e_3, _b, e_4, _c;
            if (dim === void 0) {
                dim = "both";
            }
            if (this._basepoint == null)
                return;
            var _d = (0, tslib_1.__read)(this._basepoint, 2), bx = _d[0], by = _d[1];
            try {
                for (var renderers_1 = (0, tslib_1.__values)(renderers), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                    var renderer = renderers_1_1.value;
                    var basepoint = this._map_drag(bx, by, renderer);
                    var point = this._map_drag(ev.sx, ev.sy, renderer);
                    if (point == null || basepoint == null) {
                        continue;
                    }
                    var _f = (0, tslib_1.__read)(point, 2), x = _f[0], y = _f[1];
                    var _g = (0, tslib_1.__read)(basepoint, 2), px = _g[0], py = _g[1];
                    var _h = (0, tslib_1.__read)([x - px, y - py], 2), dx = _h[0], dy = _h[1];
                    // Type once dataspecs are typed
                    var glyph = renderer.glyph;
                    var cds = renderer.data_source;
                    var _j = (0, tslib_1.__read)([glyph.x.field, glyph.y.field], 2), xkey = _j[0], ykey = _j[1];
                    try {
                        for (var _k = (e_4 = void 0, (0, tslib_1.__values)(cds.selected.indices)), _l = _k.next(); !_l.done; _l = _k.next()) {
                            var index = _l.value;
                            if (xkey && (dim == "width" || dim == "both")) {
                                cds.data[xkey][index] += dx;
                            }
                            if (ykey && (dim == "height" || dim == "both")) {
                                cds.data[ykey][index] += dy;
                            }
                        }
                    }
                    catch (e_4_1) {
                        e_4 = { error: e_4_1 };
                    }
                    finally {
                        try {
                            if (_l && !_l.done && (_c = _k.return))
                                _c.call(_k);
                        }
                        finally {
                            if (e_4)
                                throw e_4.error;
                        }
                    }
                    cds.change.emit();
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (renderers_1_1 && !renderers_1_1.done && (_b = renderers_1.return))
                        _b.call(renderers_1);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            this._basepoint = [ev.sx, ev.sy];
        };
        EditToolView.prototype._pad_empty_columns = function (cds, coord_columns) {
            var e_5, _b;
            try {
                // Pad ColumnDataSource non-coordinate columns with empty_value
                for (var _c = (0, tslib_1.__values)(cds.columns()), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var column = _d.value;
                    if (!(0, array_1.includes)(coord_columns, column))
                        cds.get_array(column).push(this.model.empty_value);
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
        };
        EditToolView.prototype._select_event = function (ev, mode, renderers) {
            var e_6, _b;
            // Process selection event on the supplied renderers and return selected renderers
            var frame = this.plot_view.frame;
            var sx = ev.sx, sy = ev.sy;
            if (!frame.bbox.contains(sx, sy)) {
                return [];
            }
            var geometry = { type: "point", sx: sx, sy: sy };
            var selected = [];
            try {
                for (var renderers_2 = (0, tslib_1.__values)(renderers), renderers_2_1 = renderers_2.next(); !renderers_2_1.done; renderers_2_1 = renderers_2.next()) {
                    var renderer = renderers_2_1.value;
                    var sm = renderer.get_selection_manager();
                    var cds = renderer.data_source;
                    var view = this.plot_view.renderer_view(renderer);
                    if (view != null) {
                        var did_hit = sm.select([view], geometry, true, mode);
                        if (did_hit) {
                            selected.push(renderer);
                        }
                        cds.properties.selected.change.emit();
                    }
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (renderers_2_1 && !renderers_2_1.done && (_b = renderers_2.return))
                        _b.call(renderers_2);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            return selected;
        };
        return EditToolView;
    }(gesture_tool_1.GestureToolView));
    exports.EditToolView = EditToolView;
    EditToolView.__name__ = "EditToolView";
    var EditTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(EditTool, _super);
        function EditTool(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(EditTool.prototype, "computed_icon", {
            get: function () {
                var _b;
                return (_b = this.custom_icon) !== null && _b !== void 0 ? _b : this.icon;
            },
            enumerable: false,
            configurable: true
        });
        return EditTool;
    }(gesture_tool_1.GestureTool));
    exports.EditTool = EditTool;
    _a = EditTool;
    EditTool.__name__ = "EditTool";
    (function () {
        _a.define(function (_b) {
            var Unknown = _b.Unknown, String = _b.String, Array = _b.Array, Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                custom_icon: [Nullable(String), null],
                empty_value: [Unknown],
                renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
            });
        });
    })();
},
/* models/tools/edit/box_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var dom_1 = require(158) /* ../../../core/dom */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var edit_tool_1 = require(485) /* ./edit_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var BoxEditToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxEditToolView, _super);
        function BoxEditToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BoxEditToolView.prototype._tap = function (ev) {
            if ((this._draw_basepoint != null) || (this._basepoint != null))
                return;
            this._select_event(ev, this._select_mode(ev), this.model.renderers);
        };
        BoxEditToolView.prototype._keyup = function (ev) {
            var e_1, _b;
            if (!this.model.active || !this._mouse_in_frame)
                return;
            try {
                for (var _c = (0, tslib_1.__values)(this.model.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var renderer = _d.value;
                    if (ev.keyCode === dom_1.Keys.Backspace) {
                        this._delete_selected(renderer);
                    }
                    else if (ev.keyCode == dom_1.Keys.Esc) {
                        // Type properly once selection_manager is typed
                        var cds = renderer.data_source;
                        cds.selection_manager.clear();
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        BoxEditToolView.prototype._set_extent = function (_b, _c, append, emit) {
            var _d = (0, tslib_1.__read)(_b, 2), sx0 = _d[0], sx1 = _d[1];
            var _e = (0, tslib_1.__read)(_c, 2), sy0 = _e[0], sy1 = _e[1];
            if (emit === void 0) {
                emit = false;
            }
            var renderer = this.model.renderers[0];
            var renderer_view = this.plot_view.renderer_view(renderer);
            if (renderer_view == null)
                return;
            // Type once dataspecs are typed
            var glyph = renderer.glyph;
            var cds = renderer.data_source;
            var _f = (0, tslib_1.__read)(renderer_view.coordinates.x_scale.r_invert(sx0, sx1), 2), x0 = _f[0], x1 = _f[1];
            var _g = (0, tslib_1.__read)(renderer_view.coordinates.y_scale.r_invert(sy0, sy1), 2), y0 = _g[0], y1 = _g[1];
            var _h = (0, tslib_1.__read)([(x0 + x1) / 2, (y0 + y1) / 2], 2), x = _h[0], y = _h[1];
            var _j = (0, tslib_1.__read)([x1 - x0, y1 - y0], 2), w = _j[0], h = _j[1];
            var _k = (0, tslib_1.__read)([glyph.x.field, glyph.y.field], 2), xkey = _k[0], ykey = _k[1];
            var _l = (0, tslib_1.__read)([glyph.width.field, glyph.height.field], 2), wkey = _l[0], hkey = _l[1];
            if (append) {
                this._pop_glyphs(cds, this.model.num_objects);
                if (xkey)
                    cds.get_array(xkey).push(x);
                if (ykey)
                    cds.get_array(ykey).push(y);
                if (wkey)
                    cds.get_array(wkey).push(w);
                if (hkey)
                    cds.get_array(hkey).push(h);
                this._pad_empty_columns(cds, [xkey, ykey, wkey, hkey]);
            }
            else {
                var index = cds.data[xkey].length - 1;
                if (xkey)
                    cds.data[xkey][index] = x;
                if (ykey)
                    cds.data[ykey][index] = y;
                if (wkey)
                    cds.data[wkey][index] = w;
                if (hkey)
                    cds.data[hkey][index] = h;
            }
            this._emit_cds_changes(cds, true, false, emit);
        };
        BoxEditToolView.prototype._update_box = function (ev, append, emit) {
            if (append === void 0) {
                append = false;
            }
            if (emit === void 0) {
                emit = false;
            }
            if (this._draw_basepoint == null)
                return;
            var curpoint = [ev.sx, ev.sy];
            var frame = this.plot_view.frame;
            var dims = this.model.dimensions;
            var limits = this.model._get_dim_limits(this._draw_basepoint, curpoint, frame, dims);
            if (limits != null) {
                var _b = (0, tslib_1.__read)(limits, 2), sxlim = _b[0], sylim = _b[1];
                this._set_extent(sxlim, sylim, append, emit);
            }
        };
        BoxEditToolView.prototype._doubletap = function (ev) {
            if (!this.model.active)
                return;
            if (this._draw_basepoint != null) {
                this._update_box(ev, false, true);
                this._draw_basepoint = null;
            }
            else {
                this._draw_basepoint = [ev.sx, ev.sy];
                this._select_event(ev, "append", this.model.renderers);
                this._update_box(ev, true, false);
            }
        };
        BoxEditToolView.prototype._move = function (ev) {
            this._update_box(ev, false, false);
        };
        BoxEditToolView.prototype._pan_start = function (ev) {
            if (ev.shiftKey) {
                if (this._draw_basepoint != null)
                    return;
                this._draw_basepoint = [ev.sx, ev.sy];
                this._update_box(ev, true, false);
            }
            else {
                if (this._basepoint != null)
                    return;
                this._select_event(ev, "append", this.model.renderers);
                this._basepoint = [ev.sx, ev.sy];
            }
        };
        BoxEditToolView.prototype._pan = function (ev, append, emit) {
            if (append === void 0) {
                append = false;
            }
            if (emit === void 0) {
                emit = false;
            }
            if (ev.shiftKey) {
                if (this._draw_basepoint == null)
                    return;
                this._update_box(ev, append, emit);
            }
            else {
                if (this._basepoint == null)
                    return;
                this._drag_points(ev, this.model.renderers);
            }
        };
        BoxEditToolView.prototype._pan_end = function (ev) {
            var e_2, _b;
            this._pan(ev, false, true);
            if (ev.shiftKey) {
                this._draw_basepoint = null;
            }
            else {
                this._basepoint = null;
                try {
                    for (var _c = (0, tslib_1.__values)(this.model.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var renderer = _d.value;
                        this._emit_cds_changes(renderer.data_source, false, true, true);
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_b = _c.return))
                            _b.call(_c);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
            }
        };
        return BoxEditToolView;
    }(edit_tool_1.EditToolView));
    exports.BoxEditToolView = BoxEditToolView;
    BoxEditToolView.__name__ = "BoxEditToolView";
    var BoxEditTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxEditTool, _super);
        function BoxEditTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Box Edit Tool";
            _this.icon = icons_css_1.tool_icon_box_edit;
            _this.event_type = ["tap", "pan", "move"];
            _this.default_order = 1;
            return _this;
        }
        return BoxEditTool;
    }(edit_tool_1.EditTool));
    exports.BoxEditTool = BoxEditTool;
    _a = BoxEditTool;
    BoxEditTool.__name__ = "BoxEditTool";
    (function () {
        _a.prototype.default_view = BoxEditToolView;
        _a.define(function (_b) {
            var Int = _b.Int;
            return ({
                dimensions: [enums_1.Dimensions, "both"],
                num_objects: [Int, 0],
            });
        });
    })();
},
/* models/tools/edit/freehand_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var dom_1 = require(158) /* ../../../core/dom */;
    var types_1 = require(125) /* ../../../core/util/types */;
    var edit_tool_1 = require(485) /* ./edit_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var FreehandDrawToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FreehandDrawToolView, _super);
        function FreehandDrawToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        FreehandDrawToolView.prototype._draw = function (ev, mode, emit) {
            if (emit === void 0) {
                emit = false;
            }
            if (!this.model.active)
                return;
            var renderer = this.model.renderers[0];
            var point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            var _b = (0, tslib_1.__read)(point, 2), x = _b[0], y = _b[1];
            var cds = renderer.data_source;
            var glyph = renderer.glyph;
            var _c = (0, tslib_1.__read)([glyph.xs.field, glyph.ys.field], 2), xkey = _c[0], ykey = _c[1];
            if (mode == "new") {
                this._pop_glyphs(cds, this.model.num_objects);
                if (xkey)
                    cds.get_array(xkey).push([x]);
                if (ykey)
                    cds.get_array(ykey).push([y]);
                this._pad_empty_columns(cds, [xkey, ykey]);
            }
            else if (mode == "add") {
                if (xkey) {
                    var xidx = cds.data[xkey].length - 1;
                    var xs = cds.get_array(xkey)[xidx];
                    if (!(0, types_1.isArray)(xs)) {
                        xs = Array.from(xs);
                        cds.data[xkey][xidx] = xs;
                    }
                    xs.push(x);
                }
                if (ykey) {
                    var yidx = cds.data[ykey].length - 1;
                    var ys = cds.get_array(ykey)[yidx];
                    if (!(0, types_1.isArray)(ys)) {
                        ys = Array.from(ys);
                        cds.data[ykey][yidx] = ys;
                    }
                    ys.push(y);
                }
            }
            this._emit_cds_changes(cds, true, true, emit);
        };
        FreehandDrawToolView.prototype._pan_start = function (ev) {
            this._draw(ev, "new");
        };
        FreehandDrawToolView.prototype._pan = function (ev) {
            this._draw(ev, "add");
        };
        FreehandDrawToolView.prototype._pan_end = function (ev) {
            this._draw(ev, "add", true);
        };
        FreehandDrawToolView.prototype._tap = function (ev) {
            this._select_event(ev, this._select_mode(ev), this.model.renderers);
        };
        FreehandDrawToolView.prototype._keyup = function (ev) {
            var e_1, _b;
            if (!this.model.active || !this._mouse_in_frame)
                return;
            try {
                for (var _c = (0, tslib_1.__values)(this.model.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var renderer = _d.value;
                    if (ev.keyCode === dom_1.Keys.Esc) {
                        renderer.data_source.selection_manager.clear();
                    }
                    else if (ev.keyCode === dom_1.Keys.Backspace) {
                        this._delete_selected(renderer);
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        return FreehandDrawToolView;
    }(edit_tool_1.EditToolView));
    exports.FreehandDrawToolView = FreehandDrawToolView;
    FreehandDrawToolView.__name__ = "FreehandDrawToolView";
    var FreehandDrawTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(FreehandDrawTool, _super);
        function FreehandDrawTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Freehand Draw Tool";
            _this.icon = icons_css_1.tool_icon_freehand_draw;
            _this.event_type = ["pan", "tap"];
            _this.default_order = 3;
            return _this;
        }
        return FreehandDrawTool;
    }(edit_tool_1.EditTool));
    exports.FreehandDrawTool = FreehandDrawTool;
    _a = FreehandDrawTool;
    FreehandDrawTool.__name__ = "FreehandDrawTool";
    (function () {
        _a.prototype.default_view = FreehandDrawToolView;
        _a.define(function (_b) {
            var Int = _b.Int;
            return ({
                num_objects: [Int, 0],
            });
        });
        _a.register_alias("freehand_draw", function () { return new FreehandDrawTool(); });
    })();
},
/* models/tools/edit/point_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var dom_1 = require(158) /* ../../../core/dom */;
    var edit_tool_1 = require(485) /* ./edit_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var PointDrawToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PointDrawToolView, _super);
        function PointDrawToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PointDrawToolView.prototype._tap = function (ev) {
            var renderers = this._select_event(ev, this._select_mode(ev), this.model.renderers);
            if (renderers.length || !this.model.add) {
                return;
            }
            var renderer = this.model.renderers[0];
            var point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            // Type once dataspecs are typed
            var glyph = renderer.glyph;
            var cds = renderer.data_source;
            var _b = (0, tslib_1.__read)([glyph.x.field, glyph.y.field], 2), xkey = _b[0], ykey = _b[1];
            var _c = (0, tslib_1.__read)(point, 2), x = _c[0], y = _c[1];
            this._pop_glyphs(cds, this.model.num_objects);
            if (xkey)
                cds.get_array(xkey).push(x);
            if (ykey)
                cds.get_array(ykey).push(y);
            this._pad_empty_columns(cds, [xkey, ykey]);
            cds.change.emit();
            cds.data = cds.data;
            cds.properties.data.change.emit();
        };
        PointDrawToolView.prototype._keyup = function (ev) {
            var e_1, _b;
            if (!this.model.active || !this._mouse_in_frame)
                return;
            try {
                for (var _c = (0, tslib_1.__values)(this.model.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var renderer = _d.value;
                    if (ev.keyCode === dom_1.Keys.Backspace) {
                        this._delete_selected(renderer);
                    }
                    else if (ev.keyCode == dom_1.Keys.Esc) {
                        renderer.data_source.selection_manager.clear();
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        PointDrawToolView.prototype._pan_start = function (ev) {
            if (!this.model.drag)
                return;
            this._select_event(ev, "append", this.model.renderers);
            this._basepoint = [ev.sx, ev.sy];
        };
        PointDrawToolView.prototype._pan = function (ev) {
            if (!this.model.drag || this._basepoint == null)
                return;
            this._drag_points(ev, this.model.renderers);
        };
        PointDrawToolView.prototype._pan_end = function (ev) {
            var e_2, _b;
            if (!this.model.drag)
                return;
            this._pan(ev);
            try {
                for (var _c = (0, tslib_1.__values)(this.model.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var renderer = _d.value;
                    this._emit_cds_changes(renderer.data_source, false, true, true);
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            this._basepoint = null;
        };
        return PointDrawToolView;
    }(edit_tool_1.EditToolView));
    exports.PointDrawToolView = PointDrawToolView;
    PointDrawToolView.__name__ = "PointDrawToolView";
    var PointDrawTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PointDrawTool, _super);
        function PointDrawTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Point Draw Tool";
            _this.icon = icons_css_1.tool_icon_point_draw;
            _this.event_type = ["tap", "pan", "move"];
            _this.default_order = 2;
            return _this;
        }
        return PointDrawTool;
    }(edit_tool_1.EditTool));
    exports.PointDrawTool = PointDrawTool;
    _a = PointDrawTool;
    PointDrawTool.__name__ = "PointDrawTool";
    (function () {
        _a.prototype.default_view = PointDrawToolView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Int = _b.Int;
            return ({
                add: [Boolean, true],
                drag: [Boolean, true],
                num_objects: [Int, 0],
            });
        });
    })();
},
/* models/tools/edit/poly_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var dom_1 = require(158) /* ../../../core/dom */;
    var types_1 = require(125) /* ../../../core/util/types */;
    var poly_tool_1 = require(490) /* ./poly_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var PolyDrawToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolyDrawToolView, _super);
        function PolyDrawToolView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._drawing = false;
            _this._initialized = false;
            return _this;
        }
        PolyDrawToolView.prototype._tap = function (ev) {
            if (this._drawing)
                this._draw(ev, "add", true);
            else
                this._select_event(ev, this._select_mode(ev), this.model.renderers);
        };
        PolyDrawToolView.prototype._draw = function (ev, mode, emit) {
            if (emit === void 0) {
                emit = false;
            }
            var renderer = this.model.renderers[0];
            var point = this._map_drag(ev.sx, ev.sy, renderer);
            if (!this._initialized)
                this.activate(); // Ensure that activate has been called
            if (point == null)
                return;
            var _b = (0, tslib_1.__read)(this._snap_to_vertex.apply(this, (0, tslib_1.__spreadArray)([ev], (0, tslib_1.__read)(point), false)), 2), x = _b[0], y = _b[1];
            var cds = renderer.data_source;
            var glyph = renderer.glyph;
            var _c = (0, tslib_1.__read)([glyph.xs.field, glyph.ys.field], 2), xkey = _c[0], ykey = _c[1];
            if (mode == "new") {
                this._pop_glyphs(cds, this.model.num_objects);
                if (xkey)
                    cds.get_array(xkey).push([x, x]);
                if (ykey)
                    cds.get_array(ykey).push([y, y]);
                this._pad_empty_columns(cds, [xkey, ykey]);
            }
            else if (mode == "edit") {
                if (xkey) {
                    var xs = cds.data[xkey][cds.data[xkey].length - 1];
                    xs[xs.length - 1] = x;
                }
                if (ykey) {
                    var ys = cds.data[ykey][cds.data[ykey].length - 1];
                    ys[ys.length - 1] = y;
                }
            }
            else if (mode == "add") {
                if (xkey) {
                    var xidx = cds.data[xkey].length - 1;
                    var xs = cds.get_array(xkey)[xidx];
                    var nx = xs[xs.length - 1];
                    xs[xs.length - 1] = x;
                    if (!(0, types_1.isArray)(xs)) {
                        xs = Array.from(xs);
                        cds.data[xkey][xidx] = xs;
                    }
                    xs.push(nx);
                }
                if (ykey) {
                    var yidx = cds.data[ykey].length - 1;
                    var ys = cds.get_array(ykey)[yidx];
                    var ny = ys[ys.length - 1];
                    ys[ys.length - 1] = y;
                    if (!(0, types_1.isArray)(ys)) {
                        ys = Array.from(ys);
                        cds.data[ykey][yidx] = ys;
                    }
                    ys.push(ny);
                }
            }
            this._emit_cds_changes(cds, true, false, emit);
        };
        PolyDrawToolView.prototype._show_vertices = function () {
            var e_1, _b, e_2, _c;
            if (!this.model.active) {
                return;
            }
            var xs = [];
            var ys = [];
            for (var i = 0; i < this.model.renderers.length; i++) {
                var renderer = this.model.renderers[i];
                var cds = renderer.data_source;
                var glyph = renderer.glyph;
                var _d = (0, tslib_1.__read)([glyph.xs.field, glyph.ys.field], 2), xkey = _d[0], ykey = _d[1];
                if (xkey) {
                    try {
                        for (var _e = (e_1 = void 0, (0, tslib_1.__values)(cds.get_array(xkey))), _f = _e.next(); !_f.done; _f = _e.next()) {
                            var array = _f.value;
                            xs.push.apply(xs, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(array), false));
                        }
                    }
                    catch (e_1_1) {
                        e_1 = { error: e_1_1 };
                    }
                    finally {
                        try {
                            if (_f && !_f.done && (_b = _e.return))
                                _b.call(_e);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                    }
                }
                if (ykey) {
                    try {
                        for (var _g = (e_2 = void 0, (0, tslib_1.__values)(cds.get_array(ykey))), _h = _g.next(); !_h.done; _h = _g.next()) {
                            var array = _h.value;
                            ys.push.apply(ys, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(array), false));
                        }
                    }
                    catch (e_2_1) {
                        e_2 = { error: e_2_1 };
                    }
                    finally {
                        try {
                            if (_h && !_h.done && (_c = _g.return))
                                _c.call(_g);
                        }
                        finally {
                            if (e_2)
                                throw e_2.error;
                        }
                    }
                }
                if (this._drawing && (i == (this.model.renderers.length - 1))) {
                    // Skip currently drawn vertex
                    xs.splice(xs.length - 1, 1);
                    ys.splice(ys.length - 1, 1);
                }
            }
            this._set_vertices(xs, ys);
        };
        PolyDrawToolView.prototype._doubletap = function (ev) {
            if (!this.model.active)
                return;
            if (this._drawing) {
                this._drawing = false;
                this._draw(ev, "edit", true);
            }
            else {
                this._drawing = true;
                this._draw(ev, "new", true);
            }
        };
        PolyDrawToolView.prototype._move = function (ev) {
            if (this._drawing) {
                this._draw(ev, "edit");
            }
        };
        PolyDrawToolView.prototype._remove = function () {
            var renderer = this.model.renderers[0];
            var cds = renderer.data_source;
            var glyph = renderer.glyph;
            var _b = (0, tslib_1.__read)([glyph.xs.field, glyph.ys.field], 2), xkey = _b[0], ykey = _b[1];
            if (xkey) {
                var xidx = cds.data[xkey].length - 1;
                var xs = cds.get_array(xkey)[xidx];
                xs.splice(xs.length - 1, 1);
            }
            if (ykey) {
                var yidx = cds.data[ykey].length - 1;
                var ys = cds.get_array(ykey)[yidx];
                ys.splice(ys.length - 1, 1);
            }
            this._emit_cds_changes(cds);
        };
        PolyDrawToolView.prototype._keyup = function (ev) {
            var e_3, _b;
            if (!this.model.active || !this._mouse_in_frame)
                return;
            try {
                for (var _c = (0, tslib_1.__values)(this.model.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var renderer = _d.value;
                    if (ev.keyCode === dom_1.Keys.Backspace) {
                        this._delete_selected(renderer);
                    }
                    else if (ev.keyCode == dom_1.Keys.Esc) {
                        if (this._drawing) {
                            this._remove();
                            this._drawing = false;
                        }
                        renderer.data_source.selection_manager.clear();
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
        };
        PolyDrawToolView.prototype._pan_start = function (ev) {
            if (!this.model.drag)
                return;
            this._select_event(ev, "append", this.model.renderers);
            this._basepoint = [ev.sx, ev.sy];
        };
        PolyDrawToolView.prototype._pan = function (ev) {
            var e_4, _b, e_5, _c;
            if (this._basepoint == null || !this.model.drag)
                return;
            var _d = (0, tslib_1.__read)(this._basepoint, 2), bx = _d[0], by = _d[1];
            try {
                // Process polygon/line dragging
                for (var _e = (0, tslib_1.__values)(this.model.renderers), _f = _e.next(); !_f.done; _f = _e.next()) {
                    var renderer = _f.value;
                    var basepoint = this._map_drag(bx, by, renderer);
                    var point = this._map_drag(ev.sx, ev.sy, renderer);
                    if (point == null || basepoint == null)
                        continue;
                    var cds = renderer.data_source;
                    // Type once dataspecs are typed
                    var glyph = renderer.glyph;
                    var _g = (0, tslib_1.__read)([glyph.xs.field, glyph.ys.field], 2), xkey = _g[0], ykey = _g[1];
                    if (!xkey && !ykey)
                        continue;
                    var _h = (0, tslib_1.__read)(point, 2), x = _h[0], y = _h[1];
                    var _j = (0, tslib_1.__read)(basepoint, 2), px = _j[0], py = _j[1];
                    var _k = (0, tslib_1.__read)([x - px, y - py], 2), dx = _k[0], dy = _k[1];
                    try {
                        for (var _l = (e_5 = void 0, (0, tslib_1.__values)(cds.selected.indices)), _m = _l.next(); !_m.done; _m = _l.next()) {
                            var index = _m.value;
                            var length = void 0, xs = void 0, ys = void 0;
                            if (xkey)
                                xs = cds.data[xkey][index];
                            if (ykey) {
                                ys = cds.data[ykey][index];
                                length = ys.length;
                            }
                            else {
                                length = xs.length;
                            }
                            for (var i = 0; i < length; i++) {
                                if (xs)
                                    xs[i] += dx;
                                if (ys)
                                    ys[i] += dy;
                            }
                        }
                    }
                    catch (e_5_1) {
                        e_5 = { error: e_5_1 };
                    }
                    finally {
                        try {
                            if (_m && !_m.done && (_c = _l.return))
                                _c.call(_l);
                        }
                        finally {
                            if (e_5)
                                throw e_5.error;
                        }
                    }
                    cds.change.emit();
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_f && !_f.done && (_b = _e.return))
                        _b.call(_e);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            this._basepoint = [ev.sx, ev.sy];
        };
        PolyDrawToolView.prototype._pan_end = function (ev) {
            var e_6, _b;
            if (!this.model.drag)
                return;
            this._pan(ev);
            try {
                for (var _c = (0, tslib_1.__values)(this.model.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var renderer = _d.value;
                    this._emit_cds_changes(renderer.data_source);
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            this._basepoint = null;
        };
        PolyDrawToolView.prototype.activate = function () {
            var e_7, _b;
            var _this = this;
            if (!this.model.vertex_renderer || !this.model.active)
                return;
            this._show_vertices();
            if (!this._initialized) {
                try {
                    for (var _c = (0, tslib_1.__values)(this.model.renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var renderer = _d.value;
                        var cds = renderer.data_source;
                        cds.connect(cds.properties.data.change, function () { return _this._show_vertices(); });
                    }
                }
                catch (e_7_1) {
                    e_7 = { error: e_7_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_b = _c.return))
                            _b.call(_c);
                    }
                    finally {
                        if (e_7)
                            throw e_7.error;
                    }
                }
            }
            this._initialized = true;
        };
        PolyDrawToolView.prototype.deactivate = function () {
            if (this._drawing) {
                this._remove();
                this._drawing = false;
            }
            if (this.model.vertex_renderer)
                this._hide_vertices();
        };
        return PolyDrawToolView;
    }(poly_tool_1.PolyToolView));
    exports.PolyDrawToolView = PolyDrawToolView;
    PolyDrawToolView.__name__ = "PolyDrawToolView";
    var PolyDrawTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolyDrawTool, _super);
        function PolyDrawTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Polygon Draw Tool";
            _this.icon = icons_css_1.tool_icon_poly_draw;
            _this.event_type = ["pan", "tap", "move"];
            _this.default_order = 3;
            return _this;
        }
        return PolyDrawTool;
    }(poly_tool_1.PolyTool));
    exports.PolyDrawTool = PolyDrawTool;
    _a = PolyDrawTool;
    PolyDrawTool.__name__ = "PolyDrawTool";
    (function () {
        _a.prototype.default_view = PolyDrawToolView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Int = _b.Int;
            return ({
                drag: [Boolean, true],
                num_objects: [Int, 0],
            });
        });
    })();
},
/* models/tools/edit/poly_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var types_1 = require(125) /* ../../../core/util/types */;
    var edit_tool_1 = require(485) /* ./edit_tool */;
    var PolyToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolyToolView, _super);
        function PolyToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PolyToolView.prototype._set_vertices = function (xs, ys) {
            var point_glyph = this.model.vertex_renderer.glyph;
            var point_cds = this.model.vertex_renderer.data_source;
            var _b = (0, tslib_1.__read)([point_glyph.x.field, point_glyph.y.field], 2), pxkey = _b[0], pykey = _b[1];
            if (pxkey) {
                if ((0, types_1.isArray)(xs))
                    point_cds.data[pxkey] = xs;
                else
                    point_glyph.x = { value: xs };
            }
            if (pykey) {
                if ((0, types_1.isArray)(ys))
                    point_cds.data[pykey] = ys;
                else
                    point_glyph.y = { value: ys };
            }
            this._emit_cds_changes(point_cds, true, true, false);
        };
        PolyToolView.prototype._hide_vertices = function () {
            this._set_vertices([], []);
        };
        PolyToolView.prototype._snap_to_vertex = function (ev, x, y) {
            if (this.model.vertex_renderer) {
                // If an existing vertex is hit snap to it
                var vertex_selected = this._select_event(ev, "replace", [this.model.vertex_renderer]);
                var point_ds = this.model.vertex_renderer.data_source;
                // Type once dataspecs are typed
                var point_glyph = this.model.vertex_renderer.glyph;
                var _b = (0, tslib_1.__read)([point_glyph.x.field, point_glyph.y.field], 2), pxkey = _b[0], pykey = _b[1];
                if (vertex_selected.length) {
                    var index = point_ds.selected.indices[0];
                    if (pxkey)
                        x = point_ds.data[pxkey][index];
                    if (pykey)
                        y = point_ds.data[pykey][index];
                    point_ds.selection_manager.clear();
                }
            }
            return [x, y];
        };
        return PolyToolView;
    }(edit_tool_1.EditToolView));
    exports.PolyToolView = PolyToolView;
    PolyToolView.__name__ = "PolyToolView";
    var PolyTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolyTool, _super);
        function PolyTool(attrs) {
            return _super.call(this, attrs) || this;
        }
        return PolyTool;
    }(edit_tool_1.EditTool));
    exports.PolyTool = PolyTool;
    _a = PolyTool;
    PolyTool.__name__ = "PolyTool";
    (function () {
        _a.define(function (_b) {
            var AnyRef = _b.AnyRef;
            return ({
                vertex_renderer: [AnyRef()],
            });
        });
    })();
},
/* models/tools/edit/poly_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var dom_1 = require(158) /* ../../../core/dom */;
    var types_1 = require(125) /* ../../../core/util/types */;
    var poly_tool_1 = require(490) /* ./poly_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var PolyEditToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolyEditToolView, _super);
        function PolyEditToolView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._drawing = false;
            _this._cur_index = null;
            return _this;
        }
        PolyEditToolView.prototype._doubletap = function (ev) {
            if (!this.model.active)
                return;
            var point = this._map_drag(ev.sx, ev.sy, this.model.vertex_renderer);
            if (point == null)
                return;
            var _b = (0, tslib_1.__read)(point, 2), x = _b[0], y = _b[1];
            // Perform hit testing
            var vertex_selected = this._select_event(ev, "replace", [this.model.vertex_renderer]);
            var point_cds = this.model.vertex_renderer.data_source;
            // Type once dataspecs are typed
            var point_glyph = this.model.vertex_renderer.glyph;
            var _c = (0, tslib_1.__read)([point_glyph.x.field, point_glyph.y.field], 2), pxkey = _c[0], pykey = _c[1];
            if (vertex_selected.length && this._selected_renderer != null) {
                // Insert a new point after the selected vertex and enter draw mode
                var index = point_cds.selected.indices[0];
                if (this._drawing) {
                    this._drawing = false;
                    point_cds.selection_manager.clear();
                }
                else {
                    point_cds.selected.indices = [index + 1];
                    if (pxkey)
                        point_cds.get_array(pxkey).splice(index + 1, 0, x);
                    if (pykey)
                        point_cds.get_array(pykey).splice(index + 1, 0, y);
                    this._drawing = true;
                }
                point_cds.change.emit();
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            else {
                this._show_vertices(ev);
            }
        };
        PolyEditToolView.prototype._show_vertices = function (ev) {
            var _this = this;
            if (!this.model.active)
                return;
            var vsync_renderer = this.model.renderers[0];
            var vsync_updater = function () { return _this._update_vertices(vsync_renderer); };
            var vsync_ds = vsync_renderer === null || vsync_renderer === void 0 ? void 0 : vsync_renderer.data_source;
            var renderers = this._select_event(ev, "replace", this.model.renderers);
            if (!renderers.length) {
                this._set_vertices([], []);
                this._selected_renderer = null;
                this._drawing = false;
                this._cur_index = null;
                if (vsync_ds != null)
                    vsync_ds.disconnect(vsync_ds.properties.data.change, vsync_updater);
                return;
            }
            if (vsync_ds != null)
                vsync_ds.connect(vsync_ds.properties.data.change, vsync_updater);
            this._cur_index = renderers[0].data_source.selected.indices[0];
            this._update_vertices(renderers[0]);
        };
        PolyEditToolView.prototype._update_vertices = function (renderer) {
            var glyph = renderer.glyph;
            var cds = renderer.data_source;
            var index = this._cur_index;
            var _b = (0, tslib_1.__read)([glyph.xs.field, glyph.ys.field], 2), xkey = _b[0], ykey = _b[1];
            if (this._drawing)
                return;
            if ((index == null) && (xkey || ykey))
                return;
            var xs;
            var ys;
            if (xkey && index != null) { // redundant xkey null check to satisfy build-time checks
                xs = cds.data[xkey][index];
                if (!(0, types_1.isArray)(xs))
                    cds.data[xkey][index] = xs = Array.from(xs);
            }
            else {
                xs = glyph.xs.value;
            }
            if (ykey && index != null) {
                ys = cds.data[ykey][index];
                if (!(0, types_1.isArray)(ys))
                    cds.data[ykey][index] = ys = Array.from(ys);
            }
            else {
                ys = glyph.ys.value;
            }
            this._selected_renderer = renderer;
            this._set_vertices(xs, ys);
        };
        PolyEditToolView.prototype._move = function (ev) {
            var _b;
            if (this._drawing && this._selected_renderer != null) {
                var renderer = this.model.vertex_renderer;
                var cds = renderer.data_source;
                var glyph = renderer.glyph;
                var point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null)
                    return;
                var _c = (0, tslib_1.__read)(point, 2), x = _c[0], y = _c[1];
                var indices = cds.selected.indices;
                _b = (0, tslib_1.__read)(this._snap_to_vertex(ev, x, y), 2), x = _b[0], y = _b[1];
                cds.selected.indices = indices;
                var _d = (0, tslib_1.__read)([glyph.x.field, glyph.y.field], 2), xkey = _d[0], ykey = _d[1];
                var index = indices[0];
                if (xkey)
                    cds.data[xkey][index] = x;
                if (ykey)
                    cds.data[ykey][index] = y;
                cds.change.emit();
                this._selected_renderer.data_source.change.emit();
            }
        };
        PolyEditToolView.prototype._tap = function (ev) {
            var _b;
            var renderer = this.model.vertex_renderer;
            var point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            else if (this._drawing && this._selected_renderer) {
                var _c = (0, tslib_1.__read)(point, 2), x = _c[0], y = _c[1];
                var cds = renderer.data_source;
                // Type once dataspecs are typed
                var glyph = renderer.glyph;
                var _d = (0, tslib_1.__read)([glyph.x.field, glyph.y.field], 2), xkey = _d[0], ykey = _d[1];
                var indices = cds.selected.indices;
                _b = (0, tslib_1.__read)(this._snap_to_vertex(ev, x, y), 2), x = _b[0], y = _b[1];
                var index = indices[0];
                cds.selected.indices = [index + 1];
                if (xkey) {
                    var xs = cds.get_array(xkey);
                    var nx = xs[index];
                    xs[index] = x;
                    xs.splice(index + 1, 0, nx);
                }
                if (ykey) {
                    var ys = cds.get_array(ykey);
                    var ny = ys[index];
                    ys[index] = y;
                    ys.splice(index + 1, 0, ny);
                }
                cds.change.emit();
                this._emit_cds_changes(this._selected_renderer.data_source, true, false, true);
                return;
            }
            var mode = this._select_mode(ev);
            this._select_event(ev, mode, [renderer]);
            this._select_event(ev, mode, this.model.renderers);
        };
        PolyEditToolView.prototype._remove_vertex = function () {
            if (!this._drawing || !this._selected_renderer)
                return;
            var renderer = this.model.vertex_renderer;
            var cds = renderer.data_source;
            // Type once dataspecs are typed
            var glyph = renderer.glyph;
            var index = cds.selected.indices[0];
            var _b = (0, tslib_1.__read)([glyph.x.field, glyph.y.field], 2), xkey = _b[0], ykey = _b[1];
            if (xkey)
                cds.get_array(xkey).splice(index, 1);
            if (ykey)
                cds.get_array(ykey).splice(index, 1);
            cds.change.emit();
            this._emit_cds_changes(this._selected_renderer.data_source);
        };
        PolyEditToolView.prototype._pan_start = function (ev) {
            this._select_event(ev, "append", [this.model.vertex_renderer]);
            this._basepoint = [ev.sx, ev.sy];
        };
        PolyEditToolView.prototype._pan = function (ev) {
            if (this._basepoint == null)
                return;
            this._drag_points(ev, [this.model.vertex_renderer]);
            if (this._selected_renderer)
                this._selected_renderer.data_source.change.emit();
        };
        PolyEditToolView.prototype._pan_end = function (ev) {
            if (this._basepoint == null)
                return;
            this._drag_points(ev, [this.model.vertex_renderer]);
            this._emit_cds_changes(this.model.vertex_renderer.data_source, false, true, true);
            if (this._selected_renderer) {
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            this._basepoint = null;
        };
        PolyEditToolView.prototype._keyup = function (ev) {
            var e_1, _b;
            if (!this.model.active || !this._mouse_in_frame)
                return;
            var renderers;
            if (this._selected_renderer) {
                renderers = [this.model.vertex_renderer];
            }
            else {
                renderers = this.model.renderers;
            }
            try {
                for (var renderers_1 = (0, tslib_1.__values)(renderers), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                    var renderer = renderers_1_1.value;
                    if (ev.keyCode === dom_1.Keys.Backspace) {
                        this._delete_selected(renderer);
                        if (this._selected_renderer) {
                            this._emit_cds_changes(this._selected_renderer.data_source);
                        }
                    }
                    else if (ev.keyCode == dom_1.Keys.Esc) {
                        if (this._drawing) {
                            this._remove_vertex();
                            this._drawing = false;
                        }
                        else if (this._selected_renderer) {
                            this._hide_vertices();
                        }
                        renderer.data_source.selection_manager.clear();
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (renderers_1_1 && !renderers_1_1.done && (_b = renderers_1.return))
                        _b.call(renderers_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        PolyEditToolView.prototype.deactivate = function () {
            if (!this._selected_renderer) {
                return;
            }
            else if (this._drawing) {
                this._remove_vertex();
                this._drawing = false;
            }
            this._hide_vertices();
        };
        return PolyEditToolView;
    }(poly_tool_1.PolyToolView));
    exports.PolyEditToolView = PolyEditToolView;
    PolyEditToolView.__name__ = "PolyEditToolView";
    var PolyEditTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolyEditTool, _super);
        function PolyEditTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Poly Edit Tool";
            _this.icon = icons_css_1.tool_icon_poly_edit;
            _this.event_type = ["tap", "pan", "move"];
            _this.default_order = 4;
            return _this;
        }
        return PolyEditTool;
    }(poly_tool_1.PolyTool));
    exports.PolyEditTool = PolyEditTool;
    _a = PolyEditTool;
    PolyEditTool.__name__ = "PolyEditTool";
    (function () {
        _a.prototype.default_view = PolyEditToolView;
    })();
},
/* models/tools/gestures/box_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var select_tool_1 = require(493) /* ./select_tool */;
    var box_annotation_1 = require(231) /* ../../annotations/box_annotation */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var BoxSelectToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxSelectToolView, _super);
        function BoxSelectToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BoxSelectToolView.prototype._compute_limits = function (curpoint) {
            var frame = this.plot_view.frame;
            var dims = this.model.dimensions;
            var base_point = this._base_point;
            if (this.model.origin == "center") {
                var _b = (0, tslib_1.__read)(base_point, 2), cx = _b[0], cy = _b[1];
                var _c = (0, tslib_1.__read)(curpoint, 2), dx = _c[0], dy = _c[1];
                base_point = [cx - (dx - cx), cy - (dy - cy)];
            }
            return this.model._get_dim_limits(base_point, curpoint, frame, dims);
        };
        BoxSelectToolView.prototype._pan_start = function (ev) {
            var sx = ev.sx, sy = ev.sy;
            this._base_point = [sx, sy];
        };
        BoxSelectToolView.prototype._pan = function (ev) {
            var sx = ev.sx, sy = ev.sy;
            var curpoint = [sx, sy];
            var _b = (0, tslib_1.__read)(this._compute_limits(curpoint), 2), sxlim = _b[0], sylim = _b[1];
            this.model.overlay.update({ left: sxlim[0], right: sxlim[1], top: sylim[0], bottom: sylim[1] });
            if (this.model.select_every_mousemove) {
                this._do_select(sxlim, sylim, false, this._select_mode(ev));
            }
        };
        BoxSelectToolView.prototype._pan_end = function (ev) {
            var sx = ev.sx, sy = ev.sy;
            var curpoint = [sx, sy];
            var _b = (0, tslib_1.__read)(this._compute_limits(curpoint), 2), sxlim = _b[0], sylim = _b[1];
            this._do_select(sxlim, sylim, true, this._select_mode(ev));
            this.model.overlay.update({ left: null, right: null, top: null, bottom: null });
            this._base_point = null;
            this.plot_view.state.push("box_select", { selection: this.plot_view.get_selection() });
        };
        BoxSelectToolView.prototype._do_select = function (_b, _c, final, mode) {
            var _d = (0, tslib_1.__read)(_b, 2), sx0 = _d[0], sx1 = _d[1];
            var _e = (0, tslib_1.__read)(_c, 2), sy0 = _e[0], sy1 = _e[1];
            if (mode === void 0) {
                mode = "replace";
            }
            var geometry = { type: "rect", sx0: sx0, sx1: sx1, sy0: sy0, sy1: sy1 };
            this._select(geometry, final, mode);
        };
        return BoxSelectToolView;
    }(select_tool_1.SelectToolView));
    exports.BoxSelectToolView = BoxSelectToolView;
    BoxSelectToolView.__name__ = "BoxSelectToolView";
    var DEFAULT_BOX_OVERLAY = function () {
        return new box_annotation_1.BoxAnnotation({
            level: "overlay",
            top_units: "screen",
            left_units: "screen",
            bottom_units: "screen",
            right_units: "screen",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    var BoxSelectTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxSelectTool, _super);
        function BoxSelectTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Box Select";
            _this.icon = icons_css_1.tool_icon_box_select;
            _this.event_type = "pan";
            _this.default_order = 30;
            return _this;
        }
        Object.defineProperty(BoxSelectTool.prototype, "tooltip", {
            get: function () {
                return this._get_dim_tooltip(this.dimensions);
            },
            enumerable: false,
            configurable: true
        });
        return BoxSelectTool;
    }(select_tool_1.SelectTool));
    exports.BoxSelectTool = BoxSelectTool;
    _a = BoxSelectTool;
    BoxSelectTool.__name__ = "BoxSelectTool";
    (function () {
        _a.prototype.default_view = BoxSelectToolView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Ref = _b.Ref;
            return ({
                dimensions: [enums_1.Dimensions, "both"],
                select_every_mousemove: [Boolean, false],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_BOX_OVERLAY],
                origin: [enums_1.BoxOrigin, "corner"],
            });
        });
        _a.register_alias("box_select", function () { return new BoxSelectTool(); });
        _a.register_alias("xbox_select", function () { return new BoxSelectTool({ dimensions: "width" }); });
        _a.register_alias("ybox_select", function () { return new BoxSelectTool({ dimensions: "height" }); });
    })();
},
/* models/tools/gestures/select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var gesture_tool_1 = require(338) /* ./gesture_tool */;
    var glyph_renderer_1 = require(290) /* ../../renderers/glyph_renderer */;
    var graph_renderer_1 = require(454) /* ../../renderers/graph_renderer */;
    var data_renderer_1 = require(291) /* ../../renderers/data_renderer */;
    var util_1 = require(181) /* ../../util */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var dom_1 = require(158) /* ../../../core/dom */;
    var bokeh_events_1 = require(366) /* ../../../core/bokeh_events */;
    var signaling_1 = require(130) /* ../../../core/signaling */;
    var assert_1 = require(127) /* ../../../core/util/assert */;
    var SelectToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SelectToolView, _super);
        function SelectToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        SelectToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.model.clear.connect(function () { return _this._clear(); });
        };
        Object.defineProperty(SelectToolView.prototype, "computed_renderers", {
            get: function () {
                var _b = this.model, renderers = _b.renderers, names = _b.names;
                var all_renderers = this.plot_model.data_renderers;
                return (0, util_1.compute_renderers)(renderers, all_renderers, names);
            },
            enumerable: false,
            configurable: true
        });
        SelectToolView.prototype._computed_renderers_by_data_source = function () {
            var e_1, _b;
            var _c;
            var renderers_by_source = new Map();
            try {
                for (var _d = (0, tslib_1.__values)(this.computed_renderers), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var r = _e.value;
                    var source = void 0;
                    if (r instanceof glyph_renderer_1.GlyphRenderer)
                        source = r.data_source;
                    else if (r instanceof graph_renderer_1.GraphRenderer)
                        source = r.node_renderer.data_source;
                    else
                        continue;
                    var renderers = (_c = renderers_by_source.get(source)) !== null && _c !== void 0 ? _c : [];
                    renderers_by_source.set(source, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(renderers), false), [r], false));
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            return renderers_by_source;
        };
        SelectToolView.prototype._select_mode = function (ev) {
            var shiftKey = ev.shiftKey, ctrlKey = ev.ctrlKey;
            if (!shiftKey && !ctrlKey)
                return this.model.mode;
            else if (shiftKey && !ctrlKey)
                return "append";
            else if (!shiftKey && ctrlKey)
                return "intersect";
            else if (shiftKey && ctrlKey)
                return "subtract";
            else
                (0, assert_1.unreachable)();
        };
        SelectToolView.prototype._keyup = function (ev) {
            if (ev.keyCode == dom_1.Keys.Esc) {
                this._clear();
            }
        };
        SelectToolView.prototype._clear = function () {
            var e_2, _b;
            var _this = this;
            try {
                for (var _c = (0, tslib_1.__values)(this.computed_renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var renderer = _d.value;
                    renderer.get_selection_manager().clear();
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            var renderer_views = this.computed_renderers.map(function (r) { return _this.plot_view.renderer_view(r); });
            this.plot_view.request_paint(renderer_views);
        };
        SelectToolView.prototype._select = function (geometry, final, mode) {
            var e_3, _b, e_4, _c;
            var renderers_by_source = this._computed_renderers_by_data_source();
            try {
                for (var renderers_by_source_1 = (0, tslib_1.__values)(renderers_by_source), renderers_by_source_1_1 = renderers_by_source_1.next(); !renderers_by_source_1_1.done; renderers_by_source_1_1 = renderers_by_source_1.next()) {
                    var _d = (0, tslib_1.__read)(renderers_by_source_1_1.value, 2), renderers = _d[1];
                    var sm = renderers[0].get_selection_manager();
                    var r_views = [];
                    try {
                        for (var renderers_1 = (e_4 = void 0, (0, tslib_1.__values)(renderers)), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                            var r = renderers_1_1.value;
                            var r_view = this.plot_view.renderer_view(r);
                            if (r_view != null) {
                                r_views.push(r_view);
                            }
                        }
                    }
                    catch (e_4_1) {
                        e_4 = { error: e_4_1 };
                    }
                    finally {
                        try {
                            if (renderers_1_1 && !renderers_1_1.done && (_c = renderers_1.return))
                                _c.call(renderers_1);
                        }
                        finally {
                            if (e_4)
                                throw e_4.error;
                        }
                    }
                    sm.select(r_views, geometry, final, mode);
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (renderers_by_source_1_1 && !renderers_by_source_1_1.done && (_b = renderers_by_source_1.return))
                        _b.call(renderers_by_source_1);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            // XXX: messed up class structure
            if (this.model.callback != null)
                this._emit_callback(geometry);
            this._emit_selection_event(geometry, final);
        };
        SelectToolView.prototype._emit_selection_event = function (geometry, final) {
            if (final === void 0) {
                final = true;
            }
            var _b = this.plot_view.frame, x_scale = _b.x_scale, y_scale = _b.y_scale;
            var geometry_data;
            switch (geometry.type) {
                case "point": {
                    var sx = geometry.sx, sy = geometry.sy;
                    var x = x_scale.invert(sx);
                    var y = y_scale.invert(sy);
                    geometry_data = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, geometry), { x: x, y: y });
                    break;
                }
                case "span": {
                    var sx = geometry.sx, sy = geometry.sy;
                    var x = x_scale.invert(sx);
                    var y = y_scale.invert(sy);
                    geometry_data = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, geometry), { x: x, y: y });
                    break;
                }
                case "rect": {
                    var sx0 = geometry.sx0, sx1 = geometry.sx1, sy0 = geometry.sy0, sy1 = geometry.sy1;
                    var _c = (0, tslib_1.__read)(x_scale.r_invert(sx0, sx1), 2), x0 = _c[0], x1 = _c[1];
                    var _d = (0, tslib_1.__read)(y_scale.r_invert(sy0, sy1), 2), y0 = _d[0], y1 = _d[1];
                    geometry_data = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, geometry), { x0: x0, y0: y0, x1: x1, y1: y1 });
                    break;
                }
                case "poly": {
                    var sx = geometry.sx, sy = geometry.sy;
                    var x = x_scale.v_invert(sx);
                    var y = y_scale.v_invert(sy);
                    geometry_data = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, geometry), { x: x, y: y });
                    break;
                }
            }
            this.plot_model.trigger_event(new bokeh_events_1.SelectionGeometry(geometry_data, final));
        };
        return SelectToolView;
    }(gesture_tool_1.GestureToolView));
    exports.SelectToolView = SelectToolView;
    SelectToolView.__name__ = "SelectToolView";
    var SelectTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SelectTool, _super);
        function SelectTool(attrs) {
            return _super.call(this, attrs) || this;
        }
        SelectTool.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.clear = new signaling_1.Signal0(this, "clear");
        };
        Object.defineProperty(SelectTool.prototype, "menu", {
            get: function () {
                var _this = this;
                return [
                    {
                        icon: "bk-tool-icon-replace-mode",
                        tooltip: "Replace the current selection",
                        active: function () { return _this.mode == "replace"; },
                        handler: function () {
                            _this.mode = "replace";
                            _this.active = true;
                        },
                    }, {
                        icon: "bk-tool-icon-append-mode",
                        tooltip: "Append to the current selection (Shift)",
                        active: function () { return _this.mode == "append"; },
                        handler: function () {
                            _this.mode = "append";
                            _this.active = true;
                        },
                    }, {
                        icon: "bk-tool-icon-intersect-mode",
                        tooltip: "Intersect with the current selection (Ctrl)",
                        active: function () { return _this.mode == "intersect"; },
                        handler: function () {
                            _this.mode = "intersect";
                            _this.active = true;
                        },
                    }, {
                        icon: "bk-tool-icon-subtract-mode",
                        tooltip: "Subtract from the current selection (Shift+Ctrl)",
                        active: function () { return _this.mode == "subtract"; },
                        handler: function () {
                            _this.mode = "subtract";
                            _this.active = true;
                        },
                    },
                    null,
                    {
                        icon: "bk-tool-icon-clear-selection",
                        tooltip: "Clear the current selection (Esc)",
                        handler: function () {
                            _this.clear.emit();
                        },
                    },
                ];
            },
            enumerable: false,
            configurable: true
        });
        return SelectTool;
    }(gesture_tool_1.GestureTool));
    exports.SelectTool = SelectTool;
    _a = SelectTool;
    SelectTool.__name__ = "SelectTool";
    (function () {
        _a.define(function (_b) {
            var String = _b.String, Array = _b.Array, Ref = _b.Ref, Or = _b.Or, Auto = _b.Auto;
            return ({
                renderers: [Or(Array(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
                names: [Array(String), []],
                mode: [enums_1.SelectionMode, "replace"],
            });
        });
    })();
},
/* models/tools/gestures/box_zoom_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var gesture_tool_1 = require(338) /* ./gesture_tool */;
    var box_annotation_1 = require(231) /* ../../annotations/box_annotation */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var BoxZoomToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxZoomToolView, _super);
        function BoxZoomToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        BoxZoomToolView.prototype._match_aspect = function (base_point, curpoint, frame) {
            // aspect ratio of plot frame
            var a = frame.bbox.aspect;
            var hend = frame.bbox.h_range.end;
            var hstart = frame.bbox.h_range.start;
            var vend = frame.bbox.v_range.end;
            var vstart = frame.bbox.v_range.start;
            // current aspect of cursor-defined box
            var vw = Math.abs(base_point[0] - curpoint[0]);
            var vh = Math.abs(base_point[1] - curpoint[1]);
            var va = vh == 0 ? 0 : vw / vh;
            var _b = (0, tslib_1.__read)(va >= a ? [1, va / a] : [a / va, 1], 1), xmod = _b[0];
            // OK the code blocks below merit some explanation. They do:
            //
            // compute left/right, pin to frame if necessary
            // compute top/bottom (based on new left/right), pin to frame if necessary
            // recompute left/right (based on top/bottom), in case top/bottom were pinned
            // base_point[0] is left
            var left;
            var right;
            if (base_point[0] <= curpoint[0]) {
                left = base_point[0];
                right = base_point[0] + vw * xmod;
                if (right > hend)
                    right = hend;
                // base_point[0] is right
            }
            else {
                right = base_point[0];
                left = base_point[0] - vw * xmod;
                if (left < hstart)
                    left = hstart;
            }
            vw = Math.abs(right - left);
            // base_point[1] is bottom
            var top;
            var bottom;
            if (base_point[1] <= curpoint[1]) {
                bottom = base_point[1];
                top = base_point[1] + vw / a;
                if (top > vend)
                    top = vend;
                // base_point[1] is top
            }
            else {
                top = base_point[1];
                bottom = base_point[1] - vw / a;
                if (bottom < vstart)
                    bottom = vstart;
            }
            vh = Math.abs(top - bottom);
            // base_point[0] is left
            if (base_point[0] <= curpoint[0])
                right = base_point[0] + a * vh;
            // base_point[0] is right
            else
                left = base_point[0] - a * vh;
            return [[left, right], [bottom, top]];
        };
        BoxZoomToolView.prototype._compute_limits = function (curpoint) {
            var _b, _c;
            var frame = this.plot_view.frame;
            var dims = this.model.dimensions;
            var base_point = this._base_point;
            if (this.model.origin == "center") {
                var _d = (0, tslib_1.__read)(base_point, 2), cx = _d[0], cy = _d[1];
                var _e = (0, tslib_1.__read)(curpoint, 2), dx = _e[0], dy = _e[1];
                base_point = [cx - (dx - cx), cy - (dy - cy)];
            }
            var sx;
            var sy;
            if (this.model.match_aspect && dims == "both")
                _b = (0, tslib_1.__read)(this._match_aspect(base_point, curpoint, frame), 2), sx = _b[0], sy = _b[1];
            else
                _c = (0, tslib_1.__read)(this.model._get_dim_limits(base_point, curpoint, frame, dims), 2), sx = _c[0], sy = _c[1];
            return [sx, sy];
        };
        BoxZoomToolView.prototype._pan_start = function (ev) {
            this._base_point = [ev.sx, ev.sy];
        };
        BoxZoomToolView.prototype._pan = function (ev) {
            var curpoint = [ev.sx, ev.sy];
            var _b = (0, tslib_1.__read)(this._compute_limits(curpoint), 2), sx = _b[0], sy = _b[1];
            this.model.overlay.update({ left: sx[0], right: sx[1], top: sy[0], bottom: sy[1] });
        };
        BoxZoomToolView.prototype._pan_end = function (ev) {
            var curpoint = [ev.sx, ev.sy];
            var _b = (0, tslib_1.__read)(this._compute_limits(curpoint), 2), sx = _b[0], sy = _b[1];
            this._update(sx, sy);
            this.model.overlay.update({ left: null, right: null, top: null, bottom: null });
            this._base_point = null;
            this.plot_view.trigger_ranges_update_event();
        };
        BoxZoomToolView.prototype._update = function (_b, _c) {
            var e_1, _d, e_2, _e;
            var _f = (0, tslib_1.__read)(_b, 2), sx0 = _f[0], sx1 = _f[1];
            var _g = (0, tslib_1.__read)(_c, 2), sy0 = _g[0], sy1 = _g[1];
            // If the viewing window is too small, no-op: it is likely that the user did
            // not intend to make this box zoom and instead was trying to cancel out of the
            // zoom, a la matplotlib's ToolZoom. Like matplotlib, set the threshold at 5 pixels.
            if (Math.abs(sx1 - sx0) <= 5 || Math.abs(sy1 - sy0) <= 5)
                return;
            var _h = this.plot_view.frame, x_scales = _h.x_scales, y_scales = _h.y_scales;
            var xrs = new Map();
            try {
                for (var x_scales_1 = (0, tslib_1.__values)(x_scales), x_scales_1_1 = x_scales_1.next(); !x_scales_1_1.done; x_scales_1_1 = x_scales_1.next()) {
                    var _j = (0, tslib_1.__read)(x_scales_1_1.value, 2), name = _j[0], scale = _j[1];
                    var _k = (0, tslib_1.__read)(scale.r_invert(sx0, sx1), 2), start = _k[0], end = _k[1];
                    xrs.set(name, { start: start, end: end });
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (x_scales_1_1 && !x_scales_1_1.done && (_d = x_scales_1.return))
                        _d.call(x_scales_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            var yrs = new Map();
            try {
                for (var y_scales_1 = (0, tslib_1.__values)(y_scales), y_scales_1_1 = y_scales_1.next(); !y_scales_1_1.done; y_scales_1_1 = y_scales_1.next()) {
                    var _l = (0, tslib_1.__read)(y_scales_1_1.value, 2), name = _l[0], scale = _l[1];
                    var _m = (0, tslib_1.__read)(scale.r_invert(sy0, sy1), 2), start = _m[0], end = _m[1];
                    yrs.set(name, { start: start, end: end });
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (y_scales_1_1 && !y_scales_1_1.done && (_e = y_scales_1.return))
                        _e.call(y_scales_1);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            var zoom_info = { xrs: xrs, yrs: yrs };
            this.plot_view.state.push("box_zoom", { range: zoom_info });
            this.plot_view.update_range(zoom_info);
        };
        return BoxZoomToolView;
    }(gesture_tool_1.GestureToolView));
    exports.BoxZoomToolView = BoxZoomToolView;
    BoxZoomToolView.__name__ = "BoxZoomToolView";
    var DEFAULT_BOX_OVERLAY = function () {
        return new box_annotation_1.BoxAnnotation({
            level: "overlay",
            top_units: "screen",
            left_units: "screen",
            bottom_units: "screen",
            right_units: "screen",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    var BoxZoomTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(BoxZoomTool, _super);
        function BoxZoomTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Box Zoom";
            _this.icon = icons_css_1.tool_icon_box_zoom;
            _this.event_type = "pan";
            _this.default_order = 20;
            return _this;
        }
        Object.defineProperty(BoxZoomTool.prototype, "tooltip", {
            get: function () {
                return this._get_dim_tooltip(this.dimensions);
            },
            enumerable: false,
            configurable: true
        });
        return BoxZoomTool;
    }(gesture_tool_1.GestureTool));
    exports.BoxZoomTool = BoxZoomTool;
    _a = BoxZoomTool;
    BoxZoomTool.__name__ = "BoxZoomTool";
    (function () {
        _a.prototype.default_view = BoxZoomToolView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Ref = _b.Ref;
            return ({
                dimensions: [enums_1.Dimensions, "both"],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_BOX_OVERLAY],
                match_aspect: [Boolean, false],
                origin: [enums_1.BoxOrigin, "corner"],
            });
        });
        _a.register_alias("box_zoom", function () { return new BoxZoomTool({ dimensions: "both" }); });
        _a.register_alias("xbox_zoom", function () { return new BoxZoomTool({ dimensions: "width" }); });
        _a.register_alias("ybox_zoom", function () { return new BoxZoomTool({ dimensions: "height" }); });
    })();
},
/* models/tools/gestures/lasso_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var select_tool_1 = require(493) /* ./select_tool */;
    var poly_annotation_1 = require(332) /* ../../annotations/poly_annotation */;
    var poly_select_tool_1 = require(496) /* ./poly_select_tool */;
    var dom_1 = require(158) /* ../../../core/dom */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var LassoSelectToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LassoSelectToolView, _super);
        function LassoSelectToolView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.sxs = [];
            _this.sys = [];
            return _this;
        }
        LassoSelectToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.active.change, function () { return _this._active_change(); });
        };
        LassoSelectToolView.prototype._active_change = function () {
            if (!this.model.active)
                this._clear_overlay();
        };
        LassoSelectToolView.prototype._keyup = function (ev) {
            if (ev.keyCode == dom_1.Keys.Enter)
                this._clear_overlay();
        };
        LassoSelectToolView.prototype._pan_start = function (ev) {
            this.sxs = [];
            this.sys = [];
            var sx = ev.sx, sy = ev.sy;
            this._append_overlay(sx, sy);
        };
        LassoSelectToolView.prototype._pan = function (ev) {
            var _b = (0, tslib_1.__read)(this.plot_view.frame.bbox.clip(ev.sx, ev.sy), 2), sx = _b[0], sy = _b[1];
            this._append_overlay(sx, sy);
            if (this.model.select_every_mousemove) {
                this._do_select(this.sxs, this.sys, false, this._select_mode(ev));
            }
        };
        LassoSelectToolView.prototype._pan_end = function (ev) {
            var _b = this, sxs = _b.sxs, sys = _b.sys;
            this._clear_overlay();
            this._do_select(sxs, sys, true, this._select_mode(ev));
            this.plot_view.state.push("lasso_select", { selection: this.plot_view.get_selection() });
        };
        LassoSelectToolView.prototype._append_overlay = function (sx, sy) {
            var _b = this, sxs = _b.sxs, sys = _b.sys;
            sxs.push(sx);
            sys.push(sy);
            this.model.overlay.update({ xs: sxs, ys: sys });
        };
        LassoSelectToolView.prototype._clear_overlay = function () {
            this.sxs = [];
            this.sys = [];
            this.model.overlay.update({ xs: this.sxs, ys: this.sys });
        };
        LassoSelectToolView.prototype._do_select = function (sx, sy, final, mode) {
            var geometry = { type: "poly", sx: sx, sy: sy };
            this._select(geometry, final, mode);
        };
        return LassoSelectToolView;
    }(select_tool_1.SelectToolView));
    exports.LassoSelectToolView = LassoSelectToolView;
    LassoSelectToolView.__name__ = "LassoSelectToolView";
    var LassoSelectTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LassoSelectTool, _super);
        function LassoSelectTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Lasso Select";
            _this.icon = icons_css_1.tool_icon_lasso_select;
            _this.event_type = "pan";
            _this.default_order = 12;
            return _this;
        }
        return LassoSelectTool;
    }(select_tool_1.SelectTool));
    exports.LassoSelectTool = LassoSelectTool;
    _a = LassoSelectTool;
    LassoSelectTool.__name__ = "LassoSelectTool";
    (function () {
        _a.prototype.default_view = LassoSelectToolView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Ref = _b.Ref;
            return ({
                select_every_mousemove: [Boolean, true],
                overlay: [Ref(poly_annotation_1.PolyAnnotation), poly_select_tool_1.DEFAULT_POLY_OVERLAY],
            });
        });
        _a.register_alias("lasso_select", function () { return new LassoSelectTool(); });
    })();
},
/* models/tools/gestures/poly_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var select_tool_1 = require(493) /* ./select_tool */;
    var poly_annotation_1 = require(332) /* ../../annotations/poly_annotation */;
    var dom_1 = require(158) /* ../../../core/dom */;
    var array_1 = require(126) /* ../../../core/util/array */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var PolySelectToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolySelectToolView, _super);
        function PolySelectToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PolySelectToolView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.data = { sx: [], sy: [] };
        };
        PolySelectToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.model.properties.active.change, function () { return _this._active_change(); });
        };
        PolySelectToolView.prototype._active_change = function () {
            if (!this.model.active)
                this._clear_data();
        };
        PolySelectToolView.prototype._keyup = function (ev) {
            if (ev.keyCode == dom_1.Keys.Enter)
                this._clear_data();
        };
        PolySelectToolView.prototype._doubletap = function (ev) {
            this._do_select(this.data.sx, this.data.sy, true, this._select_mode(ev));
            this.plot_view.state.push("poly_select", { selection: this.plot_view.get_selection() });
            this._clear_data();
        };
        PolySelectToolView.prototype._clear_data = function () {
            this.data = { sx: [], sy: [] };
            this.model.overlay.update({ xs: [], ys: [] });
        };
        PolySelectToolView.prototype._tap = function (ev) {
            var sx = ev.sx, sy = ev.sy;
            var frame = this.plot_view.frame;
            if (!frame.bbox.contains(sx, sy))
                return;
            this.data.sx.push(sx);
            this.data.sy.push(sy);
            this.model.overlay.update({ xs: (0, array_1.copy)(this.data.sx), ys: (0, array_1.copy)(this.data.sy) });
        };
        PolySelectToolView.prototype._do_select = function (sx, sy, final, mode) {
            var geometry = { type: "poly", sx: sx, sy: sy };
            this._select(geometry, final, mode);
        };
        return PolySelectToolView;
    }(select_tool_1.SelectToolView));
    exports.PolySelectToolView = PolySelectToolView;
    PolySelectToolView.__name__ = "PolySelectToolView";
    var DEFAULT_POLY_OVERLAY = function () {
        return new poly_annotation_1.PolyAnnotation({
            level: "overlay",
            xs_units: "screen",
            ys_units: "screen",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    exports.DEFAULT_POLY_OVERLAY = DEFAULT_POLY_OVERLAY;
    var PolySelectTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PolySelectTool, _super);
        function PolySelectTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Poly Select";
            _this.icon = icons_css_1.tool_icon_polygon_select;
            _this.event_type = "tap";
            _this.default_order = 11;
            return _this;
        }
        return PolySelectTool;
    }(select_tool_1.SelectTool));
    exports.PolySelectTool = PolySelectTool;
    _a = PolySelectTool;
    PolySelectTool.__name__ = "PolySelectTool";
    (function () {
        _a.prototype.default_view = PolySelectToolView;
        _a.define(function (_b) {
            var Ref = _b.Ref;
            return ({
                overlay: [Ref(poly_annotation_1.PolyAnnotation), exports.DEFAULT_POLY_OVERLAY],
            });
        });
        _a.register_alias("poly_select", function () { return new PolySelectTool(); });
    })();
},
/* models/tools/edit/line_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var enums_1 = require(135) /* ../../../core/enums */;
    var line_tool_1 = require(498) /* ./line_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var LineEditToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineEditToolView, _super);
        function LineEditToolView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this._drawing = false;
            return _this;
        }
        LineEditToolView.prototype._doubletap = function (ev) {
            var e_1, _b;
            if (!this.model.active)
                return;
            var renderers = this.model.renderers;
            try {
                for (var renderers_1 = (0, tslib_1.__values)(renderers), renderers_1_1 = renderers_1.next(); !renderers_1_1.done; renderers_1_1 = renderers_1.next()) {
                    var renderer = renderers_1_1.value;
                    var line_selected = this._select_event(ev, "replace", [renderer]);
                    if (line_selected.length == 1) {
                        this._selected_renderer = renderer;
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (renderers_1_1 && !renderers_1_1.done && (_b = renderers_1.return))
                        _b.call(renderers_1);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            this._show_intersections();
            this._update_line_cds();
        };
        LineEditToolView.prototype._show_intersections = function () {
            if (!this.model.active)
                return;
            if (this._selected_renderer == null)
                return;
            var renderers = this.model.renderers;
            if (!renderers.length) {
                this._set_intersection([], []);
                this._selected_renderer = null;
                this._drawing = false;
                return;
            }
            var cds = this._selected_renderer.data_source;
            var glyph = this._selected_renderer.glyph;
            var _b = (0, tslib_1.__read)([glyph.x.field, glyph.y.field], 2), xkey = _b[0], ykey = _b[1];
            var x = cds.get_array(xkey);
            var y = cds.get_array(ykey);
            this._set_intersection(x, y);
        };
        LineEditToolView.prototype._tap = function (ev) {
            var renderer = this.model.intersection_renderer;
            var point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            else if (this._drawing && this._selected_renderer) {
                var mode_1 = this._select_mode(ev);
                var selected_points = this._select_event(ev, mode_1, [renderer]);
                if (selected_points.length == 0) {
                    return;
                }
            }
            var mode = this._select_mode(ev);
            this._select_event(ev, mode, [renderer]);
            this._select_event(ev, mode, this.model.renderers);
        };
        LineEditToolView.prototype._update_line_cds = function () {
            if (this._selected_renderer == null)
                return;
            var point_glyph = this.model.intersection_renderer.glyph;
            var point_cds = this.model.intersection_renderer.data_source;
            var _b = (0, tslib_1.__read)([point_glyph.x.field, point_glyph.y.field], 2), pxkey = _b[0], pykey = _b[1];
            if (pxkey && pykey) {
                var x = point_cds.data[pxkey];
                var y = point_cds.data[pykey];
                this._selected_renderer.data_source.data[pxkey] = x;
                this._selected_renderer.data_source.data[pykey] = y;
            }
            this._emit_cds_changes(this._selected_renderer.data_source, true, true, false);
        };
        LineEditToolView.prototype._pan_start = function (ev) {
            this._select_event(ev, "append", [this.model.intersection_renderer]);
            this._basepoint = [ev.sx, ev.sy];
        };
        LineEditToolView.prototype._pan = function (ev) {
            if (this._basepoint == null)
                return;
            this._drag_points(ev, [this.model.intersection_renderer], this.model.dimensions);
            if (this._selected_renderer)
                this._selected_renderer.data_source.change.emit();
        };
        LineEditToolView.prototype._pan_end = function (ev) {
            if (this._basepoint == null)
                return;
            this._drag_points(ev, [this.model.intersection_renderer]);
            this._emit_cds_changes(this.model.intersection_renderer.data_source, false, true, true);
            if (this._selected_renderer) {
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            this._basepoint = null;
        };
        LineEditToolView.prototype.activate = function () {
            this._drawing = true;
        };
        LineEditToolView.prototype.deactivate = function () {
            if (!this._selected_renderer) {
                return;
            }
            else if (this._drawing) {
                this._drawing = false;
            }
            this._hide_intersections();
        };
        return LineEditToolView;
    }(line_tool_1.LineToolView));
    exports.LineEditToolView = LineEditToolView;
    LineEditToolView.__name__ = "LineEditToolView";
    var LineEditTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineEditTool, _super);
        function LineEditTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Line Edit Tool";
            _this.icon = icons_css_1.tool_icon_line_edit;
            _this.event_type = ["tap", "pan", "move"];
            _this.default_order = 4;
            return _this;
        }
        Object.defineProperty(LineEditTool.prototype, "tooltip", {
            get: function () {
                return this._get_dim_tooltip(this.dimensions);
            },
            enumerable: false,
            configurable: true
        });
        return LineEditTool;
    }(line_tool_1.LineTool));
    exports.LineEditTool = LineEditTool;
    _a = LineEditTool;
    LineEditTool.__name__ = "LineEditTool";
    (function () {
        _a.prototype.default_view = LineEditToolView;
        _a.define(function () {
            return ({
                dimensions: [enums_1.Dimensions, "both"],
            });
        });
    })();
},
/* models/tools/edit/line_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var types_1 = require(125) /* ../../../core/util/types */;
    var edit_tool_1 = require(485) /* ./edit_tool */;
    var LineToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineToolView, _super);
        function LineToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LineToolView.prototype._set_intersection = function (x, y) {
            var point_glyph = this.model.intersection_renderer.glyph;
            var point_cds = this.model.intersection_renderer.data_source;
            var _b = (0, tslib_1.__read)([point_glyph.x.field, point_glyph.y.field], 2), pxkey = _b[0], pykey = _b[1];
            if (pxkey) {
                if ((0, types_1.isArray)(x))
                    point_cds.data[pxkey] = x;
                else
                    point_glyph.x = { value: x };
            }
            if (pykey) {
                if ((0, types_1.isArray)(y))
                    point_cds.data[pykey] = y;
                else
                    point_glyph.y = { value: y };
            }
            this._emit_cds_changes(point_cds, true, true, false);
        };
        LineToolView.prototype._hide_intersections = function () {
            this._set_intersection([], []);
        };
        return LineToolView;
    }(edit_tool_1.EditToolView));
    exports.LineToolView = LineToolView;
    LineToolView.__name__ = "LineToolView";
    var LineTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(LineTool, _super);
        function LineTool(attrs) {
            return _super.call(this, attrs) || this;
        }
        return LineTool;
    }(edit_tool_1.EditTool));
    exports.LineTool = LineTool;
    _a = LineTool;
    LineTool.__name__ = "LineTool";
    (function () {
        _a.define(function (_b) {
            var AnyRef = _b.AnyRef;
            return ({
                intersection_renderer: [AnyRef()],
            });
        });
    })();
},
/* models/tools/gestures/pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var gesture_tool_1 = require(338) /* ./gesture_tool */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var icons = (0, tslib_1.__importStar)(require(343) /* ../../../styles/icons.css */);
    function update_ranges(scales, p0, p1) {
        var e_1, _b;
        var r = new Map();
        try {
            for (var scales_1 = (0, tslib_1.__values)(scales), scales_1_1 = scales_1.next(); !scales_1_1.done; scales_1_1 = scales_1.next()) {
                var _c = (0, tslib_1.__read)(scales_1_1.value, 2), name = _c[0], scale = _c[1];
                var _d = (0, tslib_1.__read)(scale.r_invert(p0, p1), 2), start = _d[0], end = _d[1];
                r.set(name, { start: start, end: end });
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (scales_1_1 && !scales_1_1.done && (_b = scales_1.return))
                    _b.call(scales_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
        return r;
    }
    exports.update_ranges = update_ranges;
    var PanToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PanToolView, _super);
        function PanToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        PanToolView.prototype._pan_start = function (ev) {
            var _b;
            this.last_dx = 0;
            this.last_dy = 0;
            var sx = ev.sx, sy = ev.sy;
            var bbox = this.plot_view.frame.bbox;
            if (!bbox.contains(sx, sy)) {
                var hr = bbox.h_range;
                var vr = bbox.v_range;
                if (sx < hr.start || sx > hr.end)
                    this.v_axis_only = true;
                if (sy < vr.start || sy > vr.end)
                    this.h_axis_only = true;
            }
            (_b = this.model.document) === null || _b === void 0 ? void 0 : _b.interactive_start(this.plot_model);
        };
        PanToolView.prototype._pan = function (ev) {
            var _b;
            this._update(ev.deltaX, ev.deltaY);
            (_b = this.model.document) === null || _b === void 0 ? void 0 : _b.interactive_start(this.plot_model);
        };
        PanToolView.prototype._pan_end = function (_e) {
            this.h_axis_only = false;
            this.v_axis_only = false;
            if (this.pan_info != null)
                this.plot_view.state.push("pan", { range: this.pan_info });
            this.plot_view.trigger_ranges_update_event();
        };
        PanToolView.prototype._update = function (dx, dy) {
            var frame = this.plot_view.frame;
            var new_dx = dx - this.last_dx;
            var new_dy = dy - this.last_dy;
            var hr = frame.bbox.h_range;
            var sx_low = hr.start - new_dx;
            var sx_high = hr.end - new_dx;
            var vr = frame.bbox.v_range;
            var sy_low = vr.start - new_dy;
            var sy_high = vr.end - new_dy;
            var dims = this.model.dimensions;
            var sx0;
            var sx1;
            var sdx;
            if ((dims == "width" || dims == "both") && !this.v_axis_only) {
                sx0 = sx_low;
                sx1 = sx_high;
                sdx = -new_dx;
            }
            else {
                sx0 = hr.start;
                sx1 = hr.end;
                sdx = 0;
            }
            var sy0;
            var sy1;
            var sdy;
            if ((dims == "height" || dims == "both") && !this.h_axis_only) {
                sy0 = sy_low;
                sy1 = sy_high;
                sdy = -new_dy;
            }
            else {
                sy0 = vr.start;
                sy1 = vr.end;
                sdy = 0;
            }
            this.last_dx = dx;
            this.last_dy = dy;
            var x_scales = frame.x_scales, y_scales = frame.y_scales;
            var xrs = update_ranges(x_scales, sx0, sx1);
            var yrs = update_ranges(y_scales, sy0, sy1);
            this.pan_info = { xrs: xrs, yrs: yrs, sdx: sdx, sdy: sdy };
            this.plot_view.update_range(this.pan_info, { panning: true });
        };
        return PanToolView;
    }(gesture_tool_1.GestureToolView));
    exports.PanToolView = PanToolView;
    PanToolView.__name__ = "PanToolView";
    var PanTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PanTool, _super);
        function PanTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Pan";
            _this.event_type = "pan";
            _this.default_order = 10;
            return _this;
        }
        Object.defineProperty(PanTool.prototype, "tooltip", {
            get: function () {
                return this._get_dim_tooltip(this.dimensions);
            },
            enumerable: false,
            configurable: true
        });
        return PanTool;
    }(gesture_tool_1.GestureTool));
    exports.PanTool = PanTool;
    _a = PanTool;
    PanTool.__name__ = "PanTool";
    (function () {
        _a.prototype.default_view = PanToolView;
        _a.define(function () {
            return ({
                dimensions: [enums_1.Dimensions, "both", {
                        on_update: function (value, obj) {
                            switch (value) {
                                case "both":
                                    obj.icon = icons.tool_icon_pan;
                                    break;
                                case "width":
                                    obj.icon = icons.tool_icon_xpan;
                                    break;
                                case "height":
                                    obj.icon = icons.tool_icon_ypan;
                                    break;
                            }
                        },
                    }],
            });
        });
        _a.register_alias("pan", function () { return new PanTool({ dimensions: "both" }); });
        _a.register_alias("xpan", function () { return new PanTool({ dimensions: "width" }); });
        _a.register_alias("ypan", function () { return new PanTool({ dimensions: "height" }); });
    })();
},
/* models/tools/gestures/range_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var box_annotation_1 = require(231) /* ../../annotations/box_annotation */;
    var range1d_1 = require(173) /* ../../ranges/range1d */;
    var logging_1 = require(134) /* ../../../core/logging */;
    var gesture_tool_1 = require(338) /* ./gesture_tool */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    function flip_side(side) {
        switch (side) {
            case 1 /* Left */: return 2 /* Right */;
            case 2 /* Right */: return 1 /* Left */;
            case 4 /* Bottom */: return 5 /* Top */;
            case 5 /* Top */: return 4 /* Bottom */;
            default: return side;
        }
    }
    exports.flip_side = flip_side;
    // TODO (bev) This would be better directly with BoxAnnotation, but hard
    // to test on a view. Move when "View Models" are implemented
    function is_near(pos, value, scale, tolerance) {
        if (value == null)
            return false;
        var svalue = scale.compute(value);
        return Math.abs(pos - svalue) < tolerance;
    }
    exports.is_near = is_near;
    // TODO (bev) This would be better directly with BoxAnnotation, but hard
    // to test on a view. Move when "View Models" are implemented
    function is_inside(sx, sy, xscale, yscale, overlay) {
        var result = true;
        if (overlay.left != null && overlay.right != null) {
            var x = xscale.invert(sx);
            if (x < overlay.left || x > overlay.right)
                result = false;
        }
        if (overlay.bottom != null && overlay.top != null) {
            var y = yscale.invert(sy);
            if (y < overlay.bottom || y > overlay.top)
                result = false;
        }
        return result;
    }
    exports.is_inside = is_inside;
    function sides_inside(start, end, range) {
        var result = 0;
        if (start >= range.start && start <= range.end)
            result += 1;
        if (end >= range.start && end <= range.end)
            result += 1;
        return result;
    }
    exports.sides_inside = sides_inside;
    function compute_value(value, scale, sdelta, range) {
        var svalue = scale.compute(value);
        var new_value = scale.invert(svalue + sdelta);
        if (new_value >= range.start && new_value <= range.end)
            return new_value;
        return value;
    }
    exports.compute_value = compute_value;
    function update_range_end_side(end, range, side) {
        if (end > range.start) {
            range.end = end;
            return side;
        }
        else {
            range.end = range.start;
            range.start = end;
            return flip_side(side);
        }
    }
    exports.update_range_end_side = update_range_end_side;
    function update_range_start_side(start, range, side) {
        if (start < range.end) {
            range.start = start;
            return side;
        }
        else {
            range.start = range.end;
            range.end = start;
            return flip_side(side);
        }
    }
    exports.update_range_start_side = update_range_start_side;
    function update_range(range, scale, delta, plot_range) {
        var _b = (0, tslib_1.__read)(scale.r_compute(range.start, range.end), 2), sstart = _b[0], send = _b[1];
        var _c = (0, tslib_1.__read)(scale.r_invert(sstart + delta, send + delta), 2), start = _c[0], end = _c[1];
        var initial_sides_inside = sides_inside(range.start, range.end, plot_range);
        var final_sides_inside = sides_inside(start, end, plot_range);
        // Allow the update as long as the number of sides in-bounds does not decrease
        if (final_sides_inside >= initial_sides_inside) {
            range.start = start;
            range.end = end;
        }
    }
    exports.update_range = update_range;
    var RangeToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RangeToolView, _super);
        function RangeToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        RangeToolView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.side = 0 /* None */;
            this.model.update_overlay_from_ranges();
        };
        RangeToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            if (this.model.x_range != null)
                this.connect(this.model.x_range.change, function () { return _this.model.update_overlay_from_ranges(); });
            if (this.model.y_range != null)
                this.connect(this.model.y_range.change, function () { return _this.model.update_overlay_from_ranges(); });
        };
        RangeToolView.prototype._pan_start = function (ev) {
            this.last_dx = 0;
            this.last_dy = 0;
            var xr = this.model.x_range;
            var yr = this.model.y_range;
            var frame = this.plot_view.frame;
            var xscale = frame.x_scale;
            var yscale = frame.y_scale;
            var overlay = this.model.overlay;
            var left = overlay.left, right = overlay.right, top = overlay.top, bottom = overlay.bottom;
            var tolerance = this.model.overlay.line_width + box_annotation_1.EDGE_TOLERANCE;
            if (xr != null && this.model.x_interaction) {
                if (is_near(ev.sx, left, xscale, tolerance))
                    this.side = 1 /* Left */;
                else if (is_near(ev.sx, right, xscale, tolerance))
                    this.side = 2 /* Right */;
                else if (is_inside(ev.sx, ev.sy, xscale, yscale, overlay)) {
                    this.side = 3 /* LeftRight */;
                }
            }
            if (yr != null && this.model.y_interaction) {
                if (this.side == 0 /* None */ && is_near(ev.sy, bottom, yscale, tolerance))
                    this.side = 4 /* Bottom */;
                if (this.side == 0 /* None */ && is_near(ev.sy, top, yscale, tolerance))
                    this.side = 5 /* Top */;
                else if (is_inside(ev.sx, ev.sy, xscale, yscale, this.model.overlay)) {
                    if (this.side == 3 /* LeftRight */)
                        this.side = 7 /* LeftRightBottomTop */;
                    else
                        this.side = 6 /* BottomTop */;
                }
            }
        };
        RangeToolView.prototype._pan = function (ev) {
            var frame = this.plot_view.frame;
            var new_dx = ev.deltaX - this.last_dx;
            var new_dy = ev.deltaY - this.last_dy;
            var xr = this.model.x_range;
            var yr = this.model.y_range;
            var xscale = frame.x_scale;
            var yscale = frame.y_scale;
            if (xr != null) {
                if (this.side == 3 /* LeftRight */ || this.side == 7 /* LeftRightBottomTop */)
                    update_range(xr, xscale, new_dx, frame.x_range);
                else if (this.side == 1 /* Left */) {
                    var start = compute_value(xr.start, xscale, new_dx, frame.x_range);
                    this.side = update_range_start_side(start, xr, this.side);
                }
                else if (this.side == 2 /* Right */) {
                    var end = compute_value(xr.end, xscale, new_dx, frame.x_range);
                    this.side = update_range_end_side(end, xr, this.side);
                }
            }
            if (yr != null) {
                if (this.side == 6 /* BottomTop */ || this.side == 7 /* LeftRightBottomTop */)
                    update_range(yr, yscale, new_dy, frame.y_range);
                else if (this.side == 4 /* Bottom */) {
                    var start = compute_value(yr.start, yscale, new_dy, frame.y_range);
                    this.side = update_range_start_side(start, yr, this.side);
                }
                else if (this.side == 5 /* Top */) {
                    var end = compute_value(yr.end, yscale, new_dy, frame.y_range);
                    this.side = update_range_end_side(end, yr, this.side);
                }
            }
            this.last_dx = ev.deltaX;
            this.last_dy = ev.deltaY;
        };
        RangeToolView.prototype._pan_end = function (_ev) {
            this.side = 0 /* None */;
            this.plot_view.trigger_ranges_update_event();
        };
        return RangeToolView;
    }(gesture_tool_1.GestureToolView));
    exports.RangeToolView = RangeToolView;
    RangeToolView.__name__ = "RangeToolView";
    var DEFAULT_RANGE_OVERLAY = function () {
        return new box_annotation_1.BoxAnnotation({
            level: "overlay",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 0.5,
            line_dash: [2, 2],
        });
    };
    var RangeTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(RangeTool, _super);
        function RangeTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Range Tool";
            _this.icon = icons_css_1.tool_icon_range;
            _this.event_type = "pan";
            _this.default_order = 1;
            return _this;
        }
        RangeTool.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.overlay.in_cursor = "grab";
            this.overlay.ew_cursor = this.x_range != null && this.x_interaction ? "ew-resize" : null;
            this.overlay.ns_cursor = this.y_range != null && this.y_interaction ? "ns-resize" : null;
        };
        RangeTool.prototype.update_overlay_from_ranges = function () {
            if (this.x_range == null && this.y_range == null) {
                this.overlay.left = null;
                this.overlay.right = null;
                this.overlay.bottom = null;
                this.overlay.top = null;
                logging_1.logger.warn("RangeTool not configured with any Ranges.");
            }
            if (this.x_range == null) {
                this.overlay.left = null;
                this.overlay.right = null;
            }
            else {
                this.overlay.left = this.x_range.start;
                this.overlay.right = this.x_range.end;
            }
            if (this.y_range == null) {
                this.overlay.bottom = null;
                this.overlay.top = null;
            }
            else {
                this.overlay.bottom = this.y_range.start;
                this.overlay.top = this.y_range.end;
            }
        };
        return RangeTool;
    }(gesture_tool_1.GestureTool));
    exports.RangeTool = RangeTool;
    _a = RangeTool;
    RangeTool.__name__ = "RangeTool";
    (function () {
        _a.prototype.default_view = RangeToolView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Ref = _b.Ref, Nullable = _b.Nullable;
            return ({
                x_range: [Nullable(Ref(range1d_1.Range1d)), null],
                x_interaction: [Boolean, true],
                y_range: [Nullable(Ref(range1d_1.Range1d)), null],
                y_interaction: [Boolean, true],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_RANGE_OVERLAY],
            });
        });
    })();
},
/* models/tools/gestures/tap_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var select_tool_1 = require(493) /* ./select_tool */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var TapToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TapToolView, _super);
        function TapToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TapToolView.prototype._tap = function (ev) {
            if (this.model.gesture == "tap")
                this._handle_tap(ev);
        };
        TapToolView.prototype._doubletap = function (ev) {
            if (this.model.gesture == "doubletap")
                this._handle_tap(ev);
        };
        TapToolView.prototype._handle_tap = function (ev) {
            var sx = ev.sx, sy = ev.sy;
            var geometry = { type: "point", sx: sx, sy: sy };
            this._select(geometry, true, this._select_mode(ev));
        };
        TapToolView.prototype._select = function (geometry, final, mode) {
            var e_1, _b, e_2, _c;
            var _this = this;
            var callback = this.model.callback;
            if (this.model.behavior == "select") {
                var renderers_by_source = this._computed_renderers_by_data_source();
                try {
                    for (var renderers_by_source_1 = (0, tslib_1.__values)(renderers_by_source), renderers_by_source_1_1 = renderers_by_source_1.next(); !renderers_by_source_1_1.done; renderers_by_source_1_1 = renderers_by_source_1.next()) {
                        var _d = (0, tslib_1.__read)(renderers_by_source_1_1.value, 2), renderers = _d[1];
                        var sm = renderers[0].get_selection_manager();
                        var r_views = renderers
                            .map(function (r) { return _this.plot_view.renderer_view(r); })
                            .filter(function (rv) { return rv != null; });
                        var did_hit = sm.select(r_views, geometry, final, mode);
                        if (did_hit && callback != null) {
                            var x = r_views[0].coordinates.x_scale.invert(geometry.sx);
                            var y = r_views[0].coordinates.y_scale.invert(geometry.sy);
                            var data = { geometries: (0, tslib_1.__assign)((0, tslib_1.__assign)({}, geometry), { x: x, y: y }), source: sm.source };
                            callback.execute(this.model, data);
                        }
                    }
                }
                catch (e_1_1) {
                    e_1 = { error: e_1_1 };
                }
                finally {
                    try {
                        if (renderers_by_source_1_1 && !renderers_by_source_1_1.done && (_b = renderers_by_source_1.return))
                            _b.call(renderers_by_source_1);
                    }
                    finally {
                        if (e_1)
                            throw e_1.error;
                    }
                }
                this._emit_selection_event(geometry);
                this.plot_view.state.push("tap", { selection: this.plot_view.get_selection() });
            }
            else {
                try {
                    for (var _e = (0, tslib_1.__values)(this.computed_renderers), _f = _e.next(); !_f.done; _f = _e.next()) {
                        var r = _f.value;
                        var rv = this.plot_view.renderer_view(r);
                        if (rv == null)
                            continue;
                        var sm = r.get_selection_manager();
                        var did_hit = sm.inspect(rv, geometry);
                        if (did_hit && callback != null) {
                            var x = rv.coordinates.x_scale.invert(geometry.sx);
                            var y = rv.coordinates.y_scale.invert(geometry.sy);
                            var data = { geometries: (0, tslib_1.__assign)((0, tslib_1.__assign)({}, geometry), { x: x, y: y }), source: sm.source };
                            callback.execute(this.model, data);
                        }
                    }
                }
                catch (e_2_1) {
                    e_2 = { error: e_2_1 };
                }
                finally {
                    try {
                        if (_f && !_f.done && (_c = _e.return))
                            _c.call(_e);
                    }
                    finally {
                        if (e_2)
                            throw e_2.error;
                    }
                }
            }
        };
        return TapToolView;
    }(select_tool_1.SelectToolView));
    exports.TapToolView = TapToolView;
    TapToolView.__name__ = "TapToolView";
    var TapTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TapTool, _super);
        function TapTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Tap";
            _this.icon = icons_css_1.tool_icon_tap_select;
            _this.event_type = "tap";
            _this.default_order = 10;
            return _this;
        }
        return TapTool;
    }(select_tool_1.SelectTool));
    exports.TapTool = TapTool;
    _a = TapTool;
    TapTool.__name__ = "TapTool";
    (function () {
        _a.prototype.default_view = TapToolView;
        _a.define(function (_b) {
            var Any = _b.Any, Enum = _b.Enum, Nullable = _b.Nullable;
            return ({
                behavior: [enums_1.TapBehavior, "select"],
                gesture: [Enum("tap", "doubletap"), "tap"],
                callback: [Nullable(Any /*TODO*/)],
            });
        });
        _a.register_alias("click", function () { return new TapTool({ behavior: "inspect" }); });
        _a.register_alias("tap", function () { return new TapTool(); });
        _a.register_alias("doubletap", function () { return new TapTool({ gesture: "doubletap" }); });
    })();
},
/* models/tools/gestures/wheel_pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var gesture_tool_1 = require(338) /* ./gesture_tool */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var pan_tool_1 = require(499) /* ./pan_tool */;
    var WheelPanToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WheelPanToolView, _super);
        function WheelPanToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        WheelPanToolView.prototype._scroll = function (ev) {
            var factor = this.model.speed * ev.delta;
            // clamp the magnitude of factor, if it is > 1 bad things happen
            if (factor > 0.9)
                factor = 0.9;
            else if (factor < -0.9)
                factor = -0.9;
            this._update_ranges(factor);
        };
        WheelPanToolView.prototype._update_ranges = function (factor) {
            var _this = this;
            var _b;
            var frame = this.plot_view.frame;
            var hr = frame.bbox.h_range;
            var vr = frame.bbox.v_range;
            var _c = (0, tslib_1.__read)([hr.start, hr.end], 2), sx_low = _c[0], sx_high = _c[1];
            var _d = (0, tslib_1.__read)([vr.start, vr.end], 2), sy_low = _d[0], sy_high = _d[1];
            var sx0;
            var sx1;
            var sy0;
            var sy1;
            switch (this.model.dimension) {
                case "height": {
                    var sy_range = Math.abs(sy_high - sy_low);
                    sx0 = sx_low;
                    sx1 = sx_high;
                    sy0 = sy_low - sy_range * factor;
                    sy1 = sy_high - sy_range * factor;
                    break;
                }
                case "width": {
                    var sx_range = Math.abs(sx_high - sx_low);
                    sx0 = sx_low - sx_range * factor;
                    sx1 = sx_high - sx_range * factor;
                    sy0 = sy_low;
                    sy1 = sy_high;
                    break;
                }
            }
            var x_scales = frame.x_scales, y_scales = frame.y_scales;
            var xrs = (0, pan_tool_1.update_ranges)(x_scales, sx0, sx1);
            var yrs = (0, pan_tool_1.update_ranges)(y_scales, sy0, sy1);
            // OK this sucks we can't set factor independently in each direction. It is used
            // for GMap plots, and GMap plots always preserve aspect, so effective the value
            // of 'dimensions' is ignored.
            var pan_info = { xrs: xrs, yrs: yrs, factor: factor };
            this.plot_view.state.push("wheel_pan", { range: pan_info });
            this.plot_view.update_range(pan_info, { scrolling: true });
            (_b = this.model.document) === null || _b === void 0 ? void 0 : _b.interactive_start(this.plot_model, function () { return _this.plot_view.trigger_ranges_update_event(); });
        };
        return WheelPanToolView;
    }(gesture_tool_1.GestureToolView));
    exports.WheelPanToolView = WheelPanToolView;
    WheelPanToolView.__name__ = "WheelPanToolView";
    var WheelPanTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WheelPanTool, _super);
        function WheelPanTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Wheel Pan";
            _this.icon = icons_css_1.tool_icon_wheel_pan;
            _this.event_type = "scroll";
            _this.default_order = 12;
            return _this;
        }
        Object.defineProperty(WheelPanTool.prototype, "tooltip", {
            get: function () {
                return this._get_dim_tooltip(this.dimension);
            },
            enumerable: false,
            configurable: true
        });
        return WheelPanTool;
    }(gesture_tool_1.GestureTool));
    exports.WheelPanTool = WheelPanTool;
    _a = WheelPanTool;
    WheelPanTool.__name__ = "WheelPanTool";
    (function () {
        _a.prototype.default_view = WheelPanToolView;
        _a.define(function () {
            return ({
                dimension: [enums_1.Dimension, "width"],
            });
        });
        _a.internal(function (_b) {
            var Number = _b.Number;
            return ({
                speed: [Number, 1 / 1000],
            });
        });
        _a.register_alias("xwheel_pan", function () { return new WheelPanTool({ dimension: "width" }); });
        _a.register_alias("ywheel_pan", function () { return new WheelPanTool({ dimension: "height" }); });
    })();
},
/* models/tools/gestures/wheel_zoom_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var gesture_tool_1 = require(338) /* ./gesture_tool */;
    var zoom_1 = require(483) /* ../../../core/util/zoom */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var platform_1 = require(142) /* ../../../core/util/platform */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var WheelZoomToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WheelZoomToolView, _super);
        function WheelZoomToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        WheelZoomToolView.prototype._pinch = function (ev) {
            // TODO (bev) this can probably be done much better
            var sx = ev.sx, sy = ev.sy, scale = ev.scale, ctrlKey = ev.ctrlKey, shiftKey = ev.shiftKey;
            var delta;
            if (scale >= 1)
                delta = (scale - 1) * 20.0;
            else
                delta = -20.0 / scale;
            this._scroll({ type: "wheel", sx: sx, sy: sy, delta: delta, ctrlKey: ctrlKey, shiftKey: shiftKey });
        };
        WheelZoomToolView.prototype._scroll = function (ev) {
            var _this = this;
            var _b;
            var frame = this.plot_view.frame;
            var hr = frame.bbox.h_range;
            var vr = frame.bbox.v_range;
            var sx = ev.sx, sy = ev.sy;
            var dims = this.model.dimensions;
            // restrict to axis configured in tool's dimensions property and if
            // zoom origin is inside of frame range/domain
            var h_axis = (dims == "width" || dims == "both") && hr.start < sx && sx < hr.end;
            var v_axis = (dims == "height" || dims == "both") && vr.start < sy && sy < vr.end;
            if ((!h_axis || !v_axis) && !this.model.zoom_on_axis) {
                return;
            }
            var factor = this.model.speed * ev.delta;
            var zoom_info = (0, zoom_1.scale_range)(frame, factor, h_axis, v_axis, { x: sx, y: sy });
            this.plot_view.state.push("wheel_zoom", { range: zoom_info });
            var maintain_focus = this.model.maintain_focus;
            this.plot_view.update_range(zoom_info, { scrolling: true, maintain_focus: maintain_focus });
            (_b = this.model.document) === null || _b === void 0 ? void 0 : _b.interactive_start(this.plot_model, function () { return _this.plot_view.trigger_ranges_update_event(); });
        };
        return WheelZoomToolView;
    }(gesture_tool_1.GestureToolView));
    exports.WheelZoomToolView = WheelZoomToolView;
    WheelZoomToolView.__name__ = "WheelZoomToolView";
    var WheelZoomTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(WheelZoomTool, _super);
        function WheelZoomTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Wheel Zoom";
            _this.icon = icons_css_1.tool_icon_wheel_zoom;
            _this.event_type = platform_1.is_mobile ? "pinch" : "scroll";
            _this.default_order = 10;
            return _this;
        }
        Object.defineProperty(WheelZoomTool.prototype, "tooltip", {
            get: function () {
                return this._get_dim_tooltip(this.dimensions);
            },
            enumerable: false,
            configurable: true
        });
        return WheelZoomTool;
    }(gesture_tool_1.GestureTool));
    exports.WheelZoomTool = WheelZoomTool;
    _a = WheelZoomTool;
    WheelZoomTool.__name__ = "WheelZoomTool";
    (function () {
        _a.prototype.default_view = WheelZoomToolView;
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Number = _b.Number;
            return ({
                dimensions: [enums_1.Dimensions, "both"],
                maintain_focus: [Boolean, true],
                zoom_on_axis: [Boolean, true],
                speed: [Number, 1 / 600],
            });
        });
        _a.register_alias("wheel_zoom", function () { return new WheelZoomTool({ dimensions: "both" }); });
        _a.register_alias("xwheel_zoom", function () { return new WheelZoomTool({ dimensions: "width" }); });
        _a.register_alias("ywheel_zoom", function () { return new WheelZoomTool({ dimensions: "height" }); });
    })();
},
/* models/tools/inspectors/crosshair_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var inspect_tool_1 = require(347) /* ./inspect_tool */;
    var span_1 = require(334) /* ../../annotations/span */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var object_1 = require(128) /* ../../../core/util/object */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var CrosshairToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CrosshairToolView, _super);
        function CrosshairToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        CrosshairToolView.prototype._move = function (ev) {
            if (!this.model.active)
                return;
            var sx = ev.sx, sy = ev.sy;
            if (!this.plot_view.frame.bbox.contains(sx, sy))
                this._update_spans(null, null);
            else
                this._update_spans(sx, sy);
        };
        CrosshairToolView.prototype._move_exit = function (_e) {
            this._update_spans(null, null);
        };
        CrosshairToolView.prototype._update_spans = function (x, y) {
            var dims = this.model.dimensions;
            if (dims == "width" || dims == "both")
                this.model.spans.width.location = y;
            if (dims == "height" || dims == "both")
                this.model.spans.height.location = x;
        };
        return CrosshairToolView;
    }(inspect_tool_1.InspectToolView));
    exports.CrosshairToolView = CrosshairToolView;
    CrosshairToolView.__name__ = "CrosshairToolView";
    var CrosshairTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CrosshairTool, _super);
        function CrosshairTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Crosshair";
            _this.icon = icons_css_1.tool_icon_crosshair;
            return _this;
        }
        Object.defineProperty(CrosshairTool.prototype, "tooltip", {
            get: function () {
                return this._get_dim_tooltip(this.dimensions);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(CrosshairTool.prototype, "synthetic_renderers", {
            get: function () {
                return (0, object_1.values)(this.spans);
            },
            enumerable: false,
            configurable: true
        });
        return CrosshairTool;
    }(inspect_tool_1.InspectTool));
    exports.CrosshairTool = CrosshairTool;
    _a = CrosshairTool;
    CrosshairTool.__name__ = "CrosshairTool";
    (function () {
        _a.prototype.default_view = CrosshairToolView;
        _a.define(function (_b) {
            var Alpha = _b.Alpha, Number = _b.Number, Color = _b.Color;
            return ({
                dimensions: [enums_1.Dimensions, "both"],
                line_color: [Color, "black"],
                line_width: [Number, 1],
                line_alpha: [Alpha, 1],
            });
        });
        function span(self, dimension) {
            return new span_1.Span({
                for_hover: true,
                dimension: dimension,
                location_units: "screen",
                level: "overlay",
                line_color: self.line_color,
                line_width: self.line_width,
                line_alpha: self.line_alpha,
            });
        }
        _a.internal(function (_b) {
            var Struct = _b.Struct, Ref = _b.Ref;
            return ({
                spans: [
                    Struct({ width: Ref(span_1.Span), height: Ref(span_1.Span) }),
                    function (self) {
                        return ({
                            width: span(self, "width"),
                            height: span(self, "height"),
                        });
                    },
                ],
            });
        });
        _a.register_alias("crosshair", function () { return new CrosshairTool(); });
    })();
},
/* models/tools/inspectors/customjs_hover.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../../model */;
    var object_1 = require(128) /* ../../../core/util/object */;
    var string_1 = require(149) /* ../../../core/util/string */;
    var CustomJSHover = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(CustomJSHover, _super);
        function CustomJSHover(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(CustomJSHover.prototype, "values", {
            get: function () {
                return (0, object_1.values)(this.args);
            },
            enumerable: false,
            configurable: true
        });
        /*protected*/ CustomJSHover.prototype._make_code = function (valname, formatname, varsname, fn) {
            // this relies on keys(args) and values(args) returning keys and values
            // in the same order
            return new (Function.bind.apply(Function, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([void 0], (0, tslib_1.__read)((0, object_1.keys)(this.args)), false), [valname, formatname, varsname, (0, string_1.use_strict)(fn)], false)))();
        };
        CustomJSHover.prototype.format = function (value, format, special_vars) {
            var formatter = this._make_code("value", "format", "special_vars", this.code);
            return formatter.apply(void 0, (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(this.values), false), [value, format, special_vars], false));
        };
        return CustomJSHover;
    }(model_1.Model));
    exports.CustomJSHover = CustomJSHover;
    _a = CustomJSHover;
    CustomJSHover.__name__ = "CustomJSHover";
    (function () {
        _a.define(function (_b) {
            var Unknown = _b.Unknown, String = _b.String, Dict = _b.Dict;
            return ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            });
        });
    })();
},
/* models/tools/inspectors/hover_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var inspect_tool_1 = require(347) /* ./inspect_tool */;
    var customjs_hover_1 = require(505) /* ./customjs_hover */;
    var tooltip_1 = require(356) /* ../../annotations/tooltip */;
    var glyph_renderer_1 = require(290) /* ../../renderers/glyph_renderer */;
    var graph_renderer_1 = require(454) /* ../../renderers/graph_renderer */;
    var data_renderer_1 = require(291) /* ../../renderers/data_renderer */;
    var line_1 = require(292) /* ../../glyphs/line */;
    var multi_line_1 = require(398) /* ../../glyphs/multi_line */;
    var hittest = (0, tslib_1.__importStar)(require(300) /* ../../../core/hittest */);
    var templating_1 = require(267) /* ../../../core/util/templating */;
    var dom_1 = require(158) /* ../../../core/dom */;
    var color_1 = require(137) /* ../../../core/util/color */;
    var object_1 = require(128) /* ../../../core/util/object */;
    var iterator_1 = require(349) /* ../../../core/util/iterator */;
    var types_1 = require(125) /* ../../../core/util/types */;
    var build_views_1 = require(228) /* ../../../core/build_views */;
    var enums_1 = require(135) /* ../../../core/enums */;
    var icons_css_1 = require(343) /* ../../../styles/icons.css */;
    var signaling_1 = require(130) /* ../../../core/signaling */;
    var util_1 = require(181) /* ../../util */;
    var styles = (0, tslib_1.__importStar)(require(357) /* ../../../styles/tooltips.css */);
    var dom_2 = require(507) /* ../../dom */;
    function _nearest_line_hit(i, geometry, sx, sy, dx, dy) {
        var d1 = { x: dx[i], y: dy[i] };
        var d2 = { x: dx[i + 1], y: dy[i + 1] };
        var dist1;
        var dist2;
        if (geometry.type == "span") {
            if (geometry.direction == "h") {
                dist1 = Math.abs(d1.x - sx);
                dist2 = Math.abs(d2.x - sx);
            }
            else {
                dist1 = Math.abs(d1.y - sy);
                dist2 = Math.abs(d2.y - sy);
            }
        }
        else {
            var s = { x: sx, y: sy };
            dist1 = hittest.dist_2_pts(d1, s);
            dist2 = hittest.dist_2_pts(d2, s);
        }
        if (dist1 < dist2)
            return [[d1.x, d1.y], i];
        else
            return [[d2.x, d2.y], i + 1];
    }
    exports._nearest_line_hit = _nearest_line_hit;
    function _line_hit(xs, ys, ind) {
        return [[xs[ind], ys[ind]], ind];
    }
    exports._line_hit = _line_hit;
    var HoverToolView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HoverToolView, _super);
        function HoverToolView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        HoverToolView.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._ttmodels = new Map();
            this._ttviews = new Map();
        };
        HoverToolView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var tooltips, _b;
                return (0, tslib_1.__generator)(this, function (_c) {
                    switch (_c.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _c.sent();
                            return [4 /*yield*/, this._update_ttmodels()];
                        case 2:
                            _c.sent();
                            tooltips = this.model.tooltips;
                            if (!(tooltips instanceof dom_2.Template))
                                return [3 /*break*/, 4];
                            _b = this;
                            return [4 /*yield*/, (0, build_views_1.build_view)(tooltips, { parent: this })];
                        case 3:
                            _b._template_view = _c.sent();
                            this._template_view.render();
                            _c.label = 4;
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        HoverToolView.prototype.remove = function () {
            var _b;
            (_b = this._template_view) === null || _b === void 0 ? void 0 : _b.remove();
            (0, build_views_1.remove_views)(this._ttviews);
            _super.prototype.remove.call(this);
        };
        HoverToolView.prototype.connect_signals = function () {
            var _this = this;
            _super.prototype.connect_signals.call(this);
            var plot_renderers = this.plot_model.properties.renderers;
            var _b = this.model.properties, renderers = _b.renderers, tooltips = _b.tooltips;
            this.on_change(tooltips, function () { return delete _this._template_el; });
            this.on_change([plot_renderers, renderers, tooltips], function () {
                return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                    return (0, tslib_1.__generator)(this, function (_b) {
                        switch (_b.label) {
                            case 0: return [4 /*yield*/, this._update_ttmodels()];
                            case 1: return [2 /*return*/, _b.sent()];
                        }
                    });
                });
            });
        };
        HoverToolView.prototype._update_ttmodels = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var _b, _ttmodels, computed_renderers, tooltips, _c, _d, r, tooltip, views, views_1, views_1_1, ttview, glyph_renderers, slot, except, glyph_renderers_1, glyph_renderers_1_1, r;
                var e_1, _e, e_2, _f, e_3, _g;
                return (0, tslib_1.__generator)(this, function (_h) {
                    switch (_h.label) {
                        case 0:
                            _b = this, _ttmodels = _b._ttmodels, computed_renderers = _b.computed_renderers;
                            _ttmodels.clear();
                            tooltips = this.model.tooltips;
                            if (tooltips != null) {
                                try {
                                    for (_c = (0, tslib_1.__values)(this.computed_renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                                        r = _d.value;
                                        tooltip = new tooltip_1.Tooltip({
                                            custom: (0, types_1.isString)(tooltips) || (0, types_1.isFunction)(tooltips),
                                            attachment: this.model.attachment,
                                            show_arrow: this.model.show_arrow,
                                        });
                                        if (r instanceof glyph_renderer_1.GlyphRenderer) {
                                            _ttmodels.set(r, tooltip);
                                        }
                                        else if (r instanceof graph_renderer_1.GraphRenderer) {
                                            _ttmodels.set(r.node_renderer, tooltip);
                                            _ttmodels.set(r.edge_renderer, tooltip);
                                        }
                                    }
                                }
                                catch (e_1_1) {
                                    e_1 = { error: e_1_1 };
                                }
                                finally {
                                    try {
                                        if (_d && !_d.done && (_e = _c.return))
                                            _e.call(_c);
                                    }
                                    finally {
                                        if (e_1)
                                            throw e_1.error;
                                    }
                                }
                            }
                            return [4 /*yield*/, (0, build_views_1.build_views)(this._ttviews, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(_ttmodels.values()), false), { parent: this.plot_view })];
                        case 1:
                            views = _h.sent();
                            try {
                                for (views_1 = (0, tslib_1.__values)(views), views_1_1 = views_1.next(); !views_1_1.done; views_1_1 = views_1.next()) {
                                    ttview = views_1_1.value;
                                    ttview.render();
                                }
                            }
                            catch (e_2_1) {
                                e_2 = { error: e_2_1 };
                            }
                            finally {
                                try {
                                    if (views_1_1 && !views_1_1.done && (_f = views_1.return))
                                        _f.call(views_1);
                                }
                                finally {
                                    if (e_2)
                                        throw e_2.error;
                                }
                            }
                            glyph_renderers = (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)((function () {
                                var computed_renderers_1, computed_renderers_1_1, r, e_4_1;
                                var e_4, _b;
                                return (0, tslib_1.__generator)(this, function (_c) {
                                    switch (_c.label) {
                                        case 0:
                                            _c.trys.push([0, 8, 9, 10]);
                                            computed_renderers_1 = (0, tslib_1.__values)(computed_renderers), computed_renderers_1_1 = computed_renderers_1.next();
                                            _c.label = 1;
                                        case 1:
                                            if (!!computed_renderers_1_1.done)
                                                return [3 /*break*/, 7];
                                            r = computed_renderers_1_1.value;
                                            if (!(r instanceof glyph_renderer_1.GlyphRenderer))
                                                return [3 /*break*/, 3];
                                            return [4 /*yield*/, r];
                                        case 2:
                                            _c.sent();
                                            return [3 /*break*/, 6];
                                        case 3:
                                            if (!(r instanceof graph_renderer_1.GraphRenderer))
                                                return [3 /*break*/, 6];
                                            return [4 /*yield*/, r.node_renderer];
                                        case 4:
                                            _c.sent();
                                            return [4 /*yield*/, r.edge_renderer];
                                        case 5:
                                            _c.sent();
                                            _c.label = 6;
                                        case 6:
                                            computed_renderers_1_1 = computed_renderers_1.next();
                                            return [3 /*break*/, 1];
                                        case 7: return [3 /*break*/, 10];
                                        case 8:
                                            e_4_1 = _c.sent();
                                            e_4 = { error: e_4_1 };
                                            return [3 /*break*/, 10];
                                        case 9:
                                            try {
                                                if (computed_renderers_1_1 && !computed_renderers_1_1.done && (_b = computed_renderers_1.return))
                                                    _b.call(computed_renderers_1);
                                            }
                                            finally {
                                                if (e_4)
                                                    throw e_4.error;
                                            }
                                            return [7 /*endfinally*/];
                                        case 10: return [2 /*return*/];
                                    }
                                });
                            })()), false);
                            slot = this._slots.get(this._update);
                            if (slot != null) {
                                except = new Set(glyph_renderers.map(function (r) { return r.data_source; }));
                                signaling_1.Signal.disconnect_receiver(this, slot, except);
                            }
                            try {
                                for (glyph_renderers_1 = (0, tslib_1.__values)(glyph_renderers), glyph_renderers_1_1 = glyph_renderers_1.next(); !glyph_renderers_1_1.done; glyph_renderers_1_1 = glyph_renderers_1.next()) {
                                    r = glyph_renderers_1_1.value;
                                    this.connect(r.data_source.inspect, this._update);
                                }
                            }
                            catch (e_3_1) {
                                e_3 = { error: e_3_1 };
                            }
                            finally {
                                try {
                                    if (glyph_renderers_1_1 && !glyph_renderers_1_1.done && (_g = glyph_renderers_1.return))
                                        _g.call(glyph_renderers_1);
                                }
                                finally {
                                    if (e_3)
                                        throw e_3.error;
                                }
                            }
                            return [2 /*return*/];
                    }
                });
            });
        };
        Object.defineProperty(HoverToolView.prototype, "computed_renderers", {
            get: function () {
                var _b = this.model, renderers = _b.renderers, names = _b.names;
                var all_renderers = this.plot_model.data_renderers;
                return (0, util_1.compute_renderers)(renderers, all_renderers, names);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(HoverToolView.prototype, "ttmodels", {
            get: function () {
                return this._ttmodels;
            },
            enumerable: false,
            configurable: true
        });
        HoverToolView.prototype._clear = function () {
            var e_5, _b;
            this._inspect(Infinity, Infinity);
            try {
                for (var _c = (0, tslib_1.__values)(this.ttmodels), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var _e = (0, tslib_1.__read)(_d.value, 2), tooltip = _e[1];
                    tooltip.clear();
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
        };
        HoverToolView.prototype._move = function (ev) {
            if (!this.model.active)
                return;
            var sx = ev.sx, sy = ev.sy;
            if (!this.plot_view.frame.bbox.contains(sx, sy))
                this._clear();
            else
                this._inspect(sx, sy);
        };
        HoverToolView.prototype._move_exit = function () {
            this._clear();
        };
        HoverToolView.prototype._inspect = function (sx, sy) {
            var e_6, _b;
            var geometry;
            if (this.model.mode == "mouse")
                geometry = { type: "point", sx: sx, sy: sy };
            else {
                var direction = this.model.mode == "vline" ? "h" : "v";
                geometry = { type: "span", direction: direction, sx: sx, sy: sy };
            }
            try {
                for (var _c = (0, tslib_1.__values)(this.computed_renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var r = _d.value;
                    var sm = r.get_selection_manager();
                    var rview = this.plot_view.renderer_view(r);
                    if (rview != null)
                        sm.inspect(rview, geometry);
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            this._emit_callback(geometry);
        };
        HoverToolView.prototype._update = function (_b) {
            var e_7, _c, _d, _e, _f, _g, _h, _j, _k, _l, e_8, _m, e_9, _o, e_10, _p, _q, _r, _s, _t, _u, _v, _w, _z, e_11, _0;
            var _1, _2;
            var _3 = (0, tslib_1.__read)(_b, 2), renderer = _3[0], geometry = _3[1].geometry;
            if (!this.model.active)
                return;
            if (!(geometry.type == "point" || geometry.type == "span"))
                return;
            if (!(renderer instanceof glyph_renderer_1.GlyphRenderer)) // || renderer instanceof GraphRenderer))
                return;
            if (this.model.muted_policy == "ignore" && renderer.muted)
                return;
            var tooltip = this.ttmodels.get(renderer);
            if (tooltip == null)
                return;
            var selection_manager = renderer.get_selection_manager();
            var fullset_indices = selection_manager.inspectors.get(renderer);
            var subset_indices = renderer.view.convert_selection_to_subset(fullset_indices);
            if (fullset_indices.is_empty()) {
                tooltip.clear();
                return;
            }
            var ds = selection_manager.source;
            var renderer_view = this.plot_view.renderer_view(renderer);
            if (renderer_view == null)
                return;
            var sx = geometry.sx, sy = geometry.sy;
            var xscale = renderer_view.coordinates.x_scale;
            var yscale = renderer_view.coordinates.y_scale;
            var x = xscale.invert(sx);
            var y = yscale.invert(sy);
            var glyph = renderer_view.glyph;
            var tooltips = [];
            if (glyph instanceof line_1.LineView) {
                try {
                    for (var _4 = (0, tslib_1.__values)(subset_indices.line_indices), _5 = _4.next(); !_5.done; _5 = _4.next()) {
                        var i = _5.value;
                        var data_x = glyph._x[i + 1];
                        var data_y = glyph._y[i + 1];
                        var ii = i;
                        var rx = void 0;
                        var ry = void 0;
                        switch (this.model.line_policy) {
                            case "interp": { // and renderer.get_interpolation_hit?
                                _d = (0, tslib_1.__read)(glyph.get_interpolation_hit(i, geometry), 2), data_x = _d[0], data_y = _d[1];
                                rx = xscale.compute(data_x);
                                ry = yscale.compute(data_y);
                                break;
                            }
                            case "prev": {
                                _e = (0, tslib_1.__read)(_line_hit(glyph.sx, glyph.sy, i), 2), _f = (0, tslib_1.__read)(_e[0], 2), rx = _f[0], ry = _f[1], ii = _e[1];
                                break;
                            }
                            case "next": {
                                _g = (0, tslib_1.__read)(_line_hit(glyph.sx, glyph.sy, i + 1), 2), _h = (0, tslib_1.__read)(_g[0], 2), rx = _h[0], ry = _h[1], ii = _g[1];
                                break;
                            }
                            case "nearest": {
                                _j = (0, tslib_1.__read)(_nearest_line_hit(i, geometry, sx, sy, glyph.sx, glyph.sy), 2), _k = (0, tslib_1.__read)(_j[0], 2), rx = _k[0], ry = _k[1], ii = _j[1];
                                data_x = glyph._x[ii];
                                data_y = glyph._y[ii];
                                break;
                            }
                            default: {
                                _l = (0, tslib_1.__read)([sx, sy], 2), rx = _l[0], ry = _l[1];
                            }
                        }
                        var vars = {
                            index: ii,
                            x: x,
                            y: y,
                            sx: sx,
                            sy: sy,
                            data_x: data_x,
                            data_y: data_y,
                            rx: rx,
                            ry: ry,
                            indices: subset_indices.line_indices,
                            name: renderer.name,
                        };
                        tooltips.push([rx, ry, this._render_tooltips(ds, ii, vars)]);
                    }
                }
                catch (e_7_1) {
                    e_7 = { error: e_7_1 };
                }
                finally {
                    try {
                        if (_5 && !_5.done && (_c = _4.return))
                            _c.call(_4);
                    }
                    finally {
                        if (e_7)
                            throw e_7.error;
                    }
                }
            }
            try {
                for (var _6 = (0, tslib_1.__values)(fullset_indices.image_indices), _7 = _6.next(); !_7.done; _7 = _6.next()) {
                    var struct = _7.value;
                    var vars = {
                        index: struct.index,
                        x: x,
                        y: y,
                        sx: sx,
                        sy: sy,
                        name: renderer.name,
                    };
                    var rendered = this._render_tooltips(ds, struct, vars);
                    tooltips.push([sx, sy, rendered]);
                }
            }
            catch (e_8_1) {
                e_8 = { error: e_8_1 };
            }
            finally {
                try {
                    if (_7 && !_7.done && (_m = _6.return))
                        _m.call(_6);
                }
                finally {
                    if (e_8)
                        throw e_8.error;
                }
            }
            try {
                for (var _8 = (0, tslib_1.__values)(subset_indices.indices), _9 = _8.next(); !_9.done; _9 = _8.next()) {
                    var i = _9.value;
                    // multiglyphs set additional indices, e.g. multiline_indices for different tooltips
                    if (glyph instanceof multi_line_1.MultiLineView && !(0, object_1.isEmpty)(subset_indices.multiline_indices)) {
                        try {
                            for (var _10 = (e_10 = void 0, (0, tslib_1.__values)(subset_indices.multiline_indices[i.toString()])), _11 = _10.next(); !_11.done; _11 = _10.next()) { // TODO: subset_indices.multiline_indices.get(i)
                                var j = _11.value;
                                var data_x = glyph._xs.get(i)[j];
                                var data_y = glyph._ys.get(i)[j];
                                var jj = j;
                                var rx = void 0;
                                var ry = void 0;
                                switch (this.model.line_policy) {
                                    case "interp": { // and renderer.get_interpolation_hit?
                                        _q = (0, tslib_1.__read)(glyph.get_interpolation_hit(i, j, geometry), 2), data_x = _q[0], data_y = _q[1];
                                        rx = xscale.compute(data_x);
                                        ry = yscale.compute(data_y);
                                        break;
                                    }
                                    case "prev": {
                                        _r = (0, tslib_1.__read)(_line_hit(glyph.sxs.get(i), glyph.sys.get(i), j), 2), _s = (0, tslib_1.__read)(_r[0], 2), rx = _s[0], ry = _s[1], jj = _r[1];
                                        break;
                                    }
                                    case "next": {
                                        _t = (0, tslib_1.__read)(_line_hit(glyph.sxs.get(i), glyph.sys.get(i), j + 1), 2), _u = (0, tslib_1.__read)(_t[0], 2), rx = _u[0], ry = _u[1], jj = _t[1];
                                        break;
                                    }
                                    case "nearest": {
                                        _v = (0, tslib_1.__read)(_nearest_line_hit(j, geometry, sx, sy, glyph.sxs.get(i), glyph.sys.get(i)), 2), _w = (0, tslib_1.__read)(_v[0], 2), rx = _w[0], ry = _w[1], jj = _v[1];
                                        data_x = glyph._xs.get(i)[jj];
                                        data_y = glyph._ys.get(i)[jj];
                                        break;
                                    }
                                    default:
                                        throw new Error("shouldn't have happened");
                                }
                                var index = void 0;
                                if (renderer instanceof glyph_renderer_1.GlyphRenderer)
                                    index = renderer.view.convert_indices_from_subset([i])[0];
                                else
                                    index = i;
                                var vars = {
                                    index: index,
                                    x: x,
                                    y: y,
                                    sx: sx,
                                    sy: sy,
                                    data_x: data_x,
                                    data_y: data_y,
                                    segment_index: jj,
                                    indices: subset_indices.multiline_indices,
                                    name: renderer.name,
                                };
                                tooltips.push([rx, ry, this._render_tooltips(ds, index, vars)]);
                            }
                        }
                        catch (e_10_1) {
                            e_10 = { error: e_10_1 };
                        }
                        finally {
                            try {
                                if (_11 && !_11.done && (_p = _10.return))
                                    _p.call(_10);
                            }
                            finally {
                                if (e_10)
                                    throw e_10.error;
                            }
                        }
                    }
                    else {
                        // handle non-multiglyphs
                        var data_x = (_1 = glyph._x) === null || _1 === void 0 ? void 0 : _1[i];
                        var data_y = (_2 = glyph._y) === null || _2 === void 0 ? void 0 : _2[i];
                        var rx = void 0;
                        var ry = void 0;
                        if (this.model.point_policy == "snap_to_data") { // and renderer.glyph.sx? and renderer.glyph.sy?
                            // Pass in our screen position so we can determine which patch we're
                            // over if there are discontinuous patches.
                            var pt = glyph.get_anchor_point(this.model.anchor, i, [sx, sy]);
                            if (pt == null) {
                                pt = glyph.get_anchor_point("center", i, [sx, sy]);
                                if (pt == null)
                                    continue; // TODO?
                            }
                            rx = pt.x;
                            ry = pt.y;
                        }
                        else
                            _z = (0, tslib_1.__read)([sx, sy], 2), rx = _z[0], ry = _z[1];
                        var index = void 0;
                        if (renderer instanceof glyph_renderer_1.GlyphRenderer)
                            index = renderer.view.convert_indices_from_subset([i])[0];
                        else
                            index = i;
                        var vars = {
                            index: index,
                            x: x,
                            y: y,
                            sx: sx,
                            sy: sy,
                            data_x: data_x,
                            data_y: data_y,
                            indices: subset_indices.indices,
                            name: renderer.name,
                        };
                        tooltips.push([rx, ry, this._render_tooltips(ds, index, vars)]);
                    }
                }
            }
            catch (e_9_1) {
                e_9 = { error: e_9_1 };
            }
            finally {
                try {
                    if (_9 && !_9.done && (_o = _8.return))
                        _o.call(_8);
                }
                finally {
                    if (e_9)
                        throw e_9.error;
                }
            }
            if (tooltips.length == 0)
                tooltip.clear();
            else {
                var content = tooltip.content;
                (0, dom_1.empty)(tooltip.content);
                try {
                    for (var tooltips_1 = (0, tslib_1.__values)(tooltips), tooltips_1_1 = tooltips_1.next(); !tooltips_1_1.done; tooltips_1_1 = tooltips_1.next()) {
                        var _12 = (0, tslib_1.__read)(tooltips_1_1.value, 3), node = _12[2];
                        if (node != null)
                            content.appendChild(node);
                    }
                }
                catch (e_11_1) {
                    e_11 = { error: e_11_1 };
                }
                finally {
                    try {
                        if (tooltips_1_1 && !tooltips_1_1.done && (_0 = tooltips_1.return))
                            _0.call(tooltips_1);
                    }
                    finally {
                        if (e_11)
                            throw e_11.error;
                    }
                }
                var _13 = (0, tslib_1.__read)(tooltips[tooltips.length - 1], 2), x_1 = _13[0], y_1 = _13[1];
                tooltip.setv({ position: [x_1, y_1] }, { check_eq: false }); // XXX: force update
            }
        };
        HoverToolView.prototype._emit_callback = function (geometry) {
            var e_12, _b;
            var callback = this.model.callback;
            if (callback == null)
                return;
            try {
                for (var _c = (0, tslib_1.__values)(this.computed_renderers), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var renderer = _d.value;
                    if (!(renderer instanceof glyph_renderer_1.GlyphRenderer))
                        continue;
                    var glyph_renderer_view = this.plot_view.renderer_view(renderer);
                    if (glyph_renderer_view == null)
                        continue;
                    var _e = glyph_renderer_view.coordinates, x_scale = _e.x_scale, y_scale = _e.y_scale;
                    var x = x_scale.invert(geometry.sx);
                    var y = y_scale.invert(geometry.sy);
                    var index = renderer.data_source.inspected;
                    callback.execute(this.model, {
                        geometry: (0, tslib_1.__assign)({ x: x, y: y }, geometry),
                        renderer: renderer,
                        index: index,
                    });
                }
            }
            catch (e_12_1) {
                e_12 = { error: e_12_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_12)
                        throw e_12.error;
                }
            }
        };
        HoverToolView.prototype._create_template = function (tooltips) {
            var e_13, _b;
            var rows = (0, dom_1.div)({ style: { display: "table", borderSpacing: "2px" } });
            try {
                for (var tooltips_2 = (0, tslib_1.__values)(tooltips), tooltips_2_1 = tooltips_2.next(); !tooltips_2_1.done; tooltips_2_1 = tooltips_2.next()) {
                    var _c = (0, tslib_1.__read)(tooltips_2_1.value, 1), label = _c[0];
                    var row = (0, dom_1.div)({ style: { display: "table-row" } });
                    rows.appendChild(row);
                    var label_cell = (0, dom_1.div)({ style: { display: "table-cell" }, class: styles.tooltip_row_label }, label.length != 0 ? label + ": " : "");
                    row.appendChild(label_cell);
                    var value_el = (0, dom_1.span)();
                    value_el.dataset.value = "";
                    var swatch_el = (0, dom_1.span)({ class: styles.tooltip_color_block }, " ");
                    swatch_el.dataset.swatch = "";
                    (0, dom_1.undisplay)(swatch_el);
                    var value_cell = (0, dom_1.div)({ style: { display: "table-cell" }, class: styles.tooltip_row_value }, value_el, swatch_el);
                    row.appendChild(value_cell);
                }
            }
            catch (e_13_1) {
                e_13 = { error: e_13_1 };
            }
            finally {
                try {
                    if (tooltips_2_1 && !tooltips_2_1.done && (_b = tooltips_2.return))
                        _b.call(tooltips_2);
                }
                finally {
                    if (e_13)
                        throw e_13.error;
                }
            }
            return rows;
        };
        HoverToolView.prototype._render_template = function (template, tooltips, ds, i, vars) {
            var e_14, _b, e_15, _c;
            var el = template.cloneNode(true);
            var value_els = el.querySelectorAll("[data-value]");
            var swatch_els = el.querySelectorAll("[data-swatch]");
            var color_re = /\$color(\[.*\])?:(\w*)/;
            var swatch_re = /\$swatch:(\w*)/;
            try {
                for (var _d = (0, tslib_1.__values)((0, iterator_1.enumerate)(tooltips)), _e = _d.next(); !_e.done; _e = _d.next()) {
                    var _f = (0, tslib_1.__read)(_e.value, 2), _g = (0, tslib_1.__read)(_f[0], 2), value = _g[1], j = _f[1];
                    var swatch_match = value.match(swatch_re);
                    var color_match = value.match(color_re);
                    if (swatch_match != null || color_match != null) {
                        if (swatch_match != null) {
                            var _h = (0, tslib_1.__read)(swatch_match, 2), colname = _h[1];
                            var column = ds.get_column(colname);
                            if (column == null) {
                                value_els[j].textContent = colname + " unknown";
                            }
                            else {
                                var color = (0, types_1.isNumber)(i) ? column[i] : null;
                                if (color != null) {
                                    swatch_els[j].style.backgroundColor = (0, color_1.color2css)(color);
                                    (0, dom_1.display)(swatch_els[j]);
                                }
                            }
                        }
                        if (color_match != null) {
                            var _j = (0, tslib_1.__read)(color_match, 3), _k = _j[1], opts = _k === void 0 ? "" : _k, colname = _j[2];
                            var column = ds.get_column(colname); // XXX: change to columnar ds
                            if (column == null) {
                                value_els[j].textContent = colname + " unknown";
                                continue;
                            }
                            var hex = opts.indexOf("hex") >= 0;
                            var swatch = opts.indexOf("swatch") >= 0;
                            var color = (0, types_1.isNumber)(i) ? column[i] : null;
                            if (color == null) {
                                value_els[j].textContent = "(null)";
                                continue;
                            }
                            value_els[j].textContent = hex ? (0, color_1.color2hex)(color) : (0, color_1.color2css)(color); // TODO: color2pretty
                            if (swatch) {
                                swatch_els[j].style.backgroundColor = (0, color_1.color2css)(color);
                                (0, dom_1.display)(swatch_els[j]);
                            }
                        }
                    }
                    else {
                        var content = (0, templating_1.replace_placeholders)(value.replace("$~", "$data_"), ds, i, this.model.formatters, vars);
                        if ((0, types_1.isString)(content)) {
                            value_els[j].textContent = content;
                        }
                        else {
                            try {
                                for (var content_1 = (e_15 = void 0, (0, tslib_1.__values)(content)), content_1_1 = content_1.next(); !content_1_1.done; content_1_1 = content_1.next()) {
                                    var el_1 = content_1_1.value;
                                    value_els[j].appendChild(el_1);
                                }
                            }
                            catch (e_15_1) {
                                e_15 = { error: e_15_1 };
                            }
                            finally {
                                try {
                                    if (content_1_1 && !content_1_1.done && (_c = content_1.return))
                                        _c.call(content_1);
                                }
                                finally {
                                    if (e_15)
                                        throw e_15.error;
                                }
                            }
                        }
                    }
                }
            }
            catch (e_14_1) {
                e_14 = { error: e_14_1 };
            }
            finally {
                try {
                    if (_e && !_e.done && (_b = _d.return))
                        _b.call(_d);
                }
                finally {
                    if (e_14)
                        throw e_14.error;
                }
            }
            return el;
        };
        HoverToolView.prototype._render_tooltips = function (ds, i, vars) {
            var _b;
            var tooltips = this.model.tooltips;
            if ((0, types_1.isString)(tooltips)) {
                var content = (0, templating_1.replace_placeholders)({ html: tooltips }, ds, i, this.model.formatters, vars);
                return (0, dom_1.div)(content);
            }
            else if ((0, types_1.isFunction)(tooltips)) {
                return tooltips(ds, vars);
            }
            else if (tooltips instanceof dom_2.Template) {
                this._template_view.update(ds, i, vars);
                return this._template_view.el;
            }
            else if (tooltips != null) {
                var template = (_b = this._template_el) !== null && _b !== void 0 ? _b : (this._template_el = this._create_template(tooltips));
                return this._render_template(template, tooltips, ds, i, vars);
            }
            else
                return null;
        };
        return HoverToolView;
    }(inspect_tool_1.InspectToolView));
    exports.HoverToolView = HoverToolView;
    HoverToolView.__name__ = "HoverToolView";
    var HoverTool = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(HoverTool, _super);
        function HoverTool(attrs) {
            var _this = _super.call(this, attrs) || this;
            _this.tool_name = "Hover";
            _this.icon = icons_css_1.tool_icon_hover;
            return _this;
        }
        return HoverTool;
    }(inspect_tool_1.InspectTool));
    exports.HoverTool = HoverTool;
    _a = HoverTool;
    HoverTool.__name__ = "HoverTool";
    (function () {
        _a.prototype.default_view = HoverToolView;
        _a.define(function (_b) {
            var Any = _b.Any, Boolean = _b.Boolean, String = _b.String, Array = _b.Array, Tuple = _b.Tuple, Dict = _b.Dict, Or = _b.Or, Ref = _b.Ref, Function = _b.Function, Auto = _b.Auto, Nullable = _b.Nullable;
            return ({
                tooltips: [Nullable(Or(Ref(dom_2.Template), String, Array(Tuple(String, String)), Function())), [
                        ["index", "$index"],
                        ["data (x, y)", "($x, $y)"],
                        ["screen (x, y)", "($sx, $sy)"],
                    ]],
                formatters: [Dict(Or(Ref(customjs_hover_1.CustomJSHover), templating_1.FormatterType)), {}],
                renderers: [Or(Array(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
                names: [Array(String), []],
                mode: [enums_1.HoverMode, "mouse"],
                muted_policy: [enums_1.MutedPolicy, "show"],
                point_policy: [enums_1.PointPolicy, "snap_to_data"],
                line_policy: [enums_1.LinePolicy, "nearest"],
                show_arrow: [Boolean, true],
                anchor: [enums_1.Anchor, "center"],
                attachment: [enums_1.TooltipAttachment, "horizontal"],
                callback: [Nullable(Any /*TODO*/)],
            });
        });
        _a.register_alias("hover", function () { return new HoverTool(); });
    })();
},
/* models/dom/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
    var model_1 = require(168) /* ../../model */;
    var layout_dom_1 = require(424) /* ../layouts/layout_dom */;
    var styles_1 = require(508) /* ./styles */;
    __esExport("Styles", styles_1.Styles);
    var dom_1 = require(158) /* ../../core/dom */;
    var view_1 = require(157) /* ../../core/view */;
    var dom_view_1 = require(341) /* ../../core/dom_view */;
    var build_views_1 = require(228) /* ../../core/build_views */;
    var types_1 = require(125) /* ../../core/util/types */;
    var object_1 = require(128) /* ../../core/util/object */;
    var styles = (0, tslib_1.__importStar)(require(357) /* ../../styles/tooltips.css */);
    var templating_1 = require(267) /* ../../core/util/templating */;
    var DOMNodeView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DOMNodeView, _super);
        function DOMNodeView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return DOMNodeView;
    }(dom_view_1.DOMView));
    exports.DOMNodeView = DOMNodeView;
    DOMNodeView.__name__ = "DOMNodeView";
    var DOMNode = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DOMNode, _super);
        function DOMNode(attrs) {
            return _super.call(this, attrs) || this;
        }
        return DOMNode;
    }(model_1.Model));
    exports.DOMNode = DOMNode;
    DOMNode.__name__ = "DOMNode";
    DOMNode.__module__ = "bokeh.models.dom";
    var TextView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TextView, _super);
        function TextView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TextView.prototype.render = function () {
            _super.prototype.render.call(this);
            this.el.textContent = this.model.content;
        };
        TextView.prototype._createElement = function () {
            return document.createTextNode("");
        };
        return TextView;
    }(DOMNodeView));
    exports.TextView = TextView;
    TextView.__name__ = "TextView";
    var Text = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Text, _super);
        function Text(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Text;
    }(DOMNode));
    exports.Text = Text;
    _a = Text;
    Text.__name__ = "Text";
    (function () {
        _a.prototype.default_view = TextView;
        _a.define(function (_p) {
            var String = _p.String;
            return ({
                content: [String, ""],
            });
        });
    })();
    var PlaceholderView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(PlaceholderView, _super);
        function PlaceholderView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return PlaceholderView;
    }(DOMNodeView));
    exports.PlaceholderView = PlaceholderView;
    PlaceholderView.__name__ = "PlaceholderView";
    PlaceholderView.tag_name = "span";
    var Placeholder = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Placeholder, _super);
        function Placeholder(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Placeholder;
    }(DOMNode));
    exports.Placeholder = Placeholder;
    _b = Placeholder;
    Placeholder.__name__ = "Placeholder";
    (function () {
        _b.define(function (_p) { return ({}); });
    })();
    var IndexView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(IndexView, _super);
        function IndexView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        IndexView.prototype.update = function (_source, i, _vars /*, formatters?: Formatters*/) {
            this.el.textContent = i.toString();
        };
        return IndexView;
    }(PlaceholderView));
    exports.IndexView = IndexView;
    IndexView.__name__ = "IndexView";
    var Index = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Index, _super);
        function Index(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Index;
    }(Placeholder));
    exports.Index = Index;
    _c = Index;
    Index.__name__ = "Index";
    (function () {
        _c.prototype.default_view = IndexView;
        _c.define(function (_p) { return ({}); });
    })();
    var ValueRefView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ValueRefView, _super);
        function ValueRefView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ValueRefView.prototype.update = function (source, i, _vars /*, formatters?: Formatters*/) {
            var value = (0, templating_1._get_column_value)(this.model.field, source, i);
            var text = value == null ? "???" : "" + value; //.toString()
            this.el.textContent = text;
        };
        return ValueRefView;
    }(PlaceholderView));
    exports.ValueRefView = ValueRefView;
    ValueRefView.__name__ = "ValueRefView";
    var ValueRef = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ValueRef, _super);
        function ValueRef(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ValueRef;
    }(Placeholder));
    exports.ValueRef = ValueRef;
    _d = ValueRef;
    ValueRef.__name__ = "ValueRef";
    (function () {
        _d.prototype.default_view = ValueRefView;
        _d.define(function (_p) {
            var String = _p.String;
            return ({
                field: [String],
            });
        });
    })();
    var ColorRefView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColorRefView, _super);
        function ColorRefView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ColorRefView.prototype.render = function () {
            _super.prototype.render.call(this);
            this.value_el = (0, dom_1.span)();
            this.swatch_el = (0, dom_1.span)({ class: styles.tooltip_color_block }, " ");
            this.el.appendChild(this.value_el);
            this.el.appendChild(this.swatch_el);
        };
        ColorRefView.prototype.update = function (source, i, _vars /*, formatters?: Formatters*/) {
            var value = (0, templating_1._get_column_value)(this.model.field, source, i);
            var text = value == null ? "???" : "" + value; //.toString()
            this.el.textContent = text;
        };
        return ColorRefView;
    }(ValueRefView));
    exports.ColorRefView = ColorRefView;
    ColorRefView.__name__ = "ColorRefView";
    var ColorRef = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ColorRef, _super);
        function ColorRef(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ColorRef;
    }(ValueRef));
    exports.ColorRef = ColorRef;
    _e = ColorRef;
    ColorRef.__name__ = "ColorRef";
    (function () {
        _e.prototype.default_view = ColorRefView;
        _e.define(function (_p) {
            var Boolean = _p.Boolean;
            return ({
                hex: [Boolean, true],
                swatch: [Boolean, true],
            });
        });
    })();
    var DOMElementView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DOMElementView, _super);
        function DOMElementView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.child_views = new Map();
            return _this;
        }
        DOMElementView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var children;
                return (0, tslib_1.__generator)(this, function (_p) {
                    switch (_p.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _p.sent();
                            children = this.model.children.filter(function (obj) { return obj instanceof model_1.Model; });
                            return [4 /*yield*/, (0, build_views_1.build_views)(this.child_views, children, { parent: this })];
                        case 2:
                            _p.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        DOMElementView.prototype.render = function () {
            var e_1, _p, e_2, _q, e_3, _r;
            _super.prototype.render.call(this);
            var style = this.model.style;
            if (style != null) {
                /*
                type IsString<T> = T extends string ? T : never
                type Key = Exclude<IsString<keyof CSSStyleDeclaration>,
                  "length" | "parentRule" | "getPropertyPriority" | "getPropertyValue" | "item" | "removeProperty" | "setProperty">
                //this.el.style[key as Key] = value
                */
                if (style instanceof styles_1.Styles) {
                    try {
                        for (var style_1 = (0, tslib_1.__values)(style), style_1_1 = style_1.next(); !style_1_1.done; style_1_1 = style_1.next()) {
                            var prop = style_1_1.value;
                            var value = prop.get_value();
                            if ((0, types_1.isString)(value)) {
                                var name = prop.attr.replace(/_/g, "-");
                                if (this.el.style.hasOwnProperty(name)) {
                                    this.el.style.setProperty(name, value);
                                }
                            }
                        }
                    }
                    catch (e_1_1) {
                        e_1 = { error: e_1_1 };
                    }
                    finally {
                        try {
                            if (style_1_1 && !style_1_1.done && (_p = style_1.return))
                                _p.call(style_1);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                    }
                }
                else {
                    try {
                        for (var _s = (0, tslib_1.__values)((0, object_1.entries)(style)), _t = _s.next(); !_t.done; _t = _s.next()) {
                            var _u = (0, tslib_1.__read)(_t.value, 2), key = _u[0], value = _u[1];
                            var name = key.replace(/_/g, "-");
                            if (this.el.style.hasOwnProperty(name)) {
                                this.el.style.setProperty(name, value);
                            }
                        }
                    }
                    catch (e_2_1) {
                        e_2 = { error: e_2_1 };
                    }
                    finally {
                        try {
                            if (_t && !_t.done && (_q = _s.return))
                                _q.call(_s);
                        }
                        finally {
                            if (e_2)
                                throw e_2.error;
                        }
                    }
                }
            }
            try {
                for (var _v = (0, tslib_1.__values)(this.model.children), _w = _v.next(); !_w.done; _w = _v.next()) {
                    var child = _w.value;
                    if ((0, types_1.isString)(child)) {
                        var node = document.createTextNode(child);
                        this.el.appendChild(node);
                    }
                    else {
                        var child_view = this.child_views.get(child);
                        child_view.renderTo(this.el);
                    }
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_w && !_w.done && (_r = _v.return))
                        _r.call(_v);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
        };
        return DOMElementView;
    }(DOMNodeView));
    exports.DOMElementView = DOMElementView;
    DOMElementView.__name__ = "DOMElementView";
    var DOMElement = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DOMElement, _super);
        function DOMElement(attrs) {
            return _super.call(this, attrs) || this;
        }
        return DOMElement;
    }(DOMNode));
    exports.DOMElement = DOMElement;
    _f = DOMElement;
    DOMElement.__name__ = "DOMElement";
    (function () {
        _f.define(function (_p) {
            var String = _p.String, Array = _p.Array, Dict = _p.Dict, Or = _p.Or, Nullable = _p.Nullable, Ref = _p.Ref;
            return ({
                style: [Nullable(Or(Ref(styles_1.Styles), Dict(String))), null],
                children: [Array(Or(String, Ref(DOMNode), Ref(layout_dom_1.LayoutDOM))), []],
            });
        });
    })();
    var ActionView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ActionView, _super);
        function ActionView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return ActionView;
    }(view_1.View));
    exports.ActionView = ActionView;
    ActionView.__name__ = "ActionView";
    var Action = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Action, _super);
        function Action(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Action;
    }(model_1.Model));
    exports.Action = Action;
    _g = Action;
    Action.__name__ = "Action";
    Action.__module__ = "bokeh.models.dom";
    (function () {
        _g.define(function (_p) { return ({}); });
    })();
    var TemplateView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TemplateView, _super);
        function TemplateView() {
            var _this = _super.apply(this, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(arguments), false)) || this;
            _this.action_views = new Map();
            return _this;
        }
        TemplateView.prototype.lazy_initialize = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_p) {
                    switch (_p.label) {
                        case 0: return [4 /*yield*/, _super.prototype.lazy_initialize.call(this)];
                        case 1:
                            _p.sent();
                            return [4 /*yield*/, (0, build_views_1.build_views)(this.action_views, this.model.actions, { parent: this })];
                        case 2:
                            _p.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        TemplateView.prototype.remove = function () {
            (0, build_views_1.remove_views)(this.action_views);
            _super.prototype.remove.call(this);
        };
        TemplateView.prototype.update = function (source, i, vars /*, formatters?: Formatters*/) {
            var e_4, _p;
            if (vars === void 0) {
                vars = {};
            }
            function descend(obj) {
                var e_5, _p;
                try {
                    for (var _q = (0, tslib_1.__values)(obj.child_views.values()), _r = _q.next(); !_r.done; _r = _q.next()) {
                        var child = _r.value;
                        if (child instanceof PlaceholderView) {
                            child.update(source, i, vars);
                        }
                        else if (child instanceof DOMElementView) {
                            descend(child);
                        }
                    }
                }
                catch (e_5_1) {
                    e_5 = { error: e_5_1 };
                }
                finally {
                    try {
                        if (_r && !_r.done && (_p = _q.return))
                            _p.call(_q);
                    }
                    finally {
                        if (e_5)
                            throw e_5.error;
                    }
                }
            }
            descend(this);
            try {
                for (var _q = (0, tslib_1.__values)(this.action_views.values()), _r = _q.next(); !_r.done; _r = _q.next()) {
                    var action = _r.value;
                    action.update(source, i, vars);
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_r && !_r.done && (_p = _q.return))
                        _p.call(_q);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
        };
        return TemplateView;
    }(DOMElementView));
    exports.TemplateView = TemplateView;
    TemplateView.__name__ = "TemplateView";
    TemplateView.tag_name = "div";
    var Template = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Template, _super);
        function Template() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Template;
    }(DOMElement));
    exports.Template = Template;
    _h = Template;
    Template.__name__ = "Template";
    (function () {
        _h.prototype.default_view = TemplateView;
        _h.define(function (_p) {
            var Array = _p.Array, Ref = _p.Ref;
            return ({
                actions: [Array(Ref(Action)), []],
            });
        });
    })();
    var SpanView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(SpanView, _super);
        function SpanView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return SpanView;
    }(DOMElementView));
    exports.SpanView = SpanView;
    SpanView.__name__ = "SpanView";
    SpanView.tag_name = "span";
    var Span = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Span, _super);
        function Span() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Span;
    }(DOMElement));
    exports.Span = Span;
    _j = Span;
    Span.__name__ = "Span";
    (function () {
        _j.prototype.default_view = SpanView;
    })();
    var DivView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(DivView, _super);
        function DivView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return DivView;
    }(DOMElementView));
    exports.DivView = DivView;
    DivView.__name__ = "DivView";
    DivView.tag_name = "div";
    var Div = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Div, _super);
        function Div() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Div;
    }(DOMElement));
    exports.Div = Div;
    _k = Div;
    Div.__name__ = "Div";
    (function () {
        _k.prototype.default_view = DivView;
    })();
    var TableView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TableView, _super);
        function TableView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return TableView;
    }(DOMElementView));
    exports.TableView = TableView;
    TableView.__name__ = "TableView";
    TableView.tag_name = "table";
    var Table = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Table, _super);
        function Table() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Table;
    }(DOMElement));
    exports.Table = Table;
    _l = Table;
    Table.__name__ = "Table";
    (function () {
        _l.prototype.default_view = TableView;
    })();
    var TableRowView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TableRowView, _super);
        function TableRowView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return TableRowView;
    }(DOMElementView));
    exports.TableRowView = TableRowView;
    TableRowView.__name__ = "TableRowView";
    TableRowView.tag_name = "tr";
    var TableRow = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(TableRow, _super);
        function TableRow() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return TableRow;
    }(DOMElement));
    exports.TableRow = TableRow;
    _m = TableRow;
    TableRow.__name__ = "TableRow";
    (function () {
        _m.prototype.default_view = TableRowView;
    })();
    /////
    var renderer_1 = require(156) /* ../renderers/renderer */;
    var iterator_1 = require(349) /* ../../core/util/iterator */;
    var ToggleGroupView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToggleGroupView, _super);
        function ToggleGroupView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ToggleGroupView.prototype.update = function (_source, i, _vars /*, formatters?: Formatters*/) {
            var e_6, _p;
            try {
                for (var _q = (0, tslib_1.__values)((0, iterator_1.enumerate)(this.model.groups)), _r = _q.next(); !_r.done; _r = _q.next()) {
                    var _s = (0, tslib_1.__read)(_r.value, 2), group = _s[0], j = _s[1];
                    group.visible = i == j;
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_r && !_r.done && (_p = _q.return))
                        _p.call(_q);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
        };
        return ToggleGroupView;
    }(ActionView));
    exports.ToggleGroupView = ToggleGroupView;
    ToggleGroupView.__name__ = "ToggleGroupView";
    var ToggleGroup = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToggleGroup, _super);
        function ToggleGroup(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ToggleGroup;
    }(Action));
    exports.ToggleGroup = ToggleGroup;
    _o = ToggleGroup;
    ToggleGroup.__name__ = "ToggleGroup";
    (function () {
        _o.prototype.default_view = ToggleGroupView;
        _o.define(function (_p) {
            var Array = _p.Array, Ref = _p.Ref;
            return ({
                groups: [Array(Ref(renderer_1.RendererGroup)), []],
            });
        });
    })();
},
/* models/dom/styles.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var model_1 = require(168) /* ../../model */;
    var Styles = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(Styles, _super);
        function Styles(attrs) {
            return _super.call(this, attrs) || this;
        }
        return Styles;
    }(model_1.Model));
    exports.Styles = Styles;
    _a = Styles;
    Styles.__name__ = "Styles";
    Styles.__module__ = "bokeh.models.css";
    (function () {
        _a.define(function (_b) {
            var String = _b.String, Nullable = _b.Nullable;
            return ({
                align_content: [Nullable(String), null],
                align_items: [Nullable(String), null],
                align_self: [Nullable(String), null],
                alignment_baseline: [Nullable(String), null],
                all: [Nullable(String), null],
                animation: [Nullable(String), null],
                animation_delay: [Nullable(String), null],
                animation_direction: [Nullable(String), null],
                animation_duration: [Nullable(String), null],
                animation_fill_mode: [Nullable(String), null],
                animation_iteration_count: [Nullable(String), null],
                animation_name: [Nullable(String), null],
                animation_play_state: [Nullable(String), null],
                animation_timing_function: [Nullable(String), null],
                backface_visibility: [Nullable(String), null],
                background: [Nullable(String), null],
                background_attachment: [Nullable(String), null],
                background_clip: [Nullable(String), null],
                background_color: [Nullable(String), null],
                background_image: [Nullable(String), null],
                background_origin: [Nullable(String), null],
                background_position: [Nullable(String), null],
                background_position_x: [Nullable(String), null],
                background_position_y: [Nullable(String), null],
                background_repeat: [Nullable(String), null],
                background_size: [Nullable(String), null],
                baseline_shift: [Nullable(String), null],
                block_size: [Nullable(String), null],
                border: [Nullable(String), null],
                border_block_end: [Nullable(String), null],
                border_block_end_color: [Nullable(String), null],
                border_block_end_style: [Nullable(String), null],
                border_block_end_width: [Nullable(String), null],
                border_block_start: [Nullable(String), null],
                border_block_start_color: [Nullable(String), null],
                border_block_start_style: [Nullable(String), null],
                border_block_start_width: [Nullable(String), null],
                border_bottom: [Nullable(String), null],
                border_bottom_color: [Nullable(String), null],
                border_bottom_left_radius: [Nullable(String), null],
                border_bottom_right_radius: [Nullable(String), null],
                border_bottom_style: [Nullable(String), null],
                border_bottom_width: [Nullable(String), null],
                border_collapse: [Nullable(String), null],
                border_color: [Nullable(String), null],
                border_image: [Nullable(String), null],
                border_image_outset: [Nullable(String), null],
                border_image_repeat: [Nullable(String), null],
                border_image_slice: [Nullable(String), null],
                border_image_source: [Nullable(String), null],
                border_image_width: [Nullable(String), null],
                border_inline_end: [Nullable(String), null],
                border_inline_end_color: [Nullable(String), null],
                border_inline_end_style: [Nullable(String), null],
                border_inline_end_width: [Nullable(String), null],
                border_inline_start: [Nullable(String), null],
                border_inline_start_color: [Nullable(String), null],
                border_inline_start_style: [Nullable(String), null],
                border_inline_start_width: [Nullable(String), null],
                border_left: [Nullable(String), null],
                border_left_color: [Nullable(String), null],
                border_left_style: [Nullable(String), null],
                border_left_width: [Nullable(String), null],
                border_radius: [Nullable(String), null],
                border_right: [Nullable(String), null],
                border_right_color: [Nullable(String), null],
                border_right_style: [Nullable(String), null],
                border_right_width: [Nullable(String), null],
                border_spacing: [Nullable(String), null],
                border_style: [Nullable(String), null],
                border_top: [Nullable(String), null],
                border_top_color: [Nullable(String), null],
                border_top_left_radius: [Nullable(String), null],
                border_top_right_radius: [Nullable(String), null],
                border_top_style: [Nullable(String), null],
                border_top_width: [Nullable(String), null],
                border_width: [Nullable(String), null],
                bottom: [Nullable(String), null],
                box_shadow: [Nullable(String), null],
                box_sizing: [Nullable(String), null],
                break_after: [Nullable(String), null],
                break_before: [Nullable(String), null],
                break_inside: [Nullable(String), null],
                caption_side: [Nullable(String), null],
                caret_color: [Nullable(String), null],
                clear: [Nullable(String), null],
                clip: [Nullable(String), null],
                clip_path: [Nullable(String), null],
                clip_rule: [Nullable(String), null],
                color: [Nullable(String), null],
                color_interpolation: [Nullable(String), null],
                color_interpolation_filters: [Nullable(String), null],
                column_count: [Nullable(String), null],
                column_fill: [Nullable(String), null],
                column_gap: [Nullable(String), null],
                column_rule: [Nullable(String), null],
                column_rule_color: [Nullable(String), null],
                column_rule_style: [Nullable(String), null],
                column_rule_width: [Nullable(String), null],
                column_span: [Nullable(String), null],
                column_width: [Nullable(String), null],
                columns: [Nullable(String), null],
                content: [Nullable(String), null],
                counter_increment: [Nullable(String), null],
                counter_reset: [Nullable(String), null],
                css_float: [Nullable(String), null],
                css_text: [Nullable(String), null],
                cursor: [Nullable(String), null],
                direction: [Nullable(String), null],
                display: [Nullable(String), null],
                dominant_baseline: [Nullable(String), null],
                empty_cells: [Nullable(String), null],
                fill: [Nullable(String), null],
                fill_opacity: [Nullable(String), null],
                fill_rule: [Nullable(String), null],
                filter: [Nullable(String), null],
                flex: [Nullable(String), null],
                flex_basis: [Nullable(String), null],
                flex_direction: [Nullable(String), null],
                flex_flow: [Nullable(String), null],
                flex_grow: [Nullable(String), null],
                flex_shrink: [Nullable(String), null],
                flex_wrap: [Nullable(String), null],
                float: [Nullable(String), null],
                flood_color: [Nullable(String), null],
                flood_opacity: [Nullable(String), null],
                font: [Nullable(String), null],
                font_family: [Nullable(String), null],
                font_feature_settings: [Nullable(String), null],
                font_kerning: [Nullable(String), null],
                font_size: [Nullable(String), null],
                font_size_adjust: [Nullable(String), null],
                font_stretch: [Nullable(String), null],
                font_style: [Nullable(String), null],
                font_synthesis: [Nullable(String), null],
                font_variant: [Nullable(String), null],
                font_variant_caps: [Nullable(String), null],
                font_variant_east_asian: [Nullable(String), null],
                font_variant_ligatures: [Nullable(String), null],
                font_variant_numeric: [Nullable(String), null],
                font_variant_position: [Nullable(String), null],
                font_weight: [Nullable(String), null],
                gap: [Nullable(String), null],
                glyph_orientation_vertical: [Nullable(String), null],
                grid: [Nullable(String), null],
                grid_area: [Nullable(String), null],
                grid_auto_columns: [Nullable(String), null],
                grid_auto_flow: [Nullable(String), null],
                grid_auto_rows: [Nullable(String), null],
                grid_column: [Nullable(String), null],
                grid_column_end: [Nullable(String), null],
                grid_column_gap: [Nullable(String), null],
                grid_column_start: [Nullable(String), null],
                grid_gap: [Nullable(String), null],
                grid_row: [Nullable(String), null],
                grid_row_end: [Nullable(String), null],
                grid_row_gap: [Nullable(String), null],
                grid_row_start: [Nullable(String), null],
                grid_template: [Nullable(String), null],
                grid_template_areas: [Nullable(String), null],
                grid_template_columns: [Nullable(String), null],
                grid_template_rows: [Nullable(String), null],
                height: [Nullable(String), null],
                hyphens: [Nullable(String), null],
                image_orientation: [Nullable(String), null],
                image_rendering: [Nullable(String), null],
                inline_size: [Nullable(String), null],
                justify_content: [Nullable(String), null],
                justify_items: [Nullable(String), null],
                justify_self: [Nullable(String), null],
                left: [Nullable(String), null],
                letter_spacing: [Nullable(String), null],
                lighting_color: [Nullable(String), null],
                line_break: [Nullable(String), null],
                line_height: [Nullable(String), null],
                list_style: [Nullable(String), null],
                list_style_image: [Nullable(String), null],
                list_style_position: [Nullable(String), null],
                list_style_type: [Nullable(String), null],
                margin: [Nullable(String), null],
                margin_block_end: [Nullable(String), null],
                margin_block_start: [Nullable(String), null],
                margin_bottom: [Nullable(String), null],
                margin_inline_end: [Nullable(String), null],
                margin_inline_start: [Nullable(String), null],
                margin_left: [Nullable(String), null],
                margin_right: [Nullable(String), null],
                margin_top: [Nullable(String), null],
                marker: [Nullable(String), null],
                marker_end: [Nullable(String), null],
                marker_mid: [Nullable(String), null],
                marker_start: [Nullable(String), null],
                mask: [Nullable(String), null],
                mask_composite: [Nullable(String), null],
                mask_image: [Nullable(String), null],
                mask_position: [Nullable(String), null],
                mask_repeat: [Nullable(String), null],
                mask_size: [Nullable(String), null],
                mask_type: [Nullable(String), null],
                max_block_size: [Nullable(String), null],
                max_height: [Nullable(String), null],
                max_inline_size: [Nullable(String), null],
                max_width: [Nullable(String), null],
                min_block_size: [Nullable(String), null],
                min_height: [Nullable(String), null],
                min_inline_size: [Nullable(String), null],
                min_width: [Nullable(String), null],
                object_fit: [Nullable(String), null],
                object_position: [Nullable(String), null],
                opacity: [Nullable(String), null],
                order: [Nullable(String), null],
                orphans: [Nullable(String), null],
                outline: [Nullable(String), null],
                outline_color: [Nullable(String), null],
                outline_offset: [Nullable(String), null],
                outline_style: [Nullable(String), null],
                outline_width: [Nullable(String), null],
                overflow: [Nullable(String), null],
                overflow_anchor: [Nullable(String), null],
                overflow_wrap: [Nullable(String), null],
                overflow_x: [Nullable(String), null],
                overflow_y: [Nullable(String), null],
                overscroll_behavior: [Nullable(String), null],
                overscroll_behavior_block: [Nullable(String), null],
                overscroll_behavior_inline: [Nullable(String), null],
                overscroll_behavior_x: [Nullable(String), null],
                overscroll_behavior_y: [Nullable(String), null],
                padding: [Nullable(String), null],
                padding_block_end: [Nullable(String), null],
                padding_block_start: [Nullable(String), null],
                padding_bottom: [Nullable(String), null],
                padding_inline_end: [Nullable(String), null],
                padding_inline_start: [Nullable(String), null],
                padding_left: [Nullable(String), null],
                padding_right: [Nullable(String), null],
                padding_top: [Nullable(String), null],
                page_break_after: [Nullable(String), null],
                page_break_before: [Nullable(String), null],
                page_break_inside: [Nullable(String), null],
                paint_order: [Nullable(String), null],
                perspective: [Nullable(String), null],
                perspective_origin: [Nullable(String), null],
                place_content: [Nullable(String), null],
                place_items: [Nullable(String), null],
                place_self: [Nullable(String), null],
                pointer_events: [Nullable(String), null],
                position: [Nullable(String), null],
                quotes: [Nullable(String), null],
                resize: [Nullable(String), null],
                right: [Nullable(String), null],
                rotate: [Nullable(String), null],
                row_gap: [Nullable(String), null],
                ruby_align: [Nullable(String), null],
                ruby_position: [Nullable(String), null],
                scale: [Nullable(String), null],
                scroll_behavior: [Nullable(String), null],
                shape_rendering: [Nullable(String), null],
                stop_color: [Nullable(String), null],
                stop_opacity: [Nullable(String), null],
                stroke: [Nullable(String), null],
                stroke_dasharray: [Nullable(String), null],
                stroke_dashoffset: [Nullable(String), null],
                stroke_linecap: [Nullable(String), null],
                stroke_linejoin: [Nullable(String), null],
                stroke_miterlimit: [Nullable(String), null],
                stroke_opacity: [Nullable(String), null],
                stroke_width: [Nullable(String), null],
                tab_size: [Nullable(String), null],
                table_layout: [Nullable(String), null],
                text_align: [Nullable(String), null],
                text_align_last: [Nullable(String), null],
                text_anchor: [Nullable(String), null],
                text_combine_upright: [Nullable(String), null],
                text_decoration: [Nullable(String), null],
                text_decoration_color: [Nullable(String), null],
                text_decoration_line: [Nullable(String), null],
                text_decoration_style: [Nullable(String), null],
                text_emphasis: [Nullable(String), null],
                text_emphasis_color: [Nullable(String), null],
                text_emphasis_position: [Nullable(String), null],
                text_emphasis_style: [Nullable(String), null],
                text_indent: [Nullable(String), null],
                text_justify: [Nullable(String), null],
                text_orientation: [Nullable(String), null],
                text_overflow: [Nullable(String), null],
                text_rendering: [Nullable(String), null],
                text_shadow: [Nullable(String), null],
                text_transform: [Nullable(String), null],
                text_underline_position: [Nullable(String), null],
                top: [Nullable(String), null],
                touch_action: [Nullable(String), null],
                transform: [Nullable(String), null],
                transform_box: [Nullable(String), null],
                transform_origin: [Nullable(String), null],
                transform_style: [Nullable(String), null],
                transition: [Nullable(String), null],
                transition_delay: [Nullable(String), null],
                transition_duration: [Nullable(String), null],
                transition_property: [Nullable(String), null],
                transition_timing_function: [Nullable(String), null],
                translate: [Nullable(String), null],
                unicode_bidi: [Nullable(String), null],
                user_select: [Nullable(String), null],
                vertical_align: [Nullable(String), null],
                visibility: [Nullable(String), null],
                white_space: [Nullable(String), null],
                widows: [Nullable(String), null],
                width: [Nullable(String), null],
                will_change: [Nullable(String), null],
                word_break: [Nullable(String), null],
                word_spacing: [Nullable(String), null],
                word_wrap: [Nullable(String), null],
                writing_mode: [Nullable(String), null],
                z_index: [Nullable(String), null],
            });
        });
    })();
},
/* models/tools/tool_proxy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a;
    var signaling_1 = require(130) /* ../../core/signaling */;
    var model_1 = require(168) /* ../../model */;
    var button_tool_1 = require(339) /* ./button_tool */;
    var inspect_tool_1 = require(347) /* ./inspectors/inspect_tool */;
    var iterator_1 = require(349) /* ../../core/util/iterator */;
    var ToolProxy = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolProxy, _super);
        function ToolProxy(attrs) {
            return _super.call(this, attrs) || this;
        }
        Object.defineProperty(ToolProxy.prototype, "button_view", {
            // Operates all the tools given only one button
            get: function () {
                return this.tools[0].button_view;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ToolProxy.prototype, "event_type", {
            get: function () {
                return this.tools[0].event_type;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ToolProxy.prototype, "tooltip", {
            get: function () {
                return this.tools[0].tooltip;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ToolProxy.prototype, "tool_name", {
            get: function () {
                return this.tools[0].tool_name;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ToolProxy.prototype, "icon", {
            get: function () {
                return this.tools[0].computed_icon;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ToolProxy.prototype, "computed_icon", {
            get: function () {
                return this.icon;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(ToolProxy.prototype, "toggleable", {
            get: function () {
                var tool = this.tools[0];
                return tool instanceof inspect_tool_1.InspectTool && tool.toggleable;
            },
            enumerable: false,
            configurable: true
        });
        ToolProxy.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this.do = new signaling_1.Signal0(this, "do");
        };
        ToolProxy.prototype.connect_signals = function () {
            var e_1, _b;
            var _this = this;
            _super.prototype.connect_signals.call(this);
            this.connect(this.do, function () { return _this.doit(); });
            this.connect(this.properties.active.change, function () { return _this.set_active(); });
            var _loop_1 = function (tool) {
                this_1.connect(tool.properties.active.change, function () {
                    _this.active = tool.active;
                });
            };
            var this_1 = this;
            try {
                for (var _c = (0, tslib_1.__values)(this.tools), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var tool = _d.value;
                    _loop_1(tool);
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        };
        ToolProxy.prototype.doit = function () {
            var e_2, _b;
            try {
                for (var _c = (0, tslib_1.__values)(this.tools), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var tool = _d.value;
                    tool.do.emit();
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
        };
        ToolProxy.prototype.set_active = function () {
            var e_3, _b;
            try {
                for (var _c = (0, tslib_1.__values)(this.tools), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var tool = _d.value;
                    tool.active = this.active;
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_d && !_d.done && (_b = _c.return))
                        _b.call(_c);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
        };
        Object.defineProperty(ToolProxy.prototype, "menu", {
            get: function () {
                var e_4, _b;
                var _this = this;
                var menu = this.tools[0].menu;
                if (menu == null)
                    return null;
                var items = [];
                var _loop_2 = function (item, i) {
                    if (item == null)
                        items.push(null);
                    else {
                        var handler = function () {
                            var e_5, _b;
                            var _c, _d, _e;
                            try {
                                for (var _f = (e_5 = void 0, (0, tslib_1.__values)(_this.tools)), _g = _f.next(); !_g.done; _g = _f.next()) {
                                    var tool = _g.value;
                                    (_e = (_d = (_c = tool.menu) === null || _c === void 0 ? void 0 : _c[i]) === null || _d === void 0 ? void 0 : _d.handler) === null || _e === void 0 ? void 0 : _e.call(_d);
                                }
                            }
                            catch (e_5_1) {
                                e_5 = { error: e_5_1 };
                            }
                            finally {
                                try {
                                    if (_g && !_g.done && (_b = _f.return))
                                        _b.call(_f);
                                }
                                finally {
                                    if (e_5)
                                        throw e_5.error;
                                }
                            }
                        };
                        items.push((0, tslib_1.__assign)((0, tslib_1.__assign)({}, item), { handler: handler }));
                    }
                };
                try {
                    for (var _c = (0, tslib_1.__values)((0, iterator_1.enumerate)(menu)), _d = _c.next(); !_d.done; _d = _c.next()) {
                        var _e = (0, tslib_1.__read)(_d.value, 2), item = _e[0], i = _e[1];
                        _loop_2(item, i);
                    }
                }
                catch (e_4_1) {
                    e_4 = { error: e_4_1 };
                }
                finally {
                    try {
                        if (_d && !_d.done && (_b = _c.return))
                            _b.call(_c);
                    }
                    finally {
                        if (e_4)
                            throw e_4.error;
                    }
                }
                return items;
            },
            enumerable: false,
            configurable: true
        });
        return ToolProxy;
    }(model_1.Model));
    exports.ToolProxy = ToolProxy;
    _a = ToolProxy;
    ToolProxy.__name__ = "ToolProxy";
    (function () {
        _a.define(function (_b) {
            var Boolean = _b.Boolean, Array = _b.Array, Ref = _b.Ref;
            return ({
                tools: [Array(Ref(button_tool_1.ButtonTool)), []],
                active: [Boolean, false],
                disabled: [Boolean, false],
            });
        });
    })();
},
/* models/tools/toolbar_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var _a, _b;
    var enums_1 = require(135) /* ../../core/enums */;
    var array_1 = require(126) /* ../../core/util/array */;
    var object_1 = require(128) /* ../../core/util/object */;
    var toolbar_base_1 = require(348) /* ./toolbar_base */;
    var toolbar_1 = require(336) /* ./toolbar */;
    var tool_proxy_1 = require(509) /* ./tool_proxy */;
    var layout_dom_1 = require(424) /* ../layouts/layout_dom */;
    var layout_1 = require(322) /* ../../core/layout */;
    var ProxyToolbar = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ProxyToolbar, _super);
        function ProxyToolbar(attrs) {
            return _super.call(this, attrs) || this;
        }
        ProxyToolbar.prototype.initialize = function () {
            _super.prototype.initialize.call(this);
            this._merge_tools();
        };
        ProxyToolbar.prototype._merge_tools = function () {
            var e_1, _c, _d, e_2, _e, e_3, _f, e_4, _g, e_5, _h, e_6, _j, e_7, _k, e_8, _l, e_9, _m, e_10, _o, e_11, _p;
            var _this = this;
            // Go through all the tools on the toolbar and replace them with
            // a proxy e.g. PanTool, BoxSelectTool, etc.
            this._proxied_tools = [];
            var inspectors = {};
            var actions = {};
            var gestures = {};
            var new_help_tools = [];
            var new_help_urls = [];
            try {
                for (var _q = (0, tslib_1.__values)(this.help), _r = _q.next(); !_r.done; _r = _q.next()) {
                    var helptool = _r.value;
                    if (!(0, array_1.includes)(new_help_urls, helptool.redirect)) {
                        new_help_tools.push(helptool);
                        new_help_urls.push(helptool.redirect);
                    }
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_r && !_r.done && (_c = _q.return))
                        _c.call(_q);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
            (_d = this._proxied_tools).push.apply(_d, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(new_help_tools), false));
            this.help = new_help_tools;
            try {
                for (var _s = (0, tslib_1.__values)((0, object_1.entries)(this.gestures)), _t = _s.next(); !_t.done; _t = _s.next()) {
                    var _u = (0, tslib_1.__read)(_t.value, 2), event_type = _u[0], gesture = _u[1];
                    if (!(event_type in gestures)) {
                        gestures[event_type] = {};
                    }
                    try {
                        for (var _v = (e_3 = void 0, (0, tslib_1.__values)(gesture.tools)), _w = _v.next(); !_w.done; _w = _v.next()) {
                            var tool = _w.value;
                            if (!(tool.type in gestures[event_type])) {
                                gestures[event_type][tool.type] = [];
                            }
                            gestures[event_type][tool.type].push(tool);
                        }
                    }
                    catch (e_3_1) {
                        e_3 = { error: e_3_1 };
                    }
                    finally {
                        try {
                            if (_w && !_w.done && (_f = _v.return))
                                _f.call(_v);
                        }
                        finally {
                            if (e_3)
                                throw e_3.error;
                        }
                    }
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_t && !_t.done && (_e = _s.return))
                        _e.call(_s);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            try {
                for (var _x = (0, tslib_1.__values)(this.inspectors), _y = _x.next(); !_y.done; _y = _x.next()) {
                    var tool = _y.value;
                    if (!(tool.type in inspectors)) {
                        inspectors[tool.type] = [];
                    }
                    inspectors[tool.type].push(tool);
                }
            }
            catch (e_4_1) {
                e_4 = { error: e_4_1 };
            }
            finally {
                try {
                    if (_y && !_y.done && (_g = _x.return))
                        _g.call(_x);
                }
                finally {
                    if (e_4)
                        throw e_4.error;
                }
            }
            try {
                for (var _z = (0, tslib_1.__values)(this.actions), _0 = _z.next(); !_0.done; _0 = _z.next()) {
                    var tool = _0.value;
                    if (!(tool.type in actions)) {
                        actions[tool.type] = [];
                    }
                    actions[tool.type].push(tool);
                }
            }
            catch (e_5_1) {
                e_5 = { error: e_5_1 };
            }
            finally {
                try {
                    if (_0 && !_0.done && (_h = _z.return))
                        _h.call(_z);
                }
                finally {
                    if (e_5)
                        throw e_5.error;
                }
            }
            // Add a proxy for each of the groups of tools.
            var make_proxy = function (tools, active) {
                if (active === void 0) {
                    active = false;
                }
                var proxy = new tool_proxy_1.ToolProxy({ tools: tools, active: active });
                _this._proxied_tools.push(proxy);
                return proxy;
            };
            try {
                for (var _1 = (0, tslib_1.__values)((0, object_1.keys)(gestures)), _2 = _1.next(); !_2.done; _2 = _1.next()) {
                    var event_type = _2.value;
                    var gesture = this.gestures[event_type];
                    gesture.tools = [];
                    var _loop_1 = function (tool_type) {
                        var e_12, _13;
                        var tools = gestures[event_type][tool_type];
                        if (tools.length > 0) {
                            if (event_type == "multi") {
                                var _loop_2 = function (tool) {
                                    var proxy = make_proxy([tool]);
                                    gesture.tools.push(proxy);
                                    this_1.connect(proxy.properties.active.change, function () { return _this._active_change(proxy); });
                                };
                                try {
                                    for (var tools_2 = (e_12 = void 0, (0, tslib_1.__values)(tools)), tools_2_1 = tools_2.next(); !tools_2_1.done; tools_2_1 = tools_2.next()) {
                                        var tool = tools_2_1.value;
                                        _loop_2(tool);
                                    }
                                }
                                catch (e_12_1) {
                                    e_12 = { error: e_12_1 };
                                }
                                finally {
                                    try {
                                        if (tools_2_1 && !tools_2_1.done && (_13 = tools_2.return))
                                            _13.call(tools_2);
                                    }
                                    finally {
                                        if (e_12)
                                            throw e_12.error;
                                    }
                                }
                            }
                            else {
                                var proxy_1 = make_proxy(tools);
                                gesture.tools.push(proxy_1);
                                this_1.connect(proxy_1.properties.active.change, function () { return _this._active_change(proxy_1); });
                            }
                        }
                    };
                    var this_1 = this;
                    try {
                        for (var _3 = (e_7 = void 0, (0, tslib_1.__values)((0, object_1.keys)(gestures[event_type]))), _4 = _3.next(); !_4.done; _4 = _3.next()) {
                            var tool_type = _4.value;
                            _loop_1(tool_type);
                        }
                    }
                    catch (e_7_1) {
                        e_7 = { error: e_7_1 };
                    }
                    finally {
                        try {
                            if (_4 && !_4.done && (_k = _3.return))
                                _k.call(_3);
                        }
                        finally {
                            if (e_7)
                                throw e_7.error;
                        }
                    }
                }
            }
            catch (e_6_1) {
                e_6 = { error: e_6_1 };
            }
            finally {
                try {
                    if (_2 && !_2.done && (_j = _1.return))
                        _j.call(_1);
                }
                finally {
                    if (e_6)
                        throw e_6.error;
                }
            }
            this.actions = [];
            try {
                for (var _5 = (0, tslib_1.__values)((0, object_1.entries)(actions)), _6 = _5.next(); !_6.done; _6 = _5.next()) {
                    var _7 = (0, tslib_1.__read)(_6.value, 2), tool_type = _7[0], tools = _7[1];
                    if (tool_type == "CustomAction") {
                        try {
                            for (var tools_1 = (e_9 = void 0, (0, tslib_1.__values)(tools)), tools_1_1 = tools_1.next(); !tools_1_1.done; tools_1_1 = tools_1.next()) {
                                var tool = tools_1_1.value;
                                this.actions.push(make_proxy([tool]));
                            }
                        }
                        catch (e_9_1) {
                            e_9 = { error: e_9_1 };
                        }
                        finally {
                            try {
                                if (tools_1_1 && !tools_1_1.done && (_m = tools_1.return))
                                    _m.call(tools_1);
                            }
                            finally {
                                if (e_9)
                                    throw e_9.error;
                            }
                        }
                    }
                    else if (tools.length > 0) {
                        this.actions.push(make_proxy(tools)); // XXX
                    }
                }
            }
            catch (e_8_1) {
                e_8 = { error: e_8_1 };
            }
            finally {
                try {
                    if (_6 && !_6.done && (_l = _5.return))
                        _l.call(_5);
                }
                finally {
                    if (e_8)
                        throw e_8.error;
                }
            }
            this.inspectors = [];
            try {
                for (var _8 = (0, tslib_1.__values)((0, object_1.values)(inspectors)), _9 = _8.next(); !_9.done; _9 = _8.next()) {
                    var tools = _9.value;
                    if (tools.length > 0)
                        this.inspectors.push(make_proxy(tools, true)); // XXX
                }
            }
            catch (e_10_1) {
                e_10 = { error: e_10_1 };
            }
            finally {
                try {
                    if (_9 && !_9.done && (_o = _8.return))
                        _o.call(_8);
                }
                finally {
                    if (e_10)
                        throw e_10.error;
                }
            }
            try {
                for (var _10 = (0, tslib_1.__values)((0, object_1.entries)(this.gestures)), _11 = _10.next(); !_11.done; _11 = _10.next()) {
                    var _12 = (0, tslib_1.__read)(_11.value, 2), et = _12[0], gesture = _12[1];
                    if (gesture.tools.length == 0)
                        continue;
                    gesture.tools = (0, array_1.sort_by)(gesture.tools, function (tool) { return tool.default_order; });
                    if (!(et == "pinch" || et == "scroll" || et == "multi"))
                        gesture.tools[0].active = true;
                }
            }
            catch (e_11_1) {
                e_11 = { error: e_11_1 };
            }
            finally {
                try {
                    if (_11 && !_11.done && (_p = _10.return))
                        _p.call(_10);
                }
                finally {
                    if (e_11)
                        throw e_11.error;
                }
            }
        };
        return ProxyToolbar;
    }(toolbar_base_1.ToolbarBase));
    exports.ProxyToolbar = ProxyToolbar;
    _a = ProxyToolbar;
    ProxyToolbar.__name__ = "ProxyToolbar";
    (function () {
        _a.define(function (_c) {
            var Array = _c.Array, Ref = _c.Ref;
            return ({
                toolbars: [Array(Ref(toolbar_1.Toolbar)), []],
            });
        });
    })();
    var ToolbarBoxView = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolbarBoxView, _super);
        function ToolbarBoxView() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        ToolbarBoxView.prototype.initialize = function () {
            this.model.toolbar.toolbar_location = this.model.toolbar_location;
            _super.prototype.initialize.call(this);
        };
        Object.defineProperty(ToolbarBoxView.prototype, "child_models", {
            get: function () {
                return [this.model.toolbar]; // XXX
            },
            enumerable: false,
            configurable: true
        });
        ToolbarBoxView.prototype._update_layout = function () {
            this.layout = new layout_1.ContentBox(this.child_views[0].el);
            var toolbar = this.model.toolbar;
            if (toolbar.horizontal) {
                this.layout.set_sizing({
                    width_policy: "fit", min_width: 100, height_policy: "fixed",
                });
            }
            else {
                this.layout.set_sizing({
                    width_policy: "fixed", height_policy: "fit", min_height: 100,
                });
            }
        };
        ToolbarBoxView.prototype.after_layout = function () {
            _super.prototype.after_layout.call(this);
            var toolbar_view = this.child_views[0];
            toolbar_view.layout.bbox = this.layout.bbox;
            toolbar_view.render(); // render the second time to revise overflow
        };
        return ToolbarBoxView;
    }(layout_dom_1.LayoutDOMView));
    exports.ToolbarBoxView = ToolbarBoxView;
    ToolbarBoxView.__name__ = "ToolbarBoxView";
    var ToolbarBox = /** @class */ (function (_super) {
        (0, tslib_1.__extends)(ToolbarBox, _super);
        function ToolbarBox(attrs) {
            return _super.call(this, attrs) || this;
        }
        return ToolbarBox;
    }(layout_dom_1.LayoutDOM));
    exports.ToolbarBox = ToolbarBox;
    _b = ToolbarBox;
    ToolbarBox.__name__ = "ToolbarBox";
    (function () {
        _b.prototype.default_view = ToolbarBoxView;
        _b.define(function (_c) {
            var Ref = _c.Ref;
            return ({
                toolbar: [Ref(toolbar_base_1.ToolbarBase)],
                toolbar_location: [enums_1.Location, "right"],
            });
        });
    })();
},
/* document/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var model_1 = require(168) /* ../model */;
    var kinds = (0, tslib_1.__importStar)(require(136) /* ../core/kinds */);
    var types_1 = require(125) /* ../core/util/types */;
    var object_1 = require(128) /* ../core/util/object */;
    function resolve_defs(defs, resolver) {
        var e_1, _b;
        var _c, _d, _e;
        var _a;
        function qualified(ref) {
            return ref.module != null ? ref.module + "." + ref.name : ref.name;
        }
        function kind_of(ref) {
            if ((0, types_1.isString)(ref)) {
                switch (ref) {
                    case "Any": return kinds.Any;
                    case "Unknown": return kinds.Unknown;
                    case "Boolean": return kinds.Boolean;
                    case "Number": return kinds.Number;
                    case "Int": return kinds.Int;
                    case "String": return kinds.String;
                    case "Null": return kinds.Null;
                }
            }
            else {
                switch (ref[0]) {
                    case "Nullable": {
                        var _b = (0, tslib_1.__read)(ref, 2), subref = _b[1];
                        return kinds.Nullable(kind_of(subref));
                    }
                    case "Or": {
                        var _c = (0, tslib_1.__read)(ref), subrefs = _c.slice(1);
                        return kinds.Or.apply(kinds, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(subrefs.map(kind_of)), false));
                    }
                    case "Tuple": {
                        var _d = (0, tslib_1.__read)(ref), subref = _d[1], subrefs = _d.slice(2);
                        return kinds.Tuple.apply(kinds, (0, tslib_1.__spreadArray)([kind_of(subref)], (0, tslib_1.__read)(subrefs.map(kind_of)), false));
                    }
                    case "Array": {
                        var _e = (0, tslib_1.__read)(ref, 2), subref = _e[1];
                        return kinds.Array(kind_of(subref));
                    }
                    case "Struct": {
                        var _f = (0, tslib_1.__read)(ref), entryrefs = _f.slice(1);
                        var entries = entryrefs.map(function (_b) {
                            var _c = (0, tslib_1.__read)(_b, 2), key = _c[0], valref = _c[1];
                            return [key, kind_of(valref)];
                        });
                        return kinds.Struct((0, object_1.to_object)(entries));
                    }
                    case "Dict": {
                        var _g = (0, tslib_1.__read)(ref, 2), valref = _g[1];
                        return kinds.Dict(kind_of(valref));
                    }
                    case "Map": {
                        var _h = (0, tslib_1.__read)(ref, 3), keyref = _h[1], valref = _h[2];
                        return kinds.Map(kind_of(keyref), kind_of(valref));
                    }
                    case "Enum": {
                        var _j = (0, tslib_1.__read)(ref), items = _j.slice(1);
                        return kinds.Enum.apply(kinds, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(items), false));
                    }
                    case "Ref": {
                        var _k = (0, tslib_1.__read)(ref, 2), modelref = _k[1];
                        var model = resolver.get(qualified(modelref));
                        if (model != null)
                            return kinds.Ref(model);
                        else
                            throw new Error(qualified(modelref) + " wasn't defined before referencing it");
                    }
                    case "AnyRef": {
                        return kinds.AnyRef();
                    }
                }
            }
        }
        var _loop_1 = function (def) {
            var e_2, _f, _g, e_3, _h, _j;
            var base = (function () {
                if (def.extends == null)
                    return model_1.Model;
                else {
                    var base_1 = resolver.get(qualified(def.extends));
                    if (base_1 != null)
                        return base_1;
                    else
                        throw new Error("base model " + qualified(def.extends) + " of " + qualified(def) + " is not defined");
                }
            })();
            var model = (_a = /** @class */ (function (_super) {
                (0, tslib_1.__extends)(_a, _super);
                function _a() {
                    return _super !== null && _super.apply(this, arguments) || this;
                }
                return _a;
            }(base)),
                _a.__name__ = def.name,
                _a.__module__ = def.module,
                _a);
            try {
                for (var _k = (e_2 = void 0, (0, tslib_1.__values)((_c = def.properties) !== null && _c !== void 0 ? _c : [])), _l = _k.next(); !_l.done; _l = _k.next()) {
                    var prop = _l.value;
                    var kind = kind_of((_d = prop.kind) !== null && _d !== void 0 ? _d : "Unknown");
                    model.define((_g = {}, _g[prop.name] = [kind, prop.default], _g));
                }
            }
            catch (e_2_1) {
                e_2 = { error: e_2_1 };
            }
            finally {
                try {
                    if (_l && !_l.done && (_f = _k.return))
                        _f.call(_k);
                }
                finally {
                    if (e_2)
                        throw e_2.error;
                }
            }
            try {
                for (var _m = (e_3 = void 0, (0, tslib_1.__values)((_e = def.overrides) !== null && _e !== void 0 ? _e : [])), _o = _m.next(); !_o.done; _o = _m.next()) {
                    var prop = _o.value;
                    model.override((_j = {}, _j[prop.name] = prop.default, _j));
                }
            }
            catch (e_3_1) {
                e_3 = { error: e_3_1 };
            }
            finally {
                try {
                    if (_o && !_o.done && (_h = _m.return))
                        _h.call(_m);
                }
                finally {
                    if (e_3)
                        throw e_3.error;
                }
            }
            resolver.register(model);
        };
        try {
            for (var defs_1 = (0, tslib_1.__values)(defs), defs_1_1 = defs_1.next(); !defs_1_1.done; defs_1_1 = defs_1.next()) {
                var def = defs_1_1.value;
                _loop_1(def);
            }
        }
        catch (e_1_1) {
            e_1 = { error: e_1_1 };
        }
        finally {
            try {
                if (defs_1_1 && !defs_1_1.done && (_b = defs_1.return))
                    _b.call(defs_1);
            }
            finally {
                if (e_1)
                    throw e_1.error;
            }
        }
    }
    exports.resolve_defs = resolve_defs;
},
/* embed/standalone.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var document_1 = require(122) /* ../document */;
    var dom_view_1 = require(341) /* ../core/dom_view */;
    var build_views_1 = require(228) /* ../core/build_views */;
    var dom_1 = require(158) /* ../core/dom */;
    var dom_2 = require(513) /* ./dom */;
    // A map from the root model IDs to their views.
    exports.index = {};
    function add_document_standalone(document, element, roots, use_for_title) {
        if (roots === void 0) {
            roots = [];
        }
        if (use_for_title === void 0) {
            use_for_title = false;
        }
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            function render_model(model) {
                return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                    var root_el, root_models, idx, root, view;
                    return (0, tslib_1.__generator)(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                root_models = document.roots();
                                idx = root_models.indexOf(model);
                                root = roots[idx];
                                if (root != null)
                                    root_el = root;
                                else if (element.classList.contains(dom_2.BOKEH_ROOT))
                                    root_el = element;
                                else {
                                    root_el = (0, dom_1.div)({ class: dom_2.BOKEH_ROOT });
                                    element.appendChild(root_el);
                                }
                                return [4 /*yield*/, (0, build_views_1.build_view)(model, { parent: null })];
                            case 1:
                                view = _a.sent();
                                if (view instanceof dom_view_1.DOMView)
                                    view.renderTo(root_el);
                                views.set(model, view);
                                exports.index[model.id] = view;
                                return [2 /*return*/, view];
                        }
                    });
                });
            }
            function unrender_model(model) {
                var view = views.get(model);
                if (view != null) {
                    view.remove();
                    views.delete(model);
                    delete exports.index[model.id];
                }
            }
            var views, _a, _b, model, e_1_1;
            var e_1, _c;
            return (0, tslib_1.__generator)(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        views = new Map();
                        _d.label = 1;
                    case 1:
                        _d.trys.push([1, 6, 7, 8]);
                        _a = (0, tslib_1.__values)(document.roots()), _b = _a.next();
                        _d.label = 2;
                    case 2:
                        if (!!_b.done)
                            return [3 /*break*/, 5];
                        model = _b.value;
                        return [4 /*yield*/, render_model(model)];
                    case 3:
                        _d.sent();
                        _d.label = 4;
                    case 4:
                        _b = _a.next();
                        return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 8];
                    case 6:
                        e_1_1 = _d.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 8];
                    case 7:
                        try {
                            if (_b && !_b.done && (_c = _a.return))
                                _c.call(_a);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                        return [7 /*endfinally*/];
                    case 8:
                        if (use_for_title)
                            window.document.title = document.title();
                        document.on_change(function (event) {
                            if (event instanceof document_1.RootAddedEvent)
                                render_model(event.model);
                            else if (event instanceof document_1.RootRemovedEvent)
                                unrender_model(event.model);
                            else if (use_for_title && event instanceof document_1.TitleChangedEvent)
                                window.document.title = event.title;
                        });
                        return [2 /*return*/, (0, tslib_1.__spreadArray)([], (0, tslib_1.__read)(views.values()), false)];
                }
            });
        });
    }
    exports.add_document_standalone = add_document_standalone;
},
/* embed/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var dom_1 = require(158) /* ../core/dom */;
    var root_css_1 = require(159) /* ../styles/root.css */;
    // Matches Bokeh CSS class selector. Setting all Bokeh parent element class names
    // with this var prevents user configurations where css styling is unset.
    exports.BOKEH_ROOT = root_css_1.root;
    function _get_element(elementid) {
        var element = document.getElementById(elementid);
        if (element == null)
            throw new Error("Error rendering Bokeh model: could not find #" + elementid + " HTML tag");
        if (!document.body.contains(element))
            throw new Error("Error rendering Bokeh model: element #" + elementid + " must be under <body>");
        // If autoload script, replace script tag with div for embedding.
        if (element.tagName == "SCRIPT") {
            var root_el = (0, dom_1.div)({ class: exports.BOKEH_ROOT });
            (0, dom_1.replaceWith)(element, root_el);
            element = root_el;
        }
        return element;
    }
    function _resolve_element(item) {
        var elementid = item.elementid;
        if (elementid != null)
            return _get_element(elementid);
        else
            return document.body;
    }
    exports._resolve_element = _resolve_element;
    function _resolve_root_elements(item) {
        var e_1, _a;
        var roots = [];
        if ((item.root_ids != null) && (item.roots != null)) {
            try {
                for (var _b = (0, tslib_1.__values)(item.root_ids), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var root_id = _c.value;
                    roots.push(_get_element(item.roots[root_id]));
                }
            }
            catch (e_1_1) {
                e_1 = { error: e_1_1 };
            }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return))
                        _a.call(_b);
                }
                finally {
                    if (e_1)
                        throw e_1.error;
                }
            }
        }
        return roots;
    }
    exports._resolve_root_elements = _resolve_root_elements;
},
/* embed/server.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var connection_1 = require(515) /* ../client/connection */;
    var logging_1 = require(134) /* ../core/logging */;
    var standalone_1 = require(512) /* ./standalone */;
    // @internal
    function _get_ws_url(app_path, absolute_url) {
        var protocol = "ws:";
        if (window.location.protocol == "https:")
            protocol = "wss:";
        var loc;
        if (absolute_url != null) {
            loc = document.createElement("a");
            loc.href = absolute_url;
        }
        else
            loc = window.location;
        if (app_path != null) {
            if (app_path == "/")
                app_path = "";
        }
        else
            app_path = loc.pathname.replace(/\/+$/, "");
        return protocol + "//" + loc.host + app_path + "/ws";
    }
    exports._get_ws_url = _get_ws_url;
    // map { websocket url to map { session id to promise of ClientSession } }
    var _sessions = {};
    function _get_session(websocket_url, token, args_string) {
        var session_id = (0, connection_1.parse_token)(token).session_id;
        if (!(websocket_url in _sessions))
            _sessions[websocket_url] = {};
        var subsessions = _sessions[websocket_url];
        if (!(session_id in subsessions))
            subsessions[session_id] = (0, connection_1.pull_session)(websocket_url, token, args_string);
        return subsessions[session_id];
    }
    // Fill element with the roots from token
    function add_document_from_session(websocket_url, token, element, roots, use_for_title) {
        if (roots === void 0) {
            roots = [];
        }
        if (use_for_title === void 0) {
            use_for_title = false;
        }
        return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
            var args_string, session, error_1, session_id;
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        args_string = window.location.search.substr(1);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, _get_session(websocket_url, token, args_string)];
                    case 2:
                        session = _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        error_1 = _a.sent();
                        session_id = (0, connection_1.parse_token)(token).session_id;
                        logging_1.logger.error("Failed to load Bokeh session " + session_id + ": " + error_1);
                        throw error_1;
                    case 4: return [2 /*return*/, (0, standalone_1.add_document_standalone)(session.document, element, roots, use_for_title)];
                }
            });
        });
    }
    exports.add_document_from_session = add_document_from_session;
},
/* client/connection.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var logging_1 = require(134) /* ../core/logging */;
    var document_1 = require(122) /* ../document */;
    var message_1 = require(516) /* ../protocol/message */;
    var receiver_1 = require(517) /* ../protocol/receiver */;
    var session_1 = require(518) /* ./session */;
    exports.DEFAULT_SERVER_WEBSOCKET_URL = "ws://localhost:5006/ws";
    exports.DEFAULT_TOKEN = "eyJzZXNzaW9uX2lkIjogImRlZmF1bHQifQ";
    var _connection_count = 0;
    function parse_token(token) {
        var payload = token.split(".")[0];
        var mod = payload.length % 4;
        if (mod != 0)
            payload = payload + "=".repeat(4 - mod);
        return JSON.parse(atob(payload.replace(/_/g, "/").replace(/-/g, "+")));
    }
    exports.parse_token = parse_token;
    var ClientConnection = /** @class */ (function () {
        function ClientConnection(url, token, args_string) {
            if (url === void 0) {
                url = exports.DEFAULT_SERVER_WEBSOCKET_URL;
            }
            if (token === void 0) {
                token = exports.DEFAULT_TOKEN;
            }
            if (args_string === void 0) {
                args_string = null;
            }
            this.url = url;
            this.token = token;
            this.args_string = args_string;
            this._number = _connection_count++;
            this.socket = null;
            this.session = null;
            this.closed_permanently = false;
            this._current_handler = null;
            this._pending_replies = new Map();
            this._pending_messages = [];
            this._receiver = new receiver_1.Receiver();
            this.id = parse_token(token).session_id.split(".")[0];
            logging_1.logger.debug("Creating websocket " + this._number + " to '" + this.url + "' session '" + this.id + "'");
        }
        ClientConnection.prototype.connect = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var versioned_url;
                var _this = this;
                return (0, tslib_1.__generator)(this, function (_a) {
                    if (this.closed_permanently)
                        throw new Error("Cannot connect() a closed ClientConnection");
                    if (this.socket != null)
                        throw new Error("Already connected");
                    this._current_handler = null;
                    this._pending_replies.clear();
                    this._pending_messages = [];
                    try {
                        versioned_url = "" + this.url;
                        if (this.args_string != null && this.args_string.length > 0)
                            versioned_url += "?" + this.args_string;
                        this.socket = new WebSocket(versioned_url, ["bokeh", this.token]);
                        return [2 /*return*/, new Promise(function (resolve, reject) {
                                // "arraybuffer" gives us binary data we can look at;
                                // if we just needed an opaque blob we could use "blob"
                                _this.socket.binaryType = "arraybuffer";
                                _this.socket.onopen = function () { return _this._on_open(resolve, reject); };
                                _this.socket.onmessage = function (event) { return _this._on_message(event); };
                                _this.socket.onclose = function (event) { return _this._on_close(event, reject); };
                                _this.socket.onerror = function () { return _this._on_error(reject); };
                            })];
                    }
                    catch (error) {
                        logging_1.logger.error("websocket creation failed to url: " + this.url);
                        logging_1.logger.error(" - " + error);
                        throw error;
                    }
                    return [2 /*return*/];
                });
            });
        };
        ClientConnection.prototype.close = function () {
            if (!this.closed_permanently) {
                logging_1.logger.debug("Permanently closing websocket connection " + this._number);
                this.closed_permanently = true;
                if (this.socket != null)
                    this.socket.close(1000, "close method called on ClientConnection " + this._number);
                this.session._connection_closed();
            }
        };
        ClientConnection.prototype._schedule_reconnect = function (milliseconds) {
            var _this = this;
            var retry = function () {
                // TODO commented code below until we fix reconnection to repull
                // the document when required. Otherwise, we get a lot of
                // confusing errors that are causing trouble when debugging.
                /*
                if (this.closed_permanently) {
                */
                if (!_this.closed_permanently)
                    logging_1.logger.info("Websocket connection " + _this._number + " disconnected, will not attempt to reconnect");
                return;
                /*
                } else {
                  logger.debug(`Attempting to reconnect websocket ${this._number}`)
                  this.connect()
                }
                */
            };
            setTimeout(retry, milliseconds);
        };
        ClientConnection.prototype.send = function (message) {
            if (this.socket == null)
                throw new Error("not connected so cannot send " + message);
            message.send(this.socket);
        };
        ClientConnection.prototype.send_with_reply = function (message) {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var reply;
                var _this = this;
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, new Promise(function (resolve, reject) {
                                _this._pending_replies.set(message.msgid(), { resolve: resolve, reject: reject });
                                _this.send(message);
                            })];
                        case 1:
                            reply = _a.sent();
                            if (reply.msgtype() === "ERROR")
                                throw new Error("Error reply " + reply.content.text);
                            else
                                return [2 /*return*/, reply];
                            return [2 /*return*/];
                    }
                });
            });
        };
        ClientConnection.prototype._pull_doc_json = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var message, reply;
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            message = message_1.Message.create("PULL-DOC-REQ", {});
                            return [4 /*yield*/, this.send_with_reply(message)];
                        case 1:
                            reply = _a.sent();
                            if (!("doc" in reply.content))
                                throw new Error("No 'doc' field in PULL-DOC-REPLY");
                            return [2 /*return*/, reply.content.doc];
                    }
                });
            });
        };
        ClientConnection.prototype._repull_session_doc = function (resolve, reject) {
            var _a;
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var doc_json, document, patch, patch_message, _b, _c, msg, error_1;
                var e_1, _d;
                return (0, tslib_1.__generator)(this, function (_e) {
                    switch (_e.label) {
                        case 0:
                            logging_1.logger.debug(this.session ? "Repulling session" : "Pulling session for first time");
                            _e.label = 1;
                        case 1:
                            _e.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, this._pull_doc_json()];
                        case 2:
                            doc_json = _e.sent();
                            if (this.session == null) {
                                if (this.closed_permanently) {
                                    logging_1.logger.debug("Got new document after connection was already closed");
                                    reject(new Error("The connection has been closed"));
                                }
                                else {
                                    document = document_1.Document.from_json(doc_json);
                                    patch = document_1.Document._compute_patch_since_json(doc_json, document);
                                    if (patch.events.length > 0) {
                                        logging_1.logger.debug("Sending " + patch.events.length + " changes from model construction back to server");
                                        patch_message = message_1.Message.create("PATCH-DOC", {}, patch);
                                        this.send(patch_message);
                                    }
                                    this.session = new session_1.ClientSession(this, document, this.id);
                                    try {
                                        for (_b = (0, tslib_1.__values)(this._pending_messages), _c = _b.next(); !_c.done; _c = _b.next()) {
                                            msg = _c.value;
                                            this.session.handle(msg);
                                        }
                                    }
                                    catch (e_1_1) {
                                        e_1 = { error: e_1_1 };
                                    }
                                    finally {
                                        try {
                                            if (_c && !_c.done && (_d = _b.return))
                                                _d.call(_b);
                                        }
                                        finally {
                                            if (e_1)
                                                throw e_1.error;
                                        }
                                    }
                                    this._pending_messages = [];
                                    logging_1.logger.debug("Created a new session from new pulled doc");
                                    resolve(this.session);
                                }
                            }
                            else {
                                this.session.document.replace_with_json(doc_json);
                                logging_1.logger.debug("Updated existing session with new pulled doc");
                                // Since the session already exists, we don't need to call `resolve` again.
                            }
                            return [3 /*break*/, 4];
                        case 3:
                            error_1 = _e.sent();
                            (_a = console.trace) === null || _a === void 0 ? void 0 : _a.call(console, error_1);
                            logging_1.logger.error("Failed to repull session " + error_1);
                            reject(error_1 instanceof Error ? error_1 : "" + error_1);
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        ClientConnection.prototype._on_open = function (resolve, reject) {
            var _this = this;
            logging_1.logger.info("Websocket connection " + this._number + " is now open");
            this._current_handler = function (message) {
                _this._awaiting_ack_handler(message, resolve, reject);
            };
        };
        ClientConnection.prototype._on_message = function (event) {
            if (this._current_handler == null)
                logging_1.logger.error("Got a message with no current handler set");
            try {
                this._receiver.consume(event.data);
            }
            catch (e) {
                this._close_bad_protocol("" + e);
            }
            var msg = this._receiver.message;
            if (msg != null) {
                var problem = msg.problem();
                if (problem != null)
                    this._close_bad_protocol(problem);
                this._current_handler(msg);
            }
        };
        ClientConnection.prototype._on_close = function (event, reject) {
            logging_1.logger.info("Lost websocket " + this._number + " connection, " + event.code + " (" + event.reason + ")");
            this.socket = null;
            this._pending_replies.forEach(function (pr) { return pr.reject("Disconnected"); });
            this._pending_replies.clear();
            if (!this.closed_permanently)
                this._schedule_reconnect(2000);
            reject(new Error("Lost websocket connection, " + event.code + " (" + event.reason + ")"));
        };
        ClientConnection.prototype._on_error = function (reject) {
            logging_1.logger.debug("Websocket error on socket " + this._number);
            var msg = "Could not open websocket";
            logging_1.logger.error("Failed to connect to Bokeh server: " + msg);
            reject(new Error(msg));
        };
        ClientConnection.prototype._close_bad_protocol = function (detail) {
            logging_1.logger.error("Closing connection: " + detail);
            if (this.socket != null)
                this.socket.close(1002, detail); // 1002 = protocol error
        };
        ClientConnection.prototype._awaiting_ack_handler = function (message, resolve, reject) {
            var _this = this;
            if (message.msgtype() === "ACK") {
                this._current_handler = function (message) { return _this._steady_state_handler(message); };
                // Reload any sessions
                this._repull_session_doc(resolve, reject);
            }
            else
                this._close_bad_protocol("First message was not an ACK");
        };
        ClientConnection.prototype._steady_state_handler = function (message) {
            var reqid = message.reqid();
            var pr = this._pending_replies.get(reqid);
            if (pr) {
                this._pending_replies.delete(reqid);
                pr.resolve(message);
            }
            else if (this.session) {
                this.session.handle(message);
            }
            else if (message.msgtype() != "PATCH-DOC") {
                // This branch can be executed only before we get the document.
                // When we get the document, all of the patches will already be incorporated.
                // In general, it's not possible to apply patches received before the document,
                // since they may change some models that were removed before serving the document.
                this._pending_messages.push(message);
            }
        };
        return ClientConnection;
    }());
    exports.ClientConnection = ClientConnection;
    ClientConnection.__name__ = "ClientConnection";
    function pull_session(url, token, args_string) {
        var connection = new ClientConnection(url, token, args_string);
        return connection.connect();
    }
    exports.pull_session = pull_session;
},
/* protocol/message.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var string_1 = require(149) /* ../core/util/string */;
    var Message = /** @class */ (function () {
        function Message(header, metadata, content) {
            this.header = header;
            this.metadata = metadata;
            this.content = content;
            this.buffers = new Map();
        }
        Message.assemble = function (header_json, metadata_json, content_json) {
            var header = JSON.parse(header_json);
            var metadata = JSON.parse(metadata_json);
            var content = JSON.parse(content_json);
            return new Message(header, metadata, content);
        };
        Message.prototype.assemble_buffer = function (buf_header, buf_payload) {
            var nb = this.header.num_buffers != null ? this.header.num_buffers : 0;
            if (nb <= this.buffers.size)
                throw new Error("too many buffers received, expecting " + nb);
            var id = JSON.parse(buf_header).id;
            this.buffers.set(id, buf_payload);
        };
        // not defined for BokehJS, only *receiving* buffers is supported
        // add_buffer: (buf_header, buf_payload) ->
        // write_buffers: (socket)
        Message.create = function (msgtype, metadata, content) {
            if (content === void 0) {
                content = {};
            }
            var header = Message.create_header(msgtype);
            return new Message(header, metadata, content);
        };
        Message.create_header = function (msgtype) {
            return {
                msgid: (0, string_1.uniqueId)(),
                msgtype: msgtype,
            };
        };
        Message.prototype.complete = function () {
            if (this.header != null && this.metadata != null && this.content != null) {
                if (this.header.num_buffers != undefined)
                    return this.buffers.size == this.header.num_buffers;
                else
                    return true;
            }
            else
                return false;
        };
        Message.prototype.send = function (socket) {
            var nb = this.header.num_buffers != null ? this.header.num_buffers : 0;
            if (nb > 0)
                throw new Error("BokehJS only supports receiving buffers, not sending");
            var header_json = JSON.stringify(this.header);
            var metadata_json = JSON.stringify(this.metadata);
            var content_json = JSON.stringify(this.content);
            socket.send(header_json);
            socket.send(metadata_json);
            socket.send(content_json);
        };
        Message.prototype.msgid = function () {
            return this.header.msgid;
        };
        Message.prototype.msgtype = function () {
            return this.header.msgtype;
        };
        Message.prototype.reqid = function () {
            return this.header.reqid;
        };
        // return the reason we should close on bad protocol, if there is one
        Message.prototype.problem = function () {
            if (!("msgid" in this.header))
                return "No msgid in header";
            else if (!("msgtype" in this.header))
                return "No msgtype in header";
            else
                return null;
        };
        return Message;
    }());
    exports.Message = Message;
    Message.__name__ = "Message";
},
/* protocol/receiver.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var message_1 = require(516) /* ./message */;
    var types_1 = require(125) /* ../core/util/types */;
    var Receiver = /** @class */ (function () {
        function Receiver() {
            this.message = null;
            this._partial = null;
            this._fragments = [];
            this._buf_header = null;
            this._current_consumer = this._HEADER;
        }
        Receiver.prototype.consume = function (fragment) {
            this._current_consumer(fragment);
        };
        Receiver.prototype._HEADER = function (fragment) {
            this._assume_text(fragment);
            this.message = null;
            this._partial = null;
            this._fragments = [fragment];
            this._buf_header = null;
            this._current_consumer = this._METADATA;
        };
        Receiver.prototype._METADATA = function (fragment) {
            this._assume_text(fragment);
            this._fragments.push(fragment);
            this._current_consumer = this._CONTENT;
        };
        Receiver.prototype._CONTENT = function (fragment) {
            this._assume_text(fragment);
            this._fragments.push(fragment);
            var _a = (0, tslib_1.__read)(this._fragments.slice(0, 3), 3), header_json = _a[0], metadata_json = _a[1], content_json = _a[2];
            this._partial = message_1.Message.assemble(header_json, metadata_json, content_json);
            this._check_complete();
        };
        Receiver.prototype._BUFFER_HEADER = function (fragment) {
            this._assume_text(fragment);
            this._buf_header = fragment;
            this._current_consumer = this._BUFFER_PAYLOAD;
        };
        Receiver.prototype._BUFFER_PAYLOAD = function (fragment) {
            this._assume_binary(fragment);
            this._partial.assemble_buffer(this._buf_header, fragment);
            this._check_complete();
        };
        Receiver.prototype._assume_text = function (fragment) {
            if (!(0, types_1.isString)(fragment))
                throw new Error("Expected text fragment but received binary fragment");
        };
        Receiver.prototype._assume_binary = function (fragment) {
            if (!(fragment instanceof ArrayBuffer))
                throw new Error("Expected binary fragment but received text fragment");
        };
        Receiver.prototype._check_complete = function () {
            if (this._partial.complete()) {
                this.message = this._partial;
                this._current_consumer = this._HEADER;
            }
            else
                this._current_consumer = this._BUFFER_HEADER;
        };
        return Receiver;
    }());
    exports.Receiver = Receiver;
    Receiver.__name__ = "Receiver";
},
/* client/session.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var document_1 = require(122) /* ../document */;
    var message_1 = require(516) /* ../protocol/message */;
    var logging_1 = require(134) /* ../core/logging */;
    var ClientSession = /** @class */ (function () {
        function ClientSession(_connection, document, id) {
            var _this = this;
            this._connection = _connection;
            this.document = document;
            this.id = id;
            this._document_listener = function (event) {
                _this._document_changed(event);
            };
            this.document.on_change(this._document_listener, true);
        }
        ClientSession.prototype.handle = function (message) {
            var msgtype = message.msgtype();
            if (msgtype === "PATCH-DOC")
                this._handle_patch(message);
            else if (msgtype === "OK")
                this._handle_ok(message);
            else if (msgtype === "ERROR")
                this._handle_error(message);
            else
                logging_1.logger.debug("Doing nothing with message " + message.msgtype());
        };
        ClientSession.prototype.close = function () {
            this._connection.close();
        };
        /*protected*/ ClientSession.prototype._connection_closed = function () {
            this.document.remove_on_change(this._document_listener);
        };
        // Sends a request to the server for info about the server, such as its Bokeh
        // version. Returns a promise, the value of the promise is a free-form dictionary
        // of server details.
        ClientSession.prototype.request_server_info = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                var message, reply;
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            message = message_1.Message.create("SERVER-INFO-REQ", {});
                            return [4 /*yield*/, this._connection.send_with_reply(message)];
                        case 1:
                            reply = _a.sent();
                            return [2 /*return*/, reply.content];
                    }
                });
            });
        };
        // Sends some request to the server (no guarantee about which one) and returns
        // a promise which is completed when the server replies. The purpose of this
        // is that if you wait for the promise to be completed, you know the server
        // has processed the request. This is useful when writing tests because once
        // the server has processed this request it should also have processed any
        // events or requests you sent previously, which means you can check for the
        // results of that processing without a race condition. (This assumes the
        // server processes events in sequence, which it mostly has to semantically,
        // since reordering events might change the final state.)
        ClientSession.prototype.force_roundtrip = function () {
            return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
                return (0, tslib_1.__generator)(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.request_server_info()];
                        case 1:
                            _a.sent();
                            return [2 /*return*/];
                    }
                });
            });
        };
        ClientSession.prototype._document_changed = function (event) {
            // Filter out events that were initiated by the ClientSession itself
            if (event.setter_id === this.id) // XXX: not all document events define this
                return;
            var events = event instanceof document_1.DocumentEventBatch ? event.events : [event];
            var patch = this.document.create_json_patch(events);
            // TODO (havocp) the connection may be closed here, which will
            // cause this send to throw an error - need to deal with it more cleanly.
            var message = message_1.Message.create("PATCH-DOC", {}, patch);
            this._connection.send(message);
        };
        ClientSession.prototype._handle_patch = function (message) {
            this.document.apply_json_patch(message.content, message.buffers, this.id);
        };
        ClientSession.prototype._handle_ok = function (message) {
            logging_1.logger.trace("Unhandled OK reply to " + message.reqid());
        };
        ClientSession.prototype._handle_error = function (message) {
            logging_1.logger.error("Unhandled ERROR reply to " + message.reqid() + ": " + message.content.text);
        };
        return ClientSession;
    }());
    exports.ClientSession = ClientSession;
    ClientSession.__name__ = "ClientSession";
},
/* embed/notebook.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    var document_1 = require(122) /* ../document */;
    var receiver_1 = require(517) /* ../protocol/receiver */;
    var logging_1 = require(134) /* ../core/logging */;
    var dom_1 = require(158) /* ../core/dom */;
    var object_1 = require(128) /* ../core/util/object */;
    var standalone_1 = require(512) /* ./standalone */;
    var dom_2 = require(513) /* ./dom */;
    var root_css_1 = (0, tslib_1.__importDefault)(require(159) /* ../styles/root.css */);
    var logo_css_1 = (0, tslib_1.__importDefault)(require(355) /* ../styles/logo.css */);
    var notebook_css_1 = (0, tslib_1.__importDefault)(require(520) /* ../styles/notebook.css */);
    dom_1.stylesheet.append(root_css_1.default);
    dom_1.stylesheet.append(logo_css_1.default);
    dom_1.stylesheet.append(notebook_css_1.default);
    // This exists to allow the @bokeh/jupyter_bokeh extension to store the
    // notebook kernel so that _init_comms can register the comms target.
    // This has to be available at Bokeh.embed.kernels in JupyterLab.
    exports.kernels = {};
    function _handle_notebook_comms(receiver, comm_msg) {
        if (comm_msg.buffers.length > 0)
            receiver.consume(comm_msg.buffers[0].buffer);
        else
            receiver.consume(comm_msg.content.data);
        var msg = receiver.message;
        if (msg != null)
            this.apply_json_patch(msg.content, msg.buffers);
    }
    function _init_comms(target, doc) {
        var _this = this;
        if (typeof Jupyter !== "undefined" && Jupyter.notebook.kernel != null) {
            logging_1.logger.info("Registering Jupyter comms for target " + target);
            var comm_manager = Jupyter.notebook.kernel.comm_manager;
            try {
                comm_manager.register_target(target, function (comm) {
                    logging_1.logger.info("Registering Jupyter comms for target " + target);
                    var r = new receiver_1.Receiver();
                    comm.on_msg(_handle_notebook_comms.bind(doc, r));
                });
            }
            catch (e) {
                logging_1.logger.warn("Jupyter comms failed to register. push_notebook() will not function. (exception reported: " + e + ")");
            }
        }
        else if (doc.roots()[0].id in exports.kernels) {
            logging_1.logger.info("Registering JupyterLab comms for target " + target);
            var kernel = exports.kernels[doc.roots()[0].id];
            try {
                kernel.registerCommTarget(target, function (comm) {
                    logging_1.logger.info("Registering JupyterLab comms for target " + target);
                    var r = new receiver_1.Receiver();
                    comm.onMsg = _handle_notebook_comms.bind(doc, r);
                });
            }
            catch (e) {
                logging_1.logger.warn("Jupyter comms failed to register. push_notebook() will not function. (exception reported: " + e + ")");
            }
        }
        else if (typeof google != "undefined" && google.colab.kernel != null) {
            logging_1.logger.info("Registering Google Colab comms for target " + target);
            var comm_manager = google.colab.kernel.comms;
            try {
                comm_manager.registerTarget(target, function (comm) {
                    return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                        var r, _a, _b, message, content, buffers, _c, _d, buffer, msg, e_1_1;
                        var e_2, _e;
                        var e_1, _f;
                        var _g;
                        return (0, tslib_1.__generator)(this, function (_h) {
                            switch (_h.label) {
                                case 0:
                                    logging_1.logger.info("Registering Google Colab comms for target " + target);
                                    r = new receiver_1.Receiver();
                                    _h.label = 1;
                                case 1:
                                    _h.trys.push([1, 6, 7, 12]);
                                    _a = (0, tslib_1.__asyncValues)(comm.messages);
                                    _h.label = 2;
                                case 2: return [4 /*yield*/, _a.next()];
                                case 3:
                                    if (!(_b = _h.sent(), !_b.done))
                                        return [3 /*break*/, 5];
                                    message = _b.value;
                                    content = { data: message.data };
                                    buffers = [];
                                    try {
                                        for (_c = (e_2 = void 0, (0, tslib_1.__values)((_g = message.buffers) !== null && _g !== void 0 ? _g : [])), _d = _c.next(); !_d.done; _d = _c.next()) {
                                            buffer = _d.value;
                                            buffers.push(new DataView(buffer));
                                        }
                                    }
                                    catch (e_2_1) {
                                        e_2 = { error: e_2_1 };
                                    }
                                    finally {
                                        try {
                                            if (_d && !_d.done && (_e = _c.return))
                                                _e.call(_c);
                                        }
                                        finally {
                                            if (e_2)
                                                throw e_2.error;
                                        }
                                    }
                                    msg = { content: content, buffers: buffers };
                                    _handle_notebook_comms.bind(doc)(r, msg);
                                    _h.label = 4;
                                case 4: return [3 /*break*/, 2];
                                case 5: return [3 /*break*/, 12];
                                case 6:
                                    e_1_1 = _h.sent();
                                    e_1 = { error: e_1_1 };
                                    return [3 /*break*/, 12];
                                case 7:
                                    _h.trys.push([7, , 10, 11]);
                                    if (!(_b && !_b.done && (_f = _a.return)))
                                        return [3 /*break*/, 9];
                                    return [4 /*yield*/, _f.call(_a)];
                                case 8:
                                    _h.sent();
                                    _h.label = 9;
                                case 9: return [3 /*break*/, 11];
                                case 10:
                                    if (e_1)
                                        throw e_1.error;
                                    return [7 /*endfinally*/];
                                case 11: return [7 /*endfinally*/];
                                case 12: return [2 /*return*/];
                            }
                        });
                    });
                });
            }
            catch (e) {
                logging_1.logger.warn("Google Colab comms failed to register. push_notebook() will not function. (exception reported: " + e + ")");
            }
        }
        else {
            console.warn("Jupyter notebooks comms not available. push_notebook() will not function. If running JupyterLab ensure the latest @bokeh/jupyter_bokeh extension is installed. In an exported notebook this warning is expected.");
        }
    }
    function embed_items_notebook(docs_json, render_items) {
        var e_3, _a;
        if ((0, object_1.size)(docs_json) != 1)
            throw new Error("embed_items_notebook expects exactly one document in docs_json");
        var document = document_1.Document.from_json((0, object_1.values)(docs_json)[0]);
        try {
            for (var render_items_1 = (0, tslib_1.__values)(render_items), render_items_1_1 = render_items_1.next(); !render_items_1_1.done; render_items_1_1 = render_items_1.next()) {
                var item = render_items_1_1.value;
                if (item.notebook_comms_target != null)
                    _init_comms(item.notebook_comms_target, document);
                var element = (0, dom_2._resolve_element)(item);
                var roots = (0, dom_2._resolve_root_elements)(item);
                (0, standalone_1.add_document_standalone)(document, element, roots);
            }
        }
        catch (e_3_1) {
            e_3 = { error: e_3_1 };
        }
        finally {
            try {
                if (render_items_1_1 && !render_items_1_1.done && (_a = render_items_1.return))
                    _a.call(render_items_1);
            }
            finally {
                if (e_3)
                    throw e_3.error;
            }
        }
    }
    exports.embed_items_notebook = embed_items_notebook;
},
/* styles/notebook.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tooltip = "bk-tooltip";
    exports.default = ".rendered_html .bk-root .bk-tooltip table,.rendered_html .bk-root .bk-tooltip tr,.rendered_html .bk-root .bk-tooltip th,.rendered_html .bk-root .bk-tooltip td{border:none;padding:1px;}";
},
/* protocol/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var tslib_1 = require(1) /* tslib */;
    (0, tslib_1.__exportStar)(require(516) /* ./message */, exports);
    (0, tslib_1.__exportStar)(require(517) /* ./receiver */, exports);
},
/* testing.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    // Just a dumb key/value record for collecting arbitrary info for tests
    exports.results = {};
    // Selenium has race conditions that make it difficult to read out the
    // results structure. This function deletes/creates a div that can act as
    // a semaphore. Tests should wait for the previous div to be stale, then
    // find the new div. At that point the results should be available
    function update_test_div() {
        var body = document.getElementsByTagName("body")[0];
        var col = document.getElementsByClassName("bokeh-test-div");
        if (col.length == 1) {
            body.removeChild(col[0]);
            delete col[0];
        }
        var box = document.createElement("div");
        box.classList.add("bokeh-test-div");
        box.style.display = "none";
        body.insertBefore(box, body.firstChild);
    }
    function init() {
        update_test_div();
    }
    exports.init = init;
    function record0(key, value) {
        exports.results[key] = value;
    }
    exports.record0 = record0;
    function record(key, value) {
        exports.results[key] = value;
        update_test_div();
    }
    exports.record = record;
    function count(key) {
        if (exports.results[key] == undefined)
            exports.results[key] = 0;
        exports.results[key] += 1;
        update_test_div();
    }
    exports.count = count;
},
/* safely.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    // Keep this code as terse and as close to vanila JS as possible. If we
    // arrived here, it means we should trust no one and need to act properly.
    function _burst_into_flames(error) {
        // Make box
        var box = document.createElement("div");
        box.style.backgroundColor = "#f2dede";
        box.style.border = "1px solid #a94442";
        box.style.borderRadius = "4px";
        box.style.display = "inline-block";
        box.style.fontFamily = "sans-serif";
        box.style.marginTop = "5px";
        box.style.minWidth = "200px";
        box.style.padding = "5px 5px 5px 10px";
        box.classList.add("bokeh-error-box-into-flames");
        // Make button
        var button = document.createElement("span");
        button.style.backgroundColor = "#a94442";
        button.style.borderRadius = "0px 4px 0px 0px";
        button.style.color = "white";
        button.style.cursor = "pointer";
        button.style.cssFloat = "right";
        button.style.fontSize = "0.8em";
        button.style.margin = "-6px -6px 0px 0px";
        button.style.padding = "2px 5px 4px 5px";
        button.title = "close";
        button.setAttribute("aria-label", "close");
        button.appendChild(document.createTextNode("x"));
        button.addEventListener("click", function () { return body.removeChild(box); });
        // Make title
        var title = document.createElement("h3");
        title.style.color = "#a94442";
        title.style.margin = "8px 0px 0px 0px";
        title.style.padding = "0px";
        title.appendChild(document.createTextNode("Bokeh Error"));
        // Make message
        var message = document.createElement("pre");
        message.style.whiteSpace = "unset";
        message.style.overflowX = "auto";
        message.appendChild(document.createTextNode(error));
        // Add pieces to box
        box.appendChild(button);
        box.appendChild(title);
        box.appendChild(message);
        // Put box in doc
        var body = document.getElementsByTagName("body")[0];
        body.insertBefore(box, body.firstChild);
    }
    function safely(fn, silent) {
        if (silent === void 0) {
            silent = false;
        }
        try {
            return fn();
        }
        catch (error) {
            var text = error instanceof Error && error.stack ? error.stack : "" + error;
            _burst_into_flames(text);
            if (!silent)
                throw error;
            else
                return;
        }
    }
    exports.safely = safely;
},
], 0, {"legacy":0,"polyfill":2,"core/util/arrayable":116,"core/util/math":117,"main":118,"index":119,"version":120,"embed/index":121,"document/index":122,"document/document":123,"base":124,"core/util/types":125,"core/util/array":126,"core/util/assert":127,"core/util/object":128,"core/has_props":129,"core/signaling":130,"core/util/defer":131,"core/util/refs":132,"core/properties":133,"core/logging":134,"core/enums":135,"core/kinds":136,"core/util/color":137,"core/util/svg_colors":138,"core/types":139,"core/util/bitset":140,"core/util/eq":141,"core/util/platform":142,"core/settings":143,"core/util/ndarray":144,"core/serializer":145,"core/util/serialization":146,"core/util/buffer":147,"core/uniforms":148,"core/util/string":149,"document/events":150,"core/util/pretty":151,"core/util/cloneable":152,"models/index":153,"models/annotations/index":154,"models/annotations/annotation":155,"models/renderers/renderer":156,"core/view":157,"core/dom":158,"styles/root.css":159,"core/visuals/index":160,"core/visuals/line":161,"core/visuals/visual":162,"core/property_mixins":163,"core/visuals/fill":164,"core/visuals/text":165,"core/visuals/hatch":166,"core/visuals/patterns":167,"model":168,"models/canvas/coordinates":169,"models/scales/scale":170,"models/transforms/transform":171,"models/ranges/range":172,"models/ranges/range1d":173,"models/scales/linear_scale":174,"models/scales/continuous_scale":175,"models/scales/log_scale":176,"models/scales/categorical_scale":177,"models/ranges/data_range1d":178,"models/ranges/data_range":179,"core/util/bbox":180,"models/util":181,"models/ranges/factor_range":182,"models/annotations/arrow":183,"models/annotations/data_annotation":184,"models/sources/columnar_data_source":185,"models/sources/data_source":186,"models/selections/selection":187,"core/selection_manager":188,"models/selections/interaction_policy":189,"models/sources/column_data_source":190,"core/util/typed_array":191,"core/util/set":192,"core/util/projections":193,"models/annotations/arrow_head":227,"core/build_views":228,"models/annotations/band":229,"models/annotations/upper_lower":230,"models/annotations/box_annotation":231,"models/annotations/color_bar":232,"models/annotations/title":233,"models/annotations/text_annotation":234,"core/graphics":235,"core/util/text":236,"core/util/affine":237,"core/layout/side_panel":238,"core/layout/types":239,"core/layout/layoutable":240,"models/canvas/cartesian_frame":241,"models/axes/index":242,"models/axes/axis":243,"models/renderers/guide_renderer":244,"models/tickers/ticker":245,"models/formatters/tick_formatter":246,"models/policies/labeling":247,"models/text/base_text":248,"models/text/utils":249,"models/text/math_text":250,"core/util/image":251,"models/text/providers":252,"core/util/modules":253,"models/text/plain_text":254,"models/axes/categorical_axis":255,"models/tickers/categorical_ticker":256,"models/formatters/categorical_tick_formatter":257,"models/axes/continuous_axis":258,"models/axes/datetime_axis":259,"models/axes/linear_axis":260,"models/formatters/basic_tick_formatter":261,"models/tickers/basic_ticker":262,"models/tickers/adaptive_ticker":263,"models/tickers/continuous_ticker":264,"models/formatters/datetime_tick_formatter":265,"core/util/templating":267,"models/tickers/datetime_ticker":270,"models/tickers/composite_ticker":271,"models/tickers/days_ticker":272,"models/tickers/single_interval_ticker":273,"models/tickers/util":274,"models/tickers/months_ticker":275,"models/tickers/years_ticker":276,"models/axes/log_axis":277,"models/formatters/log_tick_formatter":278,"models/tickers/log_ticker":279,"models/axes/mercator_axis":280,"models/formatters/mercator_tick_formatter":281,"models/tickers/mercator_ticker":282,"models/tickers/index":283,"models/tickers/fixed_ticker":284,"models/tickers/binned_ticker":285,"models/mappers/scanning_color_mapper":286,"models/mappers/continuous_color_mapper":287,"models/mappers/color_mapper":288,"models/mappers/mapper":289,"models/renderers/glyph_renderer":290,"models/renderers/data_renderer":291,"models/glyphs/line":292,"models/glyphs/xy_glyph":293,"models/glyphs/glyph":294,"core/util/ragged_array":295,"core/util/spatial":296,"models/glyphs/utils":299,"core/hittest":300,"models/glyphs/patch":301,"models/glyphs/harea":302,"models/glyphs/area":303,"models/glyphs/varea":304,"models/sources/cds_view":305,"models/filters/filter":306,"models/formatters/index":307,"models/formatters/func_tick_formatter":308,"models/formatters/numeral_tick_formatter":309,"models/formatters/printf_tick_formatter":310,"models/mappers/index":311,"models/mappers/categorical_color_mapper":312,"models/mappers/categorical_mapper":313,"models/mappers/categorical_marker_mapper":314,"models/mappers/categorical_pattern_mapper":315,"models/mappers/linear_color_mapper":316,"models/mappers/log_color_mapper":317,"models/mappers/eqhist_color_mapper":318,"models/scales/index":319,"models/scales/linear_interpolation_scale":320,"models/ranges/index":321,"core/layout/index":322,"core/layout/alignments":323,"core/layout/grid":324,"core/layout/html":325,"core/layout/border":326,"models/annotations/label":327,"models/annotations/label_set":328,"models/annotations/legend":329,"models/annotations/legend_item":330,"core/vectorization":331,"models/annotations/poly_annotation":332,"models/annotations/slope":333,"models/annotations/span":334,"models/annotations/toolbar_panel":335,"models/tools/toolbar":336,"models/tools/tool":337,"models/tools/gestures/gesture_tool":338,"models/tools/button_tool":339,"core/dom_view":341,"styles/toolbar.css":342,"styles/icons.css":343,"styles/menus.css":344,"core/util/menus":345,"models/tools/on_off_button":346,"models/tools/inspectors/inspect_tool":347,"models/tools/toolbar_base":348,"core/util/iterator":349,"core/util/canvas":350,"core/util/svg":351,"core/util/random":352,"models/tools/actions/action_tool":353,"models/tools/actions/help_tool":354,"styles/logo.css":355,"models/annotations/tooltip":356,"styles/tooltips.css":357,"models/annotations/whisker":358,"models/callbacks/index":359,"models/callbacks/customjs":360,"models/callbacks/callback":361,"models/callbacks/open_url":362,"models/canvas/index":363,"models/canvas/canvas":364,"core/ui_events":365,"core/bokeh_events":366,"core/util/wheel":367,"models/expressions/index":368,"models/expressions/expression":369,"models/expressions/customjs_expr":370,"models/expressions/stack":371,"models/expressions/cumsum":372,"models/expressions/minimum":373,"models/expressions/maximum":374,"models/expressions/coordinate_transform":375,"models/expressions/polar":376,"models/filters/index":377,"models/filters/boolean_filter":378,"models/filters/customjs_filter":379,"models/filters/group_filter":380,"models/filters/index_filter":381,"models/glyphs/index":382,"models/glyphs/annular_wedge":383,"models/glyphs/annulus":384,"models/glyphs/arc":385,"models/glyphs/bezier":386,"models/glyphs/circle":387,"models/glyphs/ellipse":388,"models/glyphs/ellipse_oval":389,"models/glyphs/center_rotatable":390,"models/glyphs/hbar":391,"models/glyphs/box":392,"models/glyphs/hex_tile":393,"models/glyphs/image":394,"models/glyphs/image_base":395,"models/glyphs/image_rgba":396,"models/glyphs/image_url":397,"models/glyphs/multi_line":398,"models/glyphs/multi_polygons":399,"models/glyphs/oval":400,"models/glyphs/patches":401,"models/glyphs/quad":402,"models/glyphs/quadratic":403,"models/glyphs/ray":404,"models/glyphs/rect":405,"models/glyphs/scatter":406,"models/glyphs/marker":407,"models/glyphs/defs":408,"models/glyphs/segment":409,"models/glyphs/spline":410,"core/util/interpolation":411,"models/glyphs/step":412,"models/glyphs/text":413,"models/glyphs/vbar":414,"models/glyphs/wedge":415,"models/graphs/index":416,"models/graphs/graph_hit_test_policy":417,"models/graphs/layout_provider":418,"models/graphs/static_layout_provider":419,"models/grids/index":420,"models/grids/grid":421,"models/layouts/index":422,"models/layouts/box":423,"models/layouts/layout_dom":424,"models/layouts/column":425,"models/layouts/grid_box":426,"models/layouts/html_box":427,"models/layouts/panel":428,"models/layouts/row":429,"models/layouts/spacer":430,"models/layouts/tabs":431,"styles/tabs.css":432,"styles/buttons.css":433,"models/layouts/widget_box":434,"models/text/index":435,"models/transforms/index":436,"models/transforms/customjs_transform":437,"models/transforms/dodge":438,"models/transforms/range_transform":439,"models/transforms/interpolator":440,"models/transforms/jitter":441,"models/transforms/linear_interpolator":442,"models/transforms/step_interpolator":443,"models/plots/index":444,"models/plots/gmap_plot":445,"models/plots/plot":446,"models/plots/plot_canvas":447,"core/util/throttle":448,"models/plots/range_manager":449,"models/plots/state_manager":450,"models/plots/gmap_plot_canvas":451,"models/policies/index":452,"models/renderers/index":453,"models/renderers/graph_renderer":454,"models/selections/index":455,"models/sources/index":456,"models/sources/server_sent_data_source":457,"models/sources/web_data_source":458,"models/sources/ajax_data_source":459,"models/sources/geojson_data_source":460,"models/tiles/index":461,"models/tiles/bbox_tile_source":462,"models/tiles/mercator_tile_source":463,"models/tiles/tile_source":464,"models/tiles/tile_utils":465,"models/tiles/quadkey_tile_source":466,"models/tiles/tile_renderer":467,"models/tiles/wmts_tile_source":468,"styles/tiles.css":469,"models/tiles/tms_tile_source":470,"models/textures/index":471,"models/textures/canvas_texture":472,"models/textures/texture":473,"models/textures/image_url_texture":474,"models/tools/index":475,"models/tools/actions/custom_action":476,"models/tools/actions/redo_tool":477,"models/tools/actions/reset_tool":478,"models/tools/actions/save_tool":479,"models/tools/actions/undo_tool":480,"models/tools/actions/zoom_in_tool":481,"models/tools/actions/zoom_base_tool":482,"core/util/zoom":483,"models/tools/actions/zoom_out_tool":484,"models/tools/edit/edit_tool":485,"models/tools/edit/box_edit_tool":486,"models/tools/edit/freehand_draw_tool":487,"models/tools/edit/point_draw_tool":488,"models/tools/edit/poly_draw_tool":489,"models/tools/edit/poly_tool":490,"models/tools/edit/poly_edit_tool":491,"models/tools/gestures/box_select_tool":492,"models/tools/gestures/select_tool":493,"models/tools/gestures/box_zoom_tool":494,"models/tools/gestures/lasso_select_tool":495,"models/tools/gestures/poly_select_tool":496,"models/tools/edit/line_edit_tool":497,"models/tools/edit/line_tool":498,"models/tools/gestures/pan_tool":499,"models/tools/gestures/range_tool":500,"models/tools/gestures/tap_tool":501,"models/tools/gestures/wheel_pan_tool":502,"models/tools/gestures/wheel_zoom_tool":503,"models/tools/inspectors/crosshair_tool":504,"models/tools/inspectors/customjs_hover":505,"models/tools/inspectors/hover_tool":506,"models/dom/index":507,"models/dom/styles":508,"models/tools/tool_proxy":509,"models/tools/toolbar_box":510,"document/defs":511,"embed/standalone":512,"embed/dom":513,"embed/server":514,"client/connection":515,"protocol/message":516,"protocol/receiver":517,"client/session":518,"embed/notebook":519,"styles/notebook.css":520,"protocol/index":521,"testing":522,"safely":523}, {});});
//# sourceMappingURL=bokeh.legacy.js.map
