/*!
 * Copyright (c) 2012 - 2024, 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;
})
([
/* main.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(2) /* ./index */, exports);
    // TODO: remove this when models are split up from core
    require(70) /* ./models/main */;
},
/* 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 __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
        function accept(f) {
            if (f !== void 0 && typeof f !== "function")
                throw new TypeError("Function expected");
            return f;
        }
        var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
        var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
        var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
        var _, done = false;
        for (var i = decorators.length - 1; i >= 0; i--) {
            var context = {};
            for (var p in contextIn)
                context[p] = p === "access" ? {} : contextIn[p];
            for (var p in contextIn.access)
                context.access[p] = contextIn.access[p];
            context.addInitializer = function (f) {
                if (done)
                    throw new TypeError("Cannot add initializers after decoration has completed");
                extraInitializers.push(accept(f || null));
            };
            var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
            if (kind === "accessor") {
                if (result === void 0)
                    continue;
                if (result === null || typeof result !== "object")
                    throw new TypeError("Object expected");
                if (_ = accept(result.get))
                    descriptor.get = _;
                if (_ = accept(result.set))
                    descriptor.set = _;
                if (_ = accept(result.init))
                    initializers.unshift(_);
            }
            else if (_ = accept(result)) {
                if (kind === "field")
                    initializers.unshift(_);
                else
                    descriptor[key] = _;
            }
        }
        if (target)
            Object.defineProperty(target, contextIn.name, descriptor);
        done = true;
    }
    exports.__esDecorate = __esDecorate;
    ;
    function __runInitializers(thisArg, initializers, value) {
        var useValue = arguments.length > 2;
        for (var i = 0; i < initializers.length; i++) {
            value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
        }
        return useValue ? value : void 0;
    }
    exports.__runInitializers = __runInitializers;
    ;
    function __propKey(x) {
        return typeof x === "symbol" ? x : "".concat(x);
    }
    exports.__propKey = __propKey;
    ;
    function __setFunctionName(f, name, prefix) {
        if (typeof name === "symbol")
            name = name.description ? "[".concat(name.description, "]") : "";
        return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
    }
    exports.__setFunctionName = __setFunctionName;
    ;
    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 (g && (g = 0, op[0] && (_ = 0)), _)
                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;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (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: false } : 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;
    function __classPrivateFieldIn(state, receiver) {
        if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function"))
            throw new TypeError("Cannot use 'in' operator on non-object");
        return typeof state === "function" ? receiver === state : state.has(receiver);
    }
    exports.__classPrivateFieldIn = __classPrivateFieldIn;
    function __addDisposableResource(env, value, async) {
        if (value !== null && value !== void 0) {
            if (typeof value !== "object" && typeof value !== "function")
                throw new TypeError("Object expected.");
            var dispose;
            if (async) {
                if (!Symbol.asyncDispose)
                    throw new TypeError("Symbol.asyncDispose is not defined.");
                dispose = value[Symbol.asyncDispose];
            }
            if (dispose === void 0) {
                if (!Symbol.dispose)
                    throw new TypeError("Symbol.dispose is not defined.");
                dispose = value[Symbol.dispose];
            }
            if (typeof dispose !== "function")
                throw new TypeError("Object not disposable.");
            env.stack.push({ value: value, dispose: dispose, async: async });
        }
        else if (async) {
            env.stack.push({ async: true });
        }
        return value;
    }
    exports.__addDisposableResource = __addDisposableResource;
    var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };
    function __disposeResources(env) {
        function fail(e) {
            env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        function next() {
            while (env.stack.length) {
                var rec = env.stack.pop();
                try {
                    var result = rec.dispose && rec.dispose.call(rec.value);
                    if (rec.async)
                        return Promise.resolve(result).then(next, function (e) { fail(e); return next(); });
                }
                catch (e) {
                    fail(e);
                }
            }
            if (env.hasError)
                throw env.error;
        }
        return next();
    }
    exports.__disposeResources = __disposeResources;
    exports.default = {
        __extends: __extends,
        __assign: exports.__assign,
        __rest: __rest,
        __decorate: __decorate,
        __param: __param,
        __metadata: __metadata,
        __awaiter: __awaiter,
        __generator: __generator,
        __createBinding: exports.__createBinding,
        __exportStar: __exportStar,
        __values: __values,
        __read: __read,
        __spread: __spread,
        __spreadArrays: __spreadArrays,
        __spreadArray: __spreadArray,
        __await: __await,
        __asyncGenerator: __asyncGenerator,
        __asyncDelegator: __asyncDelegator,
        __asyncValues: __asyncValues,
        __makeTemplateObject: __makeTemplateObject,
        __importStar: __importStar,
        __importDefault: __importDefault,
        __classPrivateFieldGet: __classPrivateFieldGet,
        __classPrivateFieldSet: __classPrivateFieldSet,
        __classPrivateFieldIn: __classPrivateFieldIn,
        __addDisposableResource: __addDisposableResource,
        __disposeResources: __disposeResources,
    };
},
/* index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var version_1 = require(3) /* ./version */;
    __esExport("version", version_1.version);
    var embed_1 = require(4) /* ./embed */;
    __esExport("index", embed_1.index);
    exports.embed = tslib_1.__importStar(require(4) /* ./embed */);
    exports.protocol = tslib_1.__importStar(require(67) /* ./protocol */);
    exports._testing = tslib_1.__importStar(require(68) /* ./testing */);
    var logging_1 = require(19) /* ./core/logging */;
    __esExport("logger", logging_1.logger);
    __esExport("set_log_level", logging_1.set_log_level);
    var settings_1 = require(29) /* ./core/settings */;
    __esExport("settings", settings_1.settings);
    var base_1 = require(7) /* ./base */;
    __esExport("Models", base_1.default_resolver);
    var document_1 = require(5) /* ./document */;
    __esExport("documents", document_1.documents);
    var safely_1 = require(69) /* ./safely */;
    __esExport("safely", safely_1.safely);
},
/* version.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.version = "3.3.4";
},
/* embed/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const document_1 = require(5) /* ../document */;
    const settings_1 = require(29) /* ../core/settings */;
    const logging_1 = require(19) /* ../core/logging */;
    const string_1 = require(40) /* ../core/util/string */;
    const object_1 = require(9) /* ../core/util/object */;
    const types_1 = require(8) /* ../core/util/types */;
    const defer_1 = require(16) /* ../core/util/defer */;
    const standalone_1 = require(53) /* ./standalone */;
    const server_1 = require(60) /* ./server */;
    const dom_1 = require(65) /* ./dom */;
    var standalone_2 = require(53) /* ./standalone */;
    __esExport("add_document_standalone", standalone_2.add_document_standalone);
    __esExport("index", standalone_2.index);
    var server_2 = require(60) /* ./server */;
    __esExport("add_document_from_session", server_2.add_document_from_session);
    var notebook_1 = require(66) /* ./notebook */;
    __esExport("embed_items_notebook", notebook_1.embed_items_notebook);
    __esExport("kernels", notebook_1.kernels);
    async function embed_item(item, target) {
        const docs_json = {};
        const doc_id = (0, string_1.uuid4)();
        docs_json[doc_id] = item.doc;
        if (target == null)
            target = item.target_id;
        const roots = { [item.root_id]: target };
        const render_item = { roots, root_ids: [item.root_id], docid: doc_id };
        await (0, defer_1.defer)();
        const [views] = await _embed_items(docs_json, [render_item]);
        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
    async function embed_items(docs_json, render_items, app_path, absolute_url) {
        await (0, defer_1.defer)();
        return _embed_items(docs_json, render_items, app_path, absolute_url);
    }
    exports.embed_items = embed_items;
    async function _embed_items(docs_json, render_items, app_path, absolute_url) {
        if ((0, types_1.isString)(docs_json))
            docs_json = JSON.parse((0, string_1.unescape)(docs_json));
        const docs = {};
        for (const [docid, doc_json] of (0, object_1.entries)(docs_json)) {
            docs[docid] = document_1.Document.from_json(doc_json);
        }
        const views = [];
        for (const item of render_items) {
            const element = (0, dom_1._resolve_element)(item);
            const roots = (0, dom_1._resolve_root_elements)(item);
            if (item.docid != null) {
                views.push(await (0, standalone_1.add_document_standalone)(docs[item.docid], element, roots, item.use_for_title));
            }
            else if (item.token != null) {
                const websocket_url = (0, server_1._get_ws_url)(app_path, absolute_url);
                logging_1.logger.debug(`embed: computed ws url: ${websocket_url}`);
                try {
                    views.push(await (0, server_1.add_document_from_session)(websocket_url, item.token, element, roots, item.use_for_title));
                    console.log("Bokeh items were rendered successfully");
                }
                catch (error) {
                    if (settings_1.settings.dev)
                        throw error;
                    else
                        console.error("Error rendering Bokeh items:", error);
                }
            }
            else
                throw new Error("Error rendering Bokeh items: either 'docid' or 'token' was expected.");
        }
        return views;
    }
},
/* document/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(6) /* ./document */, exports);
    tslib_1.__exportStar(require(41) /* ./events */, exports);
},
/* document/document.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const base_1 = require(7) /* ../base */;
    const version_1 = require(3) /* ../version */;
    const logging_1 = require(19) /* ../core/logging */;
    const resolvers_1 = require(46) /* ../core/resolvers */;
    const serialization_1 = require(32) /* ../core/serialization */;
    const deserializer_1 = require(47) /* ../core/serialization/deserializer */;
    const version_2 = require(49) /* ../core/util/version */;
    const signaling_1 = require(15) /* ../core/signaling */;
    const types_1 = require(8) /* ../core/util/types */;
    const eq_1 = require(26) /* ../core/util/eq */;
    const array_1 = require(10) /* ../core/util/array */;
    const object_1 = require(9) /* ../core/util/object */;
    const sets = tslib_1.__importStar(require(44) /* ../core/util/set */);
    const model_1 = require(50) /* ../model */;
    const defs_1 = require(51) /* ./defs */;
    const bokeh_events_1 = require(52) /* ../core/bokeh_events */;
    const events_1 = require(41) /* ./events */;
    deserializer_1.Deserializer.register("model", defs_1.decode_def);
    // Dispatches events to the subscribed models
    class EventManager {
        constructor(document) {
            this.subscribed_models = new Set();
            this.document = document;
        }
        send_event(bokeh_event) {
            if (bokeh_event.publish) {
                const event = new events_1.MessageSentEvent(this.document, "bokeh_event", bokeh_event);
                this.document._trigger_on_change(event);
            }
            this.document._trigger_on_event(bokeh_event);
        }
        trigger(event) {
            for (const model of this.subscribed_models) {
                if (event.origin != null && event.origin != model)
                    continue;
                model._process_event(event);
            }
        }
    }
    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.
    class Document {
        constructor(options = {}) {
            var _a;
            exports.documents.push(this);
            this._init_timestamp = Date.now();
            this._resolver = (_a = options.resolver) !== null && _a !== void 0 ? _a : new resolvers_1.ModelResolver(base_1.default_resolver);
            this._title = exports.DEFAULT_TITLE;
            this._roots = [];
            this._all_models = new Map();
            this._new_models = new Set();
            this._all_models_freeze_count = 0;
            this._callbacks = new Map();
            this._document_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 WeakSet();
            this._interactive_timestamp = null;
            this._interactive_plot = null;
            if (options.roots != null) {
                this._add_roots(...options.roots);
            }
        }
        [eq_1.equals](that, _cmp) {
            return this == that;
        }
        get is_idle() {
            // TODO: models without views, e.g. data models
            for (const root of this._roots) {
                if (!this._idle_roots.has(root))
                    return false;
            }
            return true;
        }
        notify_idle(model) {
            this._idle_roots.add(model);
            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();
            }
        }
        clear() {
            this._push_all_models_freeze();
            try {
                while (this._roots.length > 0) {
                    this.remove_root(this._roots[0]);
                }
            }
            finally {
                this._pop_all_models_freeze();
            }
        }
        interactive_start(plot, 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();
        }
        interactive_stop() {
            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;
        }
        interactive_duration() {
            if (this._interactive_timestamp == null)
                return -1;
            else
                return Date.now() - this._interactive_timestamp;
        }
        destructively_move(dest_doc) {
            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.
            const roots = (0, array_1.copy)(this._roots);
            this.clear();
            for (const root of roots) {
                if (root.document != null)
                    throw new Error(`Somehow we didn't detach ${root}`);
            }
            if (this._all_models.size != 0) {
                throw new Error(`this._all_models still had stuff in it: ${this._all_models}`);
            }
            for (const root of roots) {
                dest_doc.add_root(root);
            }
            dest_doc.set_title(this._title);
        }
        // TODO other fields of doc
        _push_all_models_freeze() {
            this._all_models_freeze_count += 1;
        }
        _pop_all_models_freeze() {
            this._all_models_freeze_count -= 1;
            if (this._all_models_freeze_count === 0) {
                this._recompute_all_models();
            }
        }
        /*protected*/ _invalidate_all_models() {
            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();
            }
        }
        _recompute_all_models() {
            let new_all_models_set = new Set();
            for (const r of this._roots) {
                new_all_models_set = sets.union(new_all_models_set, r.references());
            }
            const old_all_models_set = new Set(this._all_models.values());
            const to_detach = sets.difference(old_all_models_set, new_all_models_set);
            const to_attach = sets.difference(new_all_models_set, old_all_models_set);
            const recomputed = new Map();
            for (const model of new_all_models_set) {
                recomputed.set(model.id, model);
            }
            for (const d of to_detach) {
                d.detach_document();
            }
            for (const model of to_attach) {
                model.attach_document(this);
                this._new_models.add(model);
            }
            this._all_models = recomputed; // XXX
        }
        roots() {
            return this._roots;
        }
        _add_roots(...models) {
            models = models.filter((model) => !this._roots.includes(model));
            if (models.length == 0) {
                return false;
            }
            this._push_all_models_freeze();
            try {
                this._roots.push(...models);
            }
            finally {
                this._pop_all_models_freeze();
            }
            return true;
        }
        _remove_root(model) {
            const i = this._roots.indexOf(model);
            if (i < 0)
                return false;
            this._push_all_models_freeze();
            try {
                this._roots.splice(i, 1);
            }
            finally {
                this._pop_all_models_freeze();
            }
            return true;
        }
        _set_title(title) {
            const new_title = title != this._title;
            if (new_title)
                this._title = title;
            return new_title;
        }
        add_root(model) {
            if (this._add_roots(model))
                this._trigger_on_change(new events_1.RootAddedEvent(this, model));
        }
        remove_root(model) {
            if (this._remove_root(model))
                this._trigger_on_change(new events_1.RootRemovedEvent(this, model));
        }
        set_title(title) {
            if (this._set_title(title))
                this._trigger_on_change(new events_1.TitleChangedEvent(this, title));
        }
        title() {
            return this._title;
        }
        get_model_by_id(model_id) {
            var _a;
            return (_a = this._all_models.get(model_id)) !== null && _a !== void 0 ? _a : null;
        }
        get_model_by_name(name) {
            const found = [];
            for (const model of this._all_models.values()) {
                if (model instanceof model_1.Model && model.name == name)
                    found.push(model);
            }
            switch (found.length) {
                case 0:
                    return null;
                case 1:
                    return found[0];
                default:
                    throw new Error(`Multiple models are named '${name}'`);
            }
        }
        on_message(msg_type, callback) {
            const 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);
        }
        remove_on_message(msg_type, callback) {
            var _a;
            (_a = this._message_callbacks.get(msg_type)) === null || _a === void 0 ? void 0 : _a.delete(callback);
        }
        _trigger_on_message(msg_type, msg_data) {
            const message_callbacks = this._message_callbacks.get(msg_type);
            if (message_callbacks != null) {
                for (const cb of message_callbacks) {
                    cb(msg_data);
                }
            }
        }
        on_change(callback, allow_batches = false) {
            if (!this._callbacks.has(callback)) {
                this._callbacks.set(callback, allow_batches);
            }
        }
        remove_on_change(callback) {
            this._callbacks.delete(callback);
        }
        _trigger_on_change(event) {
            for (const [callback, allow_batches] of this._callbacks) {
                if (!allow_batches && event instanceof events_1.DocumentEventBatch) {
                    for (const ev of event.events) {
                        callback(ev);
                    }
                }
                else {
                    callback(event); // TODO
                }
            }
        }
        _trigger_on_event(event) {
            const callbacks = this._document_callbacks.get(event.event_name);
            if (callbacks != null) {
                for (const callback of callbacks) {
                    callback.execute(this, event);
                }
            }
        }
        on_event(event, ...callbacks) {
            var _a;
            const name = (0, types_1.isString)(event) ? event : event.prototype.event_name;
            const existing = (_a = this._document_callbacks.get(name)) !== null && _a !== void 0 ? _a : [];
            const added = callbacks.map((callback) => (0, types_1.isFunction)(callback) ? { execute: callback } : callback);
            this._document_callbacks.set(name, [...existing, ...added]);
        }
        to_json_string(include_defaults = true) {
            return JSON.stringify(this.to_json(include_defaults));
        }
        to_json(include_defaults = true) {
            const serializer = new serialization_1.Serializer({ include_defaults });
            const roots = serializer.encode(this._roots);
            return {
                version: version_1.version,
                title: this._title,
                roots,
            };
        }
        static from_json_string(s, events) {
            const json = JSON.parse(s);
            return Document.from_json(json, events);
        }
        static _handle_version(json) {
            if (json.version != null) {
                const py_version = json.version;
                const is_dev = py_version.indexOf("+") !== -1 || py_version.indexOf("-") !== -1;
                const versions_string = `Library versions: JS (${version_1.version}) / Python (${py_version})`;
                if (!is_dev && (0, version_2.pyify_version)(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);
            }
            else
                logging_1.logger.warn("'version' field is missing");
        }
        static from_json(doc_json, events) {
            logging_1.logger.debug("Creating Document from JSON");
            Document._handle_version(doc_json);
            const resolver = new resolvers_1.ModelResolver(base_1.default_resolver);
            if (doc_json.defs != null) {
                const deserializer = new deserializer_1.Deserializer(resolver);
                deserializer.decode(doc_json.defs);
            }
            const doc = new Document({ resolver });
            doc._push_all_models_freeze();
            const listener = (event) => events === null || events === void 0 ? void 0 : events.push(event);
            doc.on_change(listener, true);
            const deserializer = new deserializer_1.Deserializer(resolver, doc._all_models, (obj) => obj.attach_document(doc));
            const roots = deserializer.decode(doc_json.roots);
            const callbacks = (() => {
                if (doc_json.callbacks != null)
                    return deserializer.decode(doc_json.callbacks);
                else
                    return {};
            })();
            doc.remove_on_change(listener);
            for (const [event, event_callbacks] of (0, object_1.entries)(callbacks)) {
                doc.on_event(event, ...event_callbacks);
            }
            for (const root of roots) {
                doc.add_root(root);
            }
            if (doc_json.title != null) {
                doc.set_title(doc_json.title);
            }
            doc._pop_all_models_freeze();
            return doc;
        }
        replace_with_json(json) {
            const replacement = Document.from_json(json);
            replacement.destructively_move(this);
        }
        create_json_patch(events) {
            for (const event of events) {
                if (event.document != this)
                    throw new Error("Cannot create a patch using events from a different document");
            }
            const references = new Map();
            for (const model of this._all_models.values()) {
                if (!this._new_models.has(model)) {
                    references.set(model, model.ref());
                }
            }
            const serializer = new serialization_1.Serializer({ references, binary: true });
            const patch = { events: serializer.encode(events) };
            this._new_models.clear();
            return patch;
        }
        apply_json_patch(patch, buffers = new Map()) {
            this._push_all_models_freeze();
            const deserializer = new deserializer_1.Deserializer(this._resolver, this._all_models, (obj) => obj.attach_document(this));
            const events = deserializer.decode(patch.events, buffers);
            for (const event of events) {
                switch (event.kind) {
                    case "MessageSent": {
                        const { msg_type, msg_data } = event;
                        this._trigger_on_message(msg_type, msg_data);
                        break;
                    }
                    case "ModelChanged": {
                        const { model, attr, new: value } = event;
                        model.setv({ [attr]: value }, { sync: false });
                        break;
                    }
                    case "ColumnDataChanged": {
                        const { model, attr, cols, data } = event;
                        if (cols != null) {
                            const current_data = model.property(attr).get_value();
                            for (const k in current_data) {
                                if (!(k in data)) {
                                    data[k] = current_data[k];
                                }
                            }
                        }
                        model.setv({ data }, { sync: false, check_eq: false });
                        break;
                    }
                    case "ColumnsStreamed": {
                        const { model, attr, data, rollover } = event;
                        const prop = model.property(attr);
                        model.stream_to(prop, data, rollover, { sync: false });
                        break;
                    }
                    case "ColumnsPatched": {
                        const { model, attr, patches } = event;
                        const prop = model.property(attr);
                        model.patch_to(prop, patches, { sync: false });
                        break;
                    }
                    case "RootAdded": {
                        this._add_roots(event.model);
                        break;
                    }
                    case "RootRemoved": {
                        this._remove_root(event.model);
                        break;
                    }
                    case "TitleChanged": {
                        this._set_title(event.title);
                        break;
                    }
                    default:
                        throw new Error(`unknown patch event type '${event.kind}'`); // XXX
                }
            }
            this._pop_all_models_freeze();
        }
    }
    exports.Document = Document;
    Document.__name__ = "Document";
},
/* base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ./core/util/types */;
    const object_1 = require(9) /* ./core/util/object */;
    const has_props_1 = require(14) /* ./core/has_props */;
    const resolvers_1 = require(46) /* ./core/resolvers */;
    exports.default_resolver = new resolvers_1.ModelResolver(null);
    function is_HasProps(obj) {
        return (0, types_1.isObject)(obj) && obj.prototype instanceof has_props_1.HasProps;
    }
    function register_models(models, force = false) {
        for (const model of (0, types_1.isArray)(models) ? models : (0, object_1.values)(models)) {
            if (is_HasProps(model)) {
                exports.default_resolver.register(model, force);
            }
        }
    }
    exports.register_models = register_models;
},
/* 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.
    const toString = Object.prototype.toString;
    function is_undefined(obj) {
        return typeof obj === "undefined";
    }
    exports.is_undefined = is_undefined;
    function is_defined(obj) {
        return typeof obj !== "undefined";
    }
    exports.is_defined = is_defined;
    // XXX: use only to work around strict conditional expressions
    function is_nullish(obj) {
        return obj == null;
    }
    exports.is_nullish = is_nullish;
    function isNull(obj) {
        return obj == null;
    }
    exports.isNull = isNull;
    function isNotNull(obj) {
        return obj != null;
    }
    exports.isNotNull = isNotNull;
    exports.non_null = isNotNull;
    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) {
        const rep = toString.call(obj);
        switch (rep) {
            case "[object Function]":
            case "[object AsyncFunction]":
            case "[object GeneratorFunction]":
            case "[object AsyncGeneratorFunction]":
                return true;
            default:
                return false;
        }
    }
    exports.isFunction = isFunction;
    function isArray(obj) {
        return Array.isArray(obj);
    }
    exports.isArray = isArray;
    function isArrayOf(array, predicate) {
        for (const item of array) {
            if (!predicate(item))
                return false;
        }
        return true;
    }
    exports.isArrayOf = isArrayOf;
    function isArrayableOf(array, predicate) {
        for (const item of array) {
            if (!predicate(item))
                return false;
        }
        return true;
    }
    exports.isArrayableOf = isArrayableOf;
    function isTypedArray(obj) {
        return ArrayBuffer.isView(obj) && !(obj instanceof DataView);
    }
    exports.isTypedArray = isTypedArray;
    function isObject(obj) {
        const tp = typeof obj;
        return tp === "function" || tp === "object" && !!obj;
    }
    exports.isObject = isObject;
    function isBasicObject(obj) {
        return isObject(obj) && is_nullish(obj.constructor);
    }
    exports.isBasicObject = isBasicObject;
    function isPlainObject(obj) {
        return isObject(obj) && (is_nullish(obj.constructor) || obj.constructor === Object);
    }
    exports.isPlainObject = isPlainObject;
    function isIterable(obj) {
        return isObject(obj) && Symbol.iterator in obj;
    }
    exports.isIterable = isIterable;
    function isArrayable(obj) {
        return isIterable(obj) && "length" in obj;
    }
    exports.isArrayable = isArrayable;
},
/* core/util/object.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const array_1 = require(10) /* ./array */;
    const { hasOwnProperty } = Object.prototype;
    exports.keys = Object.keys, exports.values = Object.values, exports.entries = Object.entries, exports.assign = Object.assign, exports.to_object = Object.fromEntries;
    exports.extend = exports.assign;
    exports.typed_keys = exports.keys;
    exports.typed_values = exports.values;
    exports.typed_entries = exports.entries;
    function clone(obj) {
        return Object.assign({}, obj);
    }
    exports.clone = clone;
    function merge(obj1, obj2) {
        /*
         * Returns an object with the array values for obj1 and obj2 unioned by key.
         */
        const result = Object.create(Object.prototype);
        const keys = (0, array_1.concat)([Object.keys(obj1), Object.keys(obj2)]);
        for (const key of keys) {
            const arr1 = hasOwnProperty.call(obj1, key) ? obj1[key] : [];
            const arr2 = hasOwnProperty.call(obj2, key) ? obj2[key] : [];
            result[key] = (0, array_1.union)(arr1, arr2);
        }
        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;
    class Dict {
        constructor(obj) {
            this[_a] = "Dict";
            this.obj = obj;
        }
        clear() {
            for (const key of (0, exports.keys)(this.obj)) {
                delete this.obj[key];
            }
        }
        delete(key) {
            const had = key in this;
            delete this.obj[key];
            return had;
        }
        get(key) {
            return key in this.obj ? this.obj[key] : undefined;
        }
        has(key) {
            return key in this.obj;
        }
        set(key, value) {
            this.obj[key] = value;
            return this;
        }
        get size() {
            return size(this.obj);
        }
        get is_empty() {
            return this.size == 0;
        }
        [(_a = Symbol.toStringTag, Symbol.iterator)]() {
            return this.entries();
        }
        *keys() {
            yield* (0, exports.keys)(this.obj);
        }
        *values() {
            yield* (0, exports.values)(this.obj);
        }
        *entries() {
            yield* (0, exports.entries)(this.obj);
        }
        forEach(callback, that) {
            for (const [key, value] of this.entries()) {
                callback.call(that, value, key, this);
            }
        }
    }
    exports.Dict = Dict;
    Dict.__name__ = "Dict";
    function dict(o) {
        return new Dict(o);
    }
    exports.dict = dict;
},
/* core/util/array.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.
    const math_1 = require(11) /* ./math */;
    const assert_1 = require(12) /* ./assert */;
    const types_1 = require(8) /* ./types */;
    const arrayable_1 = require(13) /* ./arrayable */;
    var arrayable_2 = require(13) /* ./arrayable */;
    __esExport("map", arrayable_2.map);
    __esExport("reduce", arrayable_2.reduce);
    __esExport("min", arrayable_2.min);
    __esExport("min_by", arrayable_2.min_by);
    __esExport("max", arrayable_2.max);
    __esExport("max_by", arrayable_2.max_by);
    __esExport("sum", arrayable_2.sum);
    __esExport("cumsum", arrayable_2.cumsum);
    __esExport("every", arrayable_2.every);
    __esExport("some", arrayable_2.some);
    __esExport("find", arrayable_2.find);
    __esExport("find_last", arrayable_2.find_last);
    __esExport("find_index", arrayable_2.find_index);
    __esExport("find_last_index", arrayable_2.find_last_index);
    __esExport("sorted_index", arrayable_2.sorted_index);
    __esExport("is_empty", arrayable_2.is_empty);
    __esExport("includes", arrayable_2.includes);
    __esExport("contains", arrayable_2.contains);
    __esExport("sort_by", arrayable_2.sort_by);
    const 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(...arrays);
    }
    exports.concat = concat;
    function nth(array, index) {
        return array[index >= 0 ? index : array.length + index];
    }
    exports.nth = nth;
    function zip(...arrays) {
        if (arrays.length == 0)
            return [];
        const n = (0, arrayable_1.min)(arrays.map((a) => a.length));
        const k = arrays.length;
        const result = new Array(n);
        for (let i = 0; i < n; i++) {
            result[i] = new Array(k);
            for (let j = 0; j < k; j++)
                result[i][j] = arrays[j][i];
        }
        return result;
    }
    exports.zip = zip;
    function unzip(array) {
        const n = array.length;
        if (n == 0) {
            return [];
        }
        const k = (0, arrayable_1.min)(array.map((a) => a.length));
        const results = Array(k);
        for (let j = 0; j < k; j++)
            results[j] = new Array(n);
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < k; j++)
                results[j][i] = array[i][j];
        }
        return results;
    }
    exports.unzip = unzip;
    function range(start, stop, step = 1) {
        (0, assert_1.assert)(step > 0, "'step' must be a positive number");
        if (stop == null) {
            stop = start;
            start = 0;
        }
        const { max, ceil, abs } = Math;
        const delta = start <= stop ? step : -step;
        const length = max(ceil(abs(stop - start) / step), 0);
        const range = new Array(length);
        for (let i = 0; i < length; i++, start += delta) {
            range[i] = start;
        }
        return range;
    }
    exports.range = range;
    function linspace(start, stop, num = 100) {
        const step = num == 1 ? 0 : (stop - start) / (num - 1);
        const array = new Array(num);
        for (let i = 0; i < num; i++) {
            array[i] = start + step * i;
        }
        return array;
    }
    exports.linspace = linspace;
    function transpose(array) {
        const rows = array.length;
        const cols = array[0].length;
        const transposed = [];
        for (let j = 0; j < cols; j++) {
            transposed[j] = [];
            for (let 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), (i) => array[i]);
    }
    exports.argmin = argmin;
    function argmax(array) {
        return (0, arrayable_1.max_by)(range(array.length), (i) => array[i]);
    }
    exports.argmax = argmax;
    function uniq(array) {
        const result = new Set();
        for (const value of array) {
            result.add(value);
        }
        return [...result];
    }
    exports.uniq = uniq;
    function uniq_by(array, key) {
        const result = [];
        const seen = [];
        for (const value of array) {
            const computed = key(value);
            if (!(0, arrayable_1.includes)(seen, computed)) {
                seen.push(computed);
                result.push(value);
            }
        }
        return result;
    }
    exports.uniq_by = uniq_by;
    function _union(arrays) {
        const result = new Set();
        for (const array of arrays) {
            for (const value of array) {
                result.add(value);
            }
        }
        return result;
    }
    exports._union = _union;
    function union(...arrays) {
        return [..._union(arrays)];
    }
    exports.union = union;
    function intersection(array, ...arrays) {
        const result = [];
        top: for (const item of array) {
            if ((0, arrayable_1.includes)(result, item))
                continue;
            for (const other of arrays) {
                if (!(0, arrayable_1.includes)(other, item))
                    continue top;
            }
            result.push(item);
        }
        return result;
    }
    exports.intersection = intersection;
    function difference(array, ...arrays) {
        const rest = _union(arrays);
        return (0, arrayable_1.filter)(array, (value) => !rest.has(value));
    }
    exports.difference = difference;
    function remove_at(array, i) {
        (0, assert_1.assert)((0, types_1.isInteger)(i) && i >= 0);
        const result = copy(array);
        result.splice(i, 1);
        return result;
    }
    exports.remove_at = remove_at;
    function remove_by(array, key) {
        for (let i = 0; i < array.length;) {
            if (key(array[i]))
                array.splice(i, 1);
            else
                i++;
        }
    }
    exports.remove_by = remove_by;
    function clear(array) {
        array.splice(0, array.length);
    }
    exports.clear = clear;
    function split(array, separator) {
        const chunks = [];
        const n = array.length;
        let i = 0;
        let j = 0;
        while (j < n) {
            if (array[j] === separator) {
                chunks.push(array.slice(i, j));
                i = ++j;
            }
            else
                ++j;
        }
        chunks.push(array.slice(i));
        return chunks;
    }
    exports.split = split;
    // Shuffle a collection, using the modern version of the
    // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
    function shuffle(array) {
        const length = array.length;
        const shuffled = new Array(length);
        for (let i = 0; i < length; i++) {
            const 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) {
        const n = array.length;
        const result = new Array(n - 1);
        for (let i = 0; i < n - 1; i++) {
            result[i] = fn(array[i], array[i + 1]);
        }
        return result;
    }
    exports.pairwise = pairwise;
    function reversed(array) {
        const n = array.length;
        const result = new Array(n);
        for (let i = 0; i < n; i++) {
            result[n - i - 1] = array[i];
        }
        return result;
    }
    exports.reversed = reversed;
    function repeat(value, n) {
        const result = new Array(n).fill(value);
        return result;
    }
    exports.repeat = repeat;
},
/* core/util/math.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ./types */;
    const assert_1 = require(12) /* ./assert */;
    const { PI, abs, sign } = Math;
    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 = false) {
        const d = angle_dist(lhs, rhs);
        if (d == 0)
            return false;
        if (d == 2 * PI)
            return true;
        const norm_mid = angle_norm(mid);
        const cond = angle_dist(lhs, norm_mid) <= d && angle_dist(norm_mid, rhs) <= d;
        return !anticlock ? cond : !cond;
    }
    exports.angle_between = angle_between;
    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 compute_angle(angle, units, dir = "anticlock") {
        /**
         * Convert math CCW(default)/CW angle with units to CW radians (canvas).
         */
        const sign = dir == "anticlock" ? 1 : -1;
        return -sign * angle * to_radians_coeff(units);
    }
    exports.compute_angle = compute_angle;
    function invert_angle(angle, units, dir = "anticlock") {
        /**
         * Convert CW radians (canvas) to math CCW(default)/CW angle with units.
         */
        const sign = dir == "anticlock" ? 1 : -1;
        return -sign * angle / to_radians_coeff(units);
    }
    exports.invert_angle = invert_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;
    function minmax(v0, v1) {
        return v0 <= v1 ? [v0, v1] : [v1, v0];
    }
    exports.minmax = minmax;
    function clamp(val, min, max) {
        return val < min ? min : (val > max ? max : val);
    }
    exports.clamp = clamp;
    function cycle(val, min, max) {
        if (val > max)
            return min;
        if (val < min)
            return max;
        return val;
    }
    exports.cycle = cycle;
    function log(x, base = Math.E) {
        return Math.log(x) / Math.log(base);
    }
    exports.log = log;
    function gcd(a, b) {
        a = Math.abs(a);
        b = Math.abs(b);
        while (b != 0) {
            [a, b] = [b, a % b];
        }
        return a;
    }
    exports.gcd = gcd;
    function lcm(a, ...rest) {
        for (const b of rest) {
            a = Math.floor((a * b) / gcd(a, b));
        }
        return a;
    }
    exports.lcm = lcm;
    exports.float = Symbol("float");
    function is_Floating(obj) {
        return (0, types_1.isObject)(obj) && exports.float in obj;
    }
    exports.is_Floating = is_Floating;
    class Fraction {
        constructor(numer, denom) {
            (0, assert_1.assert)(denom != 0, "Zero divisor");
            const div = gcd(numer, denom);
            const sgn = sign(numer) * sign(denom);
            this.numer = sgn * abs(numer) / div;
            this.denom = abs(denom) / div;
        }
        [exports.float]() {
            return this.numer / this.denom;
        }
        toString() {
            return `${this.numer}/${this.denom}`;
        }
    }
    exports.Fraction = Fraction;
    Fraction.__name__ = "Fraction";
    exports.float32_epsilon = 1.1920928955078125e-7; // IEEE-754
    function factorial(x) {
        let y = 1;
        for (let i = 2; i <= x; i++) {
            y *= i;
        }
        return y;
    }
    exports.factorial = factorial;
    function hermite(n) {
        const poly = new Array(n + 1);
        poly.fill(0);
        const fn = factorial(n);
        for (let k = 0; k <= Math.floor(n / 2); k++) {
            const c = (-1) ** k * fn / (factorial(k) * factorial(n - 2 * k)) * 2 ** (n - 2 * k);
            poly[2 * k] = c;
        }
        return poly;
    }
    exports.hermite = hermite;
    function eval_poly(poly, x) {
        const n = poly.length - 1;
        let y = 0;
        let x_n = 1;
        for (let i = n; i >= 0; i--) {
            y += x_n * poly[i];
            x_n *= x;
        }
        return y;
    }
    exports.eval_poly = eval_poly;
},
/* core/util/assert.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class AssertionError extends Error {
    }
    exports.AssertionError = AssertionError;
    AssertionError.__name__ = "AssertionError";
    class UnreachableError extends Error {
    }
    exports.UnreachableError = UnreachableError;
    UnreachableError.__name__ = "UnreachableError";
    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 assert_debug(condition, message) {
        if (typeof DEBUG !== "undefined" && DEBUG) {
            assert(condition, message);
        }
    }
    exports.assert_debug = assert_debug;
    function unreachable(msg) {
        const suffix = msg != null ? `: ${msg}` : "";
        throw new UnreachableError(`unreachable code${suffix}`);
    }
    exports.unreachable = unreachable;
},
/* core/util/arrayable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const math_1 = require(11) /* ./math */;
    const assert_1 = require(12) /* ./assert */;
    const { floor } = Math;
    function is_empty(array) {
        return array.length == 0;
    }
    exports.is_empty = is_empty;
    function is_sorted(array) {
        const n = array.length;
        if (n == 0) {
            return true;
        }
        let prev = array[0];
        for (let i = 1; i < n; i++) {
            const curr = array[i];
            if (prev <= curr) {
                prev = curr;
            }
            else {
                return false;
            }
        }
        return true;
    }
    exports.is_sorted = is_sorted;
    function copy(array) {
        if (Array.isArray(array))
            return array.slice();
        else
            return new array.constructor(array);
    }
    exports.copy = copy;
    function splice(array, start, k, ...items) {
        const 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;
        const n = len - k + items.length;
        const result = new array.constructor(n);
        let i = 0;
        for (; i < start; i++) {
            result[i] = array[i];
        }
        for (const item of items) {
            result[i++] = item;
        }
        for (let 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 index_of(array, item) {
        return array.indexOf(item);
    }
    exports.index_of = index_of;
    function includes(array, value) {
        return array.indexOf(value) !== -1;
    }
    exports.includes = includes;
    exports.contains = includes;
    function subselect(array, indices) {
        const n = indices.length;
        const result = new array.constructor(n);
        for (let i = 0; i < n; i++) {
            result[i] = array[indices[i]];
        }
        return result;
    }
    exports.subselect = subselect;
    function mul(array, coeff, output) {
        const n = array.length;
        const result = output !== null && output !== void 0 ? output : new array.constructor(n);
        for (let i = 0; i < n; i++) {
            result[i] = array[i] * coeff;
        }
        return result;
    }
    exports.mul = mul;
    function map(array, fn) {
        const n = array.length;
        const result = new array.constructor(n);
        for (let i = 0; i < n; i++) {
            result[i] = fn(array[i], i, array);
        }
        return result;
    }
    exports.map = map;
    function inplace_map(array, fn, output) {
        const n = array.length;
        const result = output !== null && output !== void 0 ? output : array;
        for (let i = 0; i < n; i++) {
            result[i] = fn(array[i], i);
        }
    }
    exports.inplace_map = inplace_map;
    function filter(array, pred) {
        const n = array.length;
        const result = new array.constructor(n);
        let k = 0;
        for (let i = 0; i < n; i++) {
            const value = array[i];
            if (pred(value, i, array))
                result[k++] = value;
        }
        return head(result, k);
    }
    exports.filter = filter;
    function reduce(array, fn, initial) {
        const n = array.length;
        if (initial === undefined && n == 0)
            throw new Error("can't reduce an empty array without an initial value");
        let value;
        let 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 sort_by(array, key) {
        const tmp = Array.from(array, (value, index) => {
            return { index, key: key(value) };
        });
        tmp.sort((left, right) => {
            const a = left.key;
            const b = right.key;
            if (a !== b) {
                if (a > b)
                    return 1;
                if (a < b)
                    return -1;
            }
            return left.index - right.index;
        });
        return map(array, (_, i) => array[tmp[i].index]);
    }
    exports.sort_by = sort_by;
    function min(iterable) {
        let result = Infinity;
        for (const value of iterable) {
            if (!isNaN(value) && value < result) {
                result = value;
            }
        }
        return result;
    }
    exports.min = min;
    function max(iterable) {
        let result = -Infinity;
        for (const value of iterable) {
            if (!isNaN(value) && value > result) {
                result = value;
            }
        }
        return result;
    }
    exports.max = max;
    function minmax(iterable) {
        let min = +Infinity;
        let max = -Infinity;
        for (const value of iterable) {
            if (!isNaN(value)) {
                if (value < min) {
                    min = value;
                }
                if (value > max) {
                    max = value;
                }
            }
        }
        return [min, max];
    }
    exports.minmax = minmax;
    function minmax2(arr, brr) {
        let a;
        let b;
        let a_min = +Infinity;
        let a_max = -Infinity;
        let b_min = +Infinity;
        let b_max = -Infinity;
        const n = Math.min(arr.length, brr.length);
        for (let 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");
        let result = array[0];
        let result_computed = key(result, 0);
        for (let i = 1, length = array.length; i < length; i++) {
            const value = array[i];
            const computed = key(value, i);
            if (computed < result_computed) {
                result = value;
                result_computed = 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");
        let result = array[0];
        let result_computed = key(result, 0);
        for (let i = 1, length = array.length; i < length; i++) {
            const value = array[i];
            const computed = key(value, i);
            if (computed > result_computed) {
                result = value;
                result_computed = computed;
            }
        }
        return result;
    }
    exports.max_by = max_by;
    function sum(array) {
        let result = 0;
        for (let i = 0, n = array.length; i < n; i++) {
            result += array[i];
        }
        return result;
    }
    exports.sum = sum;
    function cumsum(array) {
        const result = new array.constructor(array.length);
        reduce(array, (a, b, i) => result[i] = a + b, 0);
        return result;
    }
    exports.cumsum = cumsum;
    function every(iter, predicate) {
        for (const item of iter) {
            if (!predicate(item))
                return false;
        }
        return true;
    }
    exports.every = every;
    function some(iter, predicate) {
        for (const item of iter) {
            if (predicate(item))
                return true;
        }
        return false;
    }
    exports.some = some;
    function _find_index(dir) {
        return function (array, predicate) {
            const length = array.length;
            let 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) {
        const index = (0, exports.find_index)(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    exports.find = find;
    function find_last(array, predicate) {
        const index = (0, exports.find_last_index)(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    exports.find_last = find_last;
    function bisect_left_by(array, value, fn, low = 0, high = array.length) {
        (0, assert_1.assert_debug)(() => is_sorted(array));
        (0, assert_1.assert)(0 <= low && high <= array.length);
        while (low < high) {
            const mid = floor((low + high) / 2);
            if (fn(array[mid]) < value) {
                low = mid + 1;
            }
            else {
                high = mid;
            }
        }
        return low;
    }
    exports.bisect_left_by = bisect_left_by;
    function bisect_right_by(array, value, fn, low = 0, high = array.length) {
        (0, assert_1.assert_debug)(() => is_sorted(array));
        (0, assert_1.assert)(0 <= low && high <= array.length);
        while (low < high) {
            const mid = floor((low + high) / 2);
            if (fn(array[mid]) <= value) {
                low = mid + 1;
            }
            else {
                high = mid;
            }
        }
        return low;
    }
    exports.bisect_right_by = bisect_right_by;
    function bisect_left(array, value, low = 0, high) {
        return bisect_left_by(array, value, (item) => item, low, high);
    }
    exports.bisect_left = bisect_left;
    function bisect_right(array, value, low = 0, high) {
        return bisect_right_by(array, value, (item) => item, low, high);
    }
    exports.bisect_right = bisect_right;
    function binary_search(array, value) {
        const i = bisect_left(array, value);
        return i != array.length && array[i] == value ? i : null;
    }
    exports.binary_search = binary_search;
    exports.sorted_index = bisect_left;
    function bin_counts(data, bin_edges) {
        const nbins = bin_edges.length - 1;
        const counts = Array(nbins).fill(0);
        for (let i = 0; i < data.length; i++) {
            const sample = data[i];
            const index = (0, exports.sorted_index)(bin_edges, sample);
            const 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
        const n = points.length;
        const results = new Array(n);
        for (let i = 0; i < n; i++) {
            const point = points[i];
            if (isNaN(point) || x_values.length == 0) {
                results[i] = NaN;
                continue;
            }
            const 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 {
                const x0 = x_values[index];
                const y0 = y_values[index];
                const x1 = x_values[index + 1];
                const 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) {
        const slope = (y1 - y0) / (x1 - x0);
        let 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;
        if (intervals.length == 1)
            // Implies point == intervals[0]
            return 0;
        let leftEdgeIndex = 0;
        let rightEdgeIndex = intervals.length - 1;
        while (rightEdgeIndex - leftEdgeIndex != 1) {
            const 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) {
        const span = end - start;
        return map(array, (x) => (x - start) / span);
    }
    exports.norm = norm;
},
/* core/has_props.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const signaling_1 = require(15) /* ./signaling */;
    const refs_1 = require(17) /* ./util/refs */;
    const p = tslib_1.__importStar(require(18) /* ./properties */);
    const k = tslib_1.__importStar(require(21) /* ./kinds */);
    const assert_1 = require(12) /* ./util/assert */;
    const string_1 = require(40) /* ./util/string */;
    const object_1 = require(9) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    const eq_1 = require(26) /* ./util/eq */;
    const serialization_1 = require(32) /* ./serialization */;
    const events_1 = require(41) /* ../document/events */;
    const eq_2 = require(26) /* ./util/eq */;
    const pretty_1 = require(42) /* ./util/pretty */;
    const cloneable_1 = require(31) /* ./util/cloneable */;
    const kinds = tslib_1.__importStar(require(21) /* ./kinds */);
    const vectorization_1 = require(28) /* ./vectorization */;
    const patching_1 = require(43) /* ./patching */;
    const _qualified_names = new WeakMap();
    class HasProps extends (0, signaling_1.Signalable)() {
        get is_syncable() {
            return true;
        }
        get type() {
            return this.constructor.__qualified__;
        }
        static get __qualified__() {
            let qualified = _qualified_names.get(this);
            if (qualified == null) {
                const { __module__, __name__ } = this;
                qualified = __module__ != null ? `${__module__}.${__name__}` : __name__;
                _qualified_names.set(this, qualified);
            }
            return qualified;
        }
        static set __qualified__(qualified) {
            _qualified_names.set(this, qualified);
        }
        get [Symbol.toStringTag]() {
            return this.constructor.__qualified__;
        }
        static _fix_default(default_value, _attr) {
            if (default_value === undefined || default_value === p.unset)
                return () => p.unset;
            else if ((0, types_1.isFunction)(default_value))
                return default_value;
            else if ((0, types_1.isPrimitive)(default_value))
                return () => default_value;
            else {
                const cloner = new cloneable_1.Cloner();
                return () => cloner.clone(default_value);
            }
        }
        // TODO: don't use Partial<>, but exclude inherited properties
        static define(obj) {
            for (const [name, prop] of (0, object_1.entries)((0, types_1.isFunction)(obj) ? obj(kinds) : obj)) {
                if (name in this.prototype._props)
                    throw new Error(`attempted to redefine property '${this.prototype.type}.${name}'`);
                if (name in this.prototype)
                    throw new Error(`attempted to redefine attribute '${this.prototype.type}.${name}'`);
                Object.defineProperty(this.prototype, name, {
                    // XXX: don't use tail calls in getters/setters due to https://bugs.webkit.org/show_bug.cgi?id=164306
                    get() {
                        const value = this.properties[name].get_value();
                        return value;
                    },
                    set(value) {
                        this.setv({ [name]: value });
                        return this;
                    },
                    configurable: false,
                    enumerable: true,
                });
                const [type, default_value, options = {}] = prop;
                const refined_prop = {
                    type,
                    default_value: this._fix_default(default_value, name),
                    options,
                };
                this.prototype._props = Object.assign(Object.assign({}, this.prototype._props), { [name]: refined_prop });
            }
        }
        static internal(obj) {
            const _object = {};
            for (const [name, prop] of (0, object_1.entries)((0, types_1.isFunction)(obj) ? obj(kinds) : obj)) {
                const [type, default_value, options = {}] = prop;
                _object[name] = [type, default_value, Object.assign(Object.assign({}, options), { internal: true })];
            }
            this.define(_object);
        }
        static mixins(defs) {
            function rename(prefix, mixin) {
                const result = {};
                for (const [name, prop] of (0, object_1.entries)(mixin)) {
                    result[prefix + name] = prop;
                }
                return result;
            }
            const mixin_defs = {};
            const mixins = [];
            for (const def of (0, types_1.isArray)(defs) ? defs : [defs]) {
                if ((0, types_1.isArray)(def)) {
                    const [prefix, mixin] = def;
                    (0, object_1.extend)(mixin_defs, rename(prefix, mixin));
                    mixins.push([prefix, mixin]);
                }
                else {
                    const mixin = def;
                    (0, object_1.extend)(mixin_defs, mixin);
                    mixins.push(["", mixin]);
                }
            }
            this.define(mixin_defs);
            this.prototype._mixins = [...this.prototype._mixins, ...mixins];
        }
        static override(obj) {
            for (const [name, prop] of (0, object_1.entries)(obj)) {
                const default_value = this._fix_default(prop, name);
                if (!(name in this.prototype._props))
                    throw new Error(`attempted to override nonexistent '${this.prototype.type}.${name}'`);
                const value = this.prototype._props[name];
                const props = Object.assign({}, this.prototype._props);
                props[name] = Object.assign(Object.assign({}, value), { default_value });
                this.prototype._props = props;
            }
        }
        static toString() {
            return this.__qualified__;
        }
        toString() {
            return `${this.type}(${this.id})`;
        }
        property(name) {
            if (name in this.properties)
                return this.properties[name];
            else
                throw new Error(`unknown property ${this.type}.${name}`);
        }
        get attributes() {
            const attrs = {};
            for (const prop of this) {
                if (!prop.is_unset)
                    attrs[prop.attr] = prop.get_value();
            }
            return attrs;
        }
        [cloneable_1.clone](cloner) {
            const attrs = new Map();
            for (const prop of this) {
                if (prop.dirty) {
                    attrs.set(prop.attr, cloner.clone(prop.get_value()));
                }
            }
            return new this.constructor(attrs);
        }
        [eq_2.equals](that, cmp) {
            for (const p0 of this) {
                const p1 = that.property(p0.attr);
                if (!cmp.eq(p0.get_value(), p1.get_value()))
                    return false;
            }
            return true;
        }
        [pretty_1.pretty](printer) {
            const T = printer.token;
            const items = [];
            for (const prop of this) {
                if (prop.dirty) {
                    const value = prop.get_value();
                    items.push(`${prop.attr}${T(":")} ${printer.to_string(value)}`);
                }
            }
            const cls = this.constructor.__qualified__;
            return `${cls}${T("(")}${T("{")}${items.join(`${T(",")} `)}${T("}")}${T(")")}`;
        }
        [serialization_1.serialize](serializer) {
            const ref = this.ref();
            serializer.add_ref(this, ref);
            const attributes = {};
            for (const prop of this) {
                if (prop.syncable && (serializer.include_defaults || prop.dirty) && !(prop.readonly && prop.is_unset)) {
                    const value = prop.get_value();
                    attributes[prop.attr] = serializer.encode(value);
                }
            }
            const { type: name, id } = this;
            const rep = { type: "object", name, id };
            return (0, object_1.is_empty)(attributes) ? rep : Object.assign(Object.assign({}, rep), { attributes });
        }
        constructor(attrs = {}) {
            super();
            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.streaming = new signaling_1.Signal0(this, "streaming");
            this.patching = new signaling_1.Signal(this, "patching");
            this.properties = {};
            this._watchers = new WeakMap();
            this._pending = false;
            this._changing = false;
            const deferred = (0, types_1.isPlainObject)(attrs) && "id" in attrs;
            this.id = deferred ? attrs.id : (0, string_1.unique_id)();
            for (const [name, { type, default_value, options }] of (0, object_1.entries)(this._props)) {
                let property;
                if (type instanceof p.PropertyAlias) {
                    Object.defineProperty(this.properties, name, {
                        get: () => this.properties[type.attr],
                        configurable: false,
                        enumerable: false,
                    });
                }
                else {
                    if (type instanceof k.Kind)
                        property = new p.PrimitiveProperty(this, name, type, default_value, options);
                    else
                        property = new type(this, name, k.Any, default_value, options);
                    this.properties[name] = property;
                }
            }
            // 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 (deferred) {
                (0, assert_1.assert)((0, object_1.keys)(attrs).length == 1, "'id' cannot be used together with property initializers");
            }
            else {
                const vals = attrs instanceof Map ? attrs : new object_1.Dict(attrs);
                this.initialize_props(vals);
                this.finalize();
                this.connect_signals();
            }
        }
        initialize_props(vals) {
            const visited = new Set();
            for (const prop of this) {
                const val = vals.get(prop.attr);
                prop.initialize(val);
                visited.add(prop.attr);
            }
            for (const attr of vals.keys()) {
                if (!visited.has(attr))
                    this.property(attr);
            }
        }
        finalize() {
            this.initialize();
        }
        initialize() { }
        assert_initialized() {
            for (const prop of this) {
                if (prop.syncable && !prop.readonly)
                    prop.get_value();
            }
        }
        connect_signals() {
            for (const prop of this) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                    continue;
                if (prop.is_unset)
                    continue;
                const value = prop.get_value();
                if (value.transform != null)
                    this.connect(value.transform.change, () => this.transformchange.emit());
                if ((0, vectorization_1.isExpr)(value))
                    this.connect(value.expr.change, () => this.exprchange.emit());
            }
        }
        disconnect_signals() {
            signaling_1.Signal.disconnect_receiver(this);
        }
        destroy() {
            this.disconnect_signals();
            this.destroyed.emit();
        }
        // Create a new model with exact attribute values to this one, but new identity.
        clone() {
            const cloner = new cloneable_1.Cloner();
            return cloner.clone(this);
        }
        _clear_watchers() {
            this._watchers = new WeakMap();
        }
        changed_for(obj) {
            const 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.
        _setv(changes, options) {
            var _b;
            // Extract attributes and options.
            const check_eq = options.check_eq;
            const changed = new Set();
            const changing = this._changing;
            this._changing = true;
            for (const [prop, value] of changes) {
                if (check_eq === false || prop.is_unset || !(0, eq_1.is_equal)(prop.get_value(), value)) {
                    prop.set_value(value);
                    changed.add(prop);
                }
            }
            // Trigger all relevant attribute changes.
            if (changed.size > 0) {
                this._clear_watchers();
                this._pending = true;
            }
            for (const prop of changed) {
                prop.change.emit();
            }
            // You might be wondering why there's a `while` loop here. Changes can
            // be recursively nested within `"change"` events.
            if (!changing) {
                if (!((_b = options.no_change) !== null && _b !== void 0 ? _b : false)) {
                    while (this._pending) {
                        this._pending = false;
                        this.change.emit();
                    }
                }
                this._pending = false;
                this._changing = false;
            }
            return changed;
        }
        setv(changed_attrs, options = {}) {
            var _b, _c;
            const changes = (0, object_1.entries)(changed_attrs);
            if (changes.length == 0)
                return;
            if ((_b = options.silent) !== null && _b !== void 0 ? _b : false) {
                this._clear_watchers();
                for (const [attr, value] of changes) {
                    this.properties[attr].set_value(value);
                }
                return;
            }
            const changed = new Map();
            const previous = new Map();
            for (const [attr, value] of changes) {
                const prop = this.properties[attr];
                changed.set(prop, value);
                previous.set(prop, prop.is_unset ? undefined : prop.get_value());
            }
            const updated = this._setv(changed, options);
            const { document } = this;
            if (document != null) {
                const changed = [];
                for (const [prop, value] of previous) {
                    if (updated.has(prop))
                        changed.push([prop, value, prop.get_value()]);
                }
                for (const [prop, old_value, new_value] of changed) {
                    if (prop.may_have_refs && this._needs_invalidate(old_value, new_value)) {
                        document._invalidate_all_models();
                        break;
                    }
                }
                if ((_c = options.sync) !== null && _c !== void 0 ? _c : true)
                    this._push_changes(changed);
            }
        }
        ref() {
            return { id: this.id };
        }
        *[Symbol.iterator]() {
            yield* (0, object_1.values)(this.properties);
        }
        *syncable_properties() {
            for (const prop of this) {
                if (prop.syncable)
                    yield prop;
            }
        }
        // add all references from 'v' to 'result', if recurse
        // is true then descend into refs, if false only
        // descend into non-refs
        static _value_record_references(value, refs, options) {
            if (!(0, types_1.isObject)(value) || !(0, refs_1.may_have_refs)(value)) {
                return;
            }
            const { recursive } = options;
            if (value instanceof _a) {
                if (!refs.has(value)) {
                    refs.add(value);
                    if (recursive) {
                        for (const prop of value.syncable_properties()) {
                            if (!prop.is_unset && prop.may_have_refs) {
                                const value = prop.get_value();
                                _a._value_record_references(value, refs, { recursive });
                            }
                        }
                    }
                }
            }
            else if ((0, types_1.isIterable)(value)) {
                for (const elem of value) {
                    _a._value_record_references(elem, refs, { recursive });
                }
            }
            else if ((0, types_1.isPlainObject)(value)) {
                for (const elem of (0, object_1.values)(value)) {
                    _a._value_record_references(elem, refs, { recursive });
                }
            }
        }
        references() {
            const refs = new Set();
            _a._value_record_references(this, refs, { recursive: true });
            return refs;
        }
        _doc_attached() { }
        _doc_detached() { }
        attach_document(doc) {
            // This should only be called by the Document implementation to set the document field
            if (this.document != null) {
                if (this.document == doc)
                    return;
                else
                    throw new Error("models must be owned by only a single document");
            }
            this.document = doc;
            this._doc_attached();
        }
        detach_document() {
            // This should only be called by the Document implementation to unset the document field
            this._doc_detached();
            this.document = null;
        }
        _needs_invalidate(old_value, new_value) {
            const new_refs = new Set();
            _a._value_record_references(new_value, new_refs, { recursive: false });
            const old_refs = new Set();
            _a._value_record_references(old_value, old_refs, { recursive: false });
            for (const new_id of new_refs) {
                if (!old_refs.has(new_id))
                    return true;
            }
            for (const old_id of old_refs) {
                if (!new_refs.has(old_id))
                    return true;
            }
            return false;
        }
        _push_changes(changes) {
            if (!this.is_syncable)
                return;
            const { document } = this;
            if (document == null)
                return;
            const events = [];
            for (const [prop, , new_value] of changes) {
                if (prop.syncable)
                    events.push(new events_1.ModelChangedEvent(document, this, prop.attr, new_value));
            }
            if (events.length != 0) {
                let event;
                if (events.length == 1)
                    [event] = events;
                else
                    event = new events_1.DocumentEventBatch(document, events);
                document._trigger_on_change(event);
            }
        }
        on_change(properties, fn) {
            for (const property of (0, types_1.isArray)(properties) ? properties : [properties]) {
                this.connect(property.change, fn);
            }
        }
        stream_to(prop, new_data, rollover, { sync } = {}) {
            const data = prop.get_value();
            (0, patching_1.stream_to_columns)(data, new_data, rollover);
            this._clear_watchers();
            prop.set_value(data);
            this.streaming.emit();
            if (this.document != null && (sync !== null && sync !== void 0 ? sync : true)) {
                const event = new events_1.ColumnsStreamedEvent(this.document, this, prop.attr, new_data, rollover);
                this.document._trigger_on_change(event);
            }
        }
        patch_to(prop, patches, { sync } = {}) {
            const data = prop.get_value();
            const patched = (0, patching_1.patch_to_columns)(data, patches);
            this._clear_watchers();
            prop.set_value(data);
            this.patching.emit([...patched]);
            if (this.document != null && (sync !== null && sync !== void 0 ? sync : true)) {
                const event = new events_1.ColumnsPatchedEvent(this.document, this, prop.attr, patches);
                this.document._trigger_on_change(event);
            }
        }
    }
    exports.HasProps = HasProps;
    _a = HasProps;
    (() => {
        _a.prototype._props = {};
        _a.prototype._mixins = [];
    })();
},
/* core/signaling.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    // Based on https://github.com/phosphorjs/phosphor/blob/master/packages/signaling/src/index.ts
    const defer_1 = require(16) /* ./util/defer */;
    const array_1 = require(10) /* ./util/array */;
    class Signal {
        constructor(sender, name) {
            this.sender = sender;
            this.name = name;
        }
        connect(slot, context = null) {
            if (!exports.receivers_for_sender.has(this.sender)) {
                exports.receivers_for_sender.set(this.sender, []);
            }
            const receivers = exports.receivers_for_sender.get(this.sender);
            if (find_connection(receivers, this, slot, context) != null) {
                return false;
            }
            const receiver = context !== null && context !== void 0 ? context : slot;
            if (!senders_for_receiver.has(receiver)) {
                senders_for_receiver.set(receiver, []);
            }
            const senders = senders_for_receiver.get(receiver);
            const connection = { signal: this, slot, context };
            receivers.push(connection);
            senders.push(connection);
            return true;
        }
        disconnect(slot, context = null) {
            const receivers = exports.receivers_for_sender.get(this.sender);
            if (receivers == null || receivers.length === 0) {
                return false;
            }
            const connection = find_connection(receivers, this, slot, context);
            if (connection == null) {
                return false;
            }
            const receiver = context !== null && context !== void 0 ? context : slot;
            const senders = senders_for_receiver.get(receiver);
            connection.signal = null;
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
            return true;
        }
        emit(args) {
            var _a;
            const receivers = (_a = exports.receivers_for_sender.get(this.sender)) !== null && _a !== void 0 ? _a : [];
            for (const { signal, slot, context } of receivers) {
                if (signal === this) {
                    slot.call(context, args, this.sender);
                }
            }
        }
    }
    exports.Signal = Signal;
    Signal.__name__ = "Signal";
    class Signal0 extends Signal {
        emit() {
            super.emit(undefined);
        }
    }
    exports.Signal0 = Signal0;
    Signal0.__name__ = "Signal0";
    (function (Signal) {
        function disconnect_between(sender, receiver) {
            const receivers = exports.receivers_for_sender.get(sender);
            if (receivers == null || receivers.length === 0)
                return;
            const senders = senders_for_receiver.get(receiver);
            if (senders == null || senders.length === 0)
                return;
            for (const connection of senders) {
                if (connection.signal == null)
                    return;
                if (connection.signal.sender === sender)
                    connection.signal = null;
            }
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
        }
        Signal.disconnect_between = disconnect_between;
        function disconnect_sender(sender) {
            var _a;
            const receivers = exports.receivers_for_sender.get(sender);
            if (receivers == null || receivers.length === 0)
                return;
            for (const connection of receivers) {
                if (connection.signal == null)
                    return;
                const receiver = (_a = connection.context) !== null && _a !== void 0 ? _a : connection.slot;
                connection.signal = null;
                schedule_cleanup(senders_for_receiver.get(receiver));
            }
            schedule_cleanup(receivers);
        }
        Signal.disconnect_sender = disconnect_sender;
        function disconnect_receiver(receiver, slot, except_senders) {
            const senders = senders_for_receiver.get(receiver);
            if (senders == null || senders.length === 0)
                return;
            for (const connection of senders) {
                if (connection.signal == null)
                    return;
                if (slot != null && connection.slot != slot)
                    continue;
                const sender = connection.signal.sender;
                if (except_senders != null && except_senders.has(sender))
                    continue;
                connection.signal = null;
                schedule_cleanup(exports.receivers_for_sender.get(sender));
            }
            schedule_cleanup(senders);
        }
        Signal.disconnect_receiver = disconnect_receiver;
        function disconnect_all(obj) {
            const receivers = exports.receivers_for_sender.get(obj);
            if (receivers != null && receivers.length !== 0) {
                for (const connection of receivers) {
                    connection.signal = null;
                }
                schedule_cleanup(receivers);
            }
            const senders = senders_for_receiver.get(obj);
            if (senders != null && senders.length !== 0) {
                for (const connection of senders) {
                    connection.signal = null;
                }
                schedule_cleanup(senders);
            }
        }
        Signal.disconnect_all = disconnect_all;
    })(Signal || (exports.Signal = Signal = {}));
    function Signalable() {
        return class {
            connect(signal, slot) {
                return signal.connect(slot, this);
            }
            disconnect(signal, slot) {
                return signal.disconnect(slot, this);
            }
        };
    }
    exports.Signalable = Signalable;
    /** @internal */
    exports.receivers_for_sender = new WeakMap();
    const senders_for_receiver = new WeakMap();
    function find_connection(conns, signal, slot, context) {
        return (0, array_1.find)(conns, conn => conn.signal === signal && conn.slot === slot && conn.context === context);
    }
    const dirty_set = new Set();
    function schedule_cleanup(connections) {
        if (dirty_set.size === 0) {
            (async () => {
                await (0, defer_1.defer)();
                cleanup_dirty_set();
            })();
        }
        dirty_set.add(connections);
    }
    function cleanup_dirty_set() {
        for (const connections of dirty_set) {
            (0, array_1.remove_by)(connections, (connection) => connection.signal == null);
        }
        dirty_set.clear();
    }
},
/* core/util/defer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const channel = new MessageChannel();
    const tasks = new Map();
    channel.port1.onmessage = (event) => {
        const handle = event.data;
        const fn = tasks.get(handle);
        if (fn != null) {
            try {
                fn();
            }
            finally {
                tasks.delete(handle);
            }
        }
    };
    let counter = 1;
    function defer() {
        return new Promise((resolve) => {
            const handle = counter++;
            tasks.set(handle, resolve);
            channel.port2.postMessage(handle);
        });
    }
    exports.defer = defer;
    function delay(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
    exports.delay = delay;
    async function poll(fn, interval = 50, timeout = 500) {
        while (!fn() && timeout >= 0) {
            await delay(interval);
            timeout -= interval;
        }
    }
    exports.poll = poll;
    function paint() {
        return new Promise((resolve) => {
            requestAnimationFrame(() => resolve());
        });
    }
    exports.paint = paint;
    function idle() {
        return new Promise((resolve) => {
            requestIdleCallback(() => resolve());
        });
    }
    exports.idle = idle;
},
/* core/util/refs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ./types */;
    function is_ref(obj) {
        return (0, types_1.isPlainObject)(obj) && "id" in obj && !("type" in obj);
    }
    exports.is_ref = is_ref;
    exports.has_refs = Symbol("has_refs");
    function _is_HasRefs(v) {
        return exports.has_refs in v;
    }
    exports._is_HasRefs = _is_HasRefs;
    function is_HasRefs(v) {
        return (0, types_1.isObject)(v) && _is_HasRefs(v);
    }
    exports.is_HasRefs = is_HasRefs;
    function may_have_refs(obj) {
        if (_is_HasRefs(obj)) {
            return obj[exports.has_refs];
        }
        const type = obj.constructor;
        if (_is_HasRefs(type)) {
            return type[exports.has_refs];
        }
        return true;
    }
    exports.may_have_refs = may_have_refs;
},
/* core/properties.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    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 = void 0;
    const tslib_1 = require(1) /* tslib */;
    const signaling_1 = require(15) /* ./signaling */;
    const logging_1 = require(19) /* ./logging */;
    const enums = tslib_1.__importStar(require(20) /* ./enums */);
    const types_1 = require(24) /* ./types */;
    const array_1 = require(10) /* ./util/array */;
    const arrayable_1 = require(13) /* ./util/arrayable */;
    const math_1 = require(11) /* ./util/math */;
    const color_1 = require(22) /* ./util/color */;
    const platform_1 = require(27) /* ./util/platform */;
    const types_2 = require(8) /* ./util/types */;
    const vectorization_1 = require(28) /* ./vectorization */;
    const settings_1 = require(29) /* ./settings */;
    const ndarray_1 = require(30) /* ./util/ndarray */;
    const diagnostics_1 = require(38) /* ./diagnostics */;
    const assert_1 = require(12) /* ./util/assert */;
    const serialization_1 = require(32) /* ./serialization */;
    const uniforms_1 = require(39) /* ./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;
    let global_theme = null;
    function use_theme(theme = null) {
        global_theme = theme;
    }
    exports.use_theme = use_theme;
    exports.unset = Symbol("unset");
    class UnsetValueError extends Error {
    }
    exports.UnsetValueError = UnsetValueError;
    UnsetValueError.__name__ = "UnsetValueError";
    class Property {
        get syncable() {
            return !this.internal;
        }
        get is_unset() {
            return this._value === exports.unset;
        }
        get initialized() {
            return this._initialized;
        }
        initialize(initial_value = exports.unset) {
            if (this._initialized)
                throw new Error("already initialized");
            let attr_value = exports.unset;
            if (initial_value !== exports.unset) {
                attr_value = initial_value;
                this._dirty = true;
            }
            else {
                const value = this._default_override();
                if (value !== exports.unset)
                    attr_value = value;
                else {
                    let themed = false;
                    if (global_theme != null) {
                        const value = global_theme.get(this.obj, this.attr);
                        if (value !== undefined) {
                            attr_value = value;
                            themed = true;
                        }
                    }
                    if (!themed) {
                        attr_value = this.default_value(this.obj);
                    }
                }
            }
            if (attr_value !== exports.unset)
                this._update(attr_value);
            else
                this._value = exports.unset;
            this._initialized = true;
        }
        get_value() {
            if (this._value !== exports.unset)
                return this._value;
            else
                throw new UnsetValueError(`${this.obj}.${this.attr} is unset`);
        }
        set_value(val) {
            if (!this._initialized)
                this.initialize(val);
            else {
                this._update(val);
                this._dirty = true;
            }
            diagnostics_1.diagnostics.report(this);
        }
        // abstract _intrinsic_default(): T
        _default_override() {
            return exports.unset;
        }
        get dirty() {
            return this._dirty;
        }
        constructor(obj, attr, kind, default_value, options = {}) {
            var _a, _b;
            this._value = exports.unset;
            this._initialized = false;
            this._dirty = false;
            this.obj = obj;
            this.attr = attr;
            this.kind = kind;
            this.default_value = default_value;
            this.change = new signaling_1.Signal0(this.obj, "change");
            this.internal = (_a = options.internal) !== null && _a !== void 0 ? _a : false;
            this.readonly = (_b = options.readonly) !== null && _b !== void 0 ? _b : false;
            this.convert = options.convert;
            this.on_update = options.on_update;
            this.may_have_refs = kind.may_have_refs();
        }
        //protected abstract _update(attr_value: T): void
        _update(attr_value) {
            var _a;
            this.validate(attr_value);
            if (this.convert != null) {
                const converted = this.convert(attr_value, this.obj);
                if (converted !== undefined)
                    attr_value = converted;
            }
            this._value = attr_value;
            (_a = this.on_update) === null || _a === void 0 ? void 0 : _a.call(this, attr_value, this.obj);
        }
        toString() {
            /*${this.name}*/
            return `Prop(${this.obj}.${this.attr}, value: ${valueToString(this._value)})`;
        }
        // ----- customizable policies
        normalize(values) {
            return values;
        }
        validate(value) {
            if (!this.valid(value))
                throw new Error(`${this.obj}.${this.attr} given invalid value: ${valueToString(value)}`);
        }
        valid(value) {
            return this.kind.valid(value);
        }
    }
    exports.Property = Property;
    Property.__name__ = "Property";
    class PropertyAlias {
        constructor(attr) {
            this.attr = attr;
        }
    }
    exports.PropertyAlias = PropertyAlias;
    PropertyAlias.__name__ = "PropertyAlias";
    function Alias(attr) {
        return new PropertyAlias(attr);
    }
    exports.Alias = Alias;
    //
    // Primitive Properties
    //
    class PrimitiveProperty extends Property {
    }
    exports.PrimitiveProperty = PrimitiveProperty;
    PrimitiveProperty.__name__ = "PrimitiveProperty";
    class Font extends PrimitiveProperty {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.Font = Font;
    Font.__name__ = "Font";
    //
    // DataSpec properties
    //
    class ScalarSpec extends Property {
        constructor() {
            super(...arguments);
            this._value = exports.unset;
        }
        get_value() {
            if (this._value !== exports.unset)
                return this._value;
            else
                throw new Error(`${this.obj}.${this.attr} is unset`);
        }
        _update(attr_value) {
            if (isSpec(attr_value))
                this._value = attr_value;
            else {
                this._value = { value: attr_value }; // Value<T>
            }
            if ((0, types_2.isPlainObject)(this._value)) {
                const { _value } = this;
                this._value[serialization_1.serialize] = (serializer) => {
                    const { value, field, expr, transform, units } = _value;
                    return serializer.encode_struct((() => {
                        if (value !== undefined)
                            return { type: "value", value, transform, units };
                        else if (field !== undefined)
                            return { type: "field", field, transform, units };
                        else
                            return { type: "expr", expr, transform, units };
                    })());
                };
            }
            if ((0, vectorization_1.isValue)(this._value))
                this.validate(this._value.value);
        }
        materialize(value) {
            return value;
        }
        scalar(value, n) {
            return new uniforms_1.UniformScalar(value, n);
        }
        uniform(source) {
            var _a;
            const obj = this.get_value();
            const n = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            if ((0, vectorization_1.isExpr)(obj)) {
                const { expr, transform } = obj;
                let result = expr.compute(source);
                if (transform != null)
                    result = transform.compute(result);
                result = this.materialize(result);
                return this.scalar(result, n);
            }
            else {
                const { value, transform } = obj;
                let result = value;
                if (transform != null)
                    result = transform.compute(result);
                result = this.materialize(result);
                return this.scalar(result, n);
            }
        }
    }
    exports.ScalarSpec = ScalarSpec;
    ScalarSpec.__name__ = "ScalarSpec";
    class AnyScalar extends ScalarSpec {
    }
    exports.AnyScalar = AnyScalar;
    AnyScalar.__name__ = "AnyScalar";
    class ColorScalar extends ScalarSpec {
    }
    exports.ColorScalar = ColorScalar;
    ColorScalar.__name__ = "ColorScalar";
    class NumberScalar extends ScalarSpec {
    }
    exports.NumberScalar = NumberScalar;
    NumberScalar.__name__ = "NumberScalar";
    class StringScalar extends ScalarSpec {
    }
    exports.StringScalar = StringScalar;
    StringScalar.__name__ = "StringScalar";
    class NullStringScalar extends ScalarSpec {
    }
    exports.NullStringScalar = NullStringScalar;
    NullStringScalar.__name__ = "NullStringScalar";
    class ArrayScalar extends ScalarSpec {
    }
    exports.ArrayScalar = ArrayScalar;
    ArrayScalar.__name__ = "ArrayScalar";
    class LineJoinScalar extends ScalarSpec {
    }
    exports.LineJoinScalar = LineJoinScalar;
    LineJoinScalar.__name__ = "LineJoinScalar";
    class LineCapScalar extends ScalarSpec {
    }
    exports.LineCapScalar = LineCapScalar;
    LineCapScalar.__name__ = "LineCapScalar";
    class LineDashScalar extends ScalarSpec {
    }
    exports.LineDashScalar = LineDashScalar;
    LineDashScalar.__name__ = "LineDashScalar";
    class FontScalar extends ScalarSpec {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.FontScalar = FontScalar;
    FontScalar.__name__ = "FontScalar";
    class FontSizeScalar extends ScalarSpec {
    }
    exports.FontSizeScalar = FontSizeScalar;
    FontSizeScalar.__name__ = "FontSizeScalar";
    class FontStyleScalar extends ScalarSpec {
    }
    exports.FontStyleScalar = FontStyleScalar;
    FontStyleScalar.__name__ = "FontStyleScalar";
    class TextAlignScalar extends ScalarSpec {
    }
    exports.TextAlignScalar = TextAlignScalar;
    TextAlignScalar.__name__ = "TextAlignScalar";
    class TextBaselineScalar extends ScalarSpec {
    }
    exports.TextBaselineScalar = TextBaselineScalar;
    TextBaselineScalar.__name__ = "TextBaselineScalar";
    class VectorSpec extends Property {
        constructor() {
            super(...arguments);
            this._value = exports.unset;
        }
        get_value() {
            if (this._value !== exports.unset)
                return this._value;
            else
                throw new Error(`${this.obj}.${this.attr} is unset`);
        }
        _update(attr_value) {
            if (isSpec(attr_value))
                this._value = attr_value;
            else
                this._value = { value: attr_value }; // Value<T>
            if ((0, types_2.isPlainObject)(this._value)) {
                const { _value } = this;
                this._value[serialization_1.serialize] = (serializer) => {
                    const { value, field, expr, transform, units } = _value;
                    return serializer.encode_struct((() => {
                        if (value !== undefined)
                            return { type: "value", value, transform, units };
                        else if (field !== undefined)
                            return { type: "field", field, transform, units };
                        else
                            return { type: "expr", expr, transform, units };
                    })());
                };
            }
            if ((0, vectorization_1.isValue)(this._value))
                this.validate(this._value.value);
        }
        materialize(value) {
            return value;
        }
        v_materialize(values) {
            return values;
        }
        scalar(value, n) {
            return new uniforms_1.UniformScalar(value, n);
        }
        vector(values) {
            return new uniforms_1.UniformVector(values);
        }
        uniform(source) {
            var _a;
            const obj = this.get_value();
            const n = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            if ((0, vectorization_1.isField)(obj)) {
                const { field, transform } = obj;
                let 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 ((0, vectorization_1.isExpr)(obj)) {
                const { expr, transform } = obj;
                let array = expr.v_compute(source);
                if (transform != null)
                    array = transform.v_compute(array);
                array = this.v_materialize(array);
                return this.vector(array);
            }
            else if ((0, vectorization_1.isValue)(obj)) {
                const { value, transform } = obj;
                let result = value;
                if (transform != null)
                    result = transform.compute(result);
                result = this.materialize(result);
                return this.scalar(result, n);
            }
            else
                (0, assert_1.unreachable)();
        }
        array(source) {
            var _a;
            let array;
            const length = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            const obj = this.get_value();
            if ((0, vectorization_1.isField)(obj)) {
                const { field } = obj;
                const column = source.get_column(field);
                if (column != null)
                    array = this.normalize(column);
                else {
                    logging_1.logger.warn(`attempted to retrieve property array for nonexistent field '${field}'`);
                    const missing = new Float64Array(length);
                    missing.fill(NaN);
                    array = missing;
                }
            }
            else if ((0, vectorization_1.isExpr)(obj)) {
                const { expr } = obj;
                array = this.normalize(expr.v_compute(source));
            }
            else {
                const value = this.normalize([obj.value])[0];
                if ((0, types_2.isNumber)(value)) {
                    const values = new Float64Array(length);
                    values.fill(value);
                    array = values;
                }
                else
                    array = (0, array_1.repeat)(value, length);
            }
            const { transform } = obj;
            if (transform != null)
                array = transform.v_compute(array);
            return array;
        }
    }
    exports.VectorSpec = VectorSpec;
    VectorSpec.__name__ = "VectorSpec";
    class DataSpec extends VectorSpec {
    }
    exports.DataSpec = DataSpec;
    DataSpec.__name__ = "DataSpec";
    class UnitsSpec extends VectorSpec {
        constructor() {
            super(...arguments);
            this._value = exports.unset;
        }
        _update(attr_value) {
            super._update(attr_value);
            if (this._value !== exports.unset) {
                const { units } = this._value;
                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}`);
                }
            }
        }
        get units() {
            var _a;
            return this._value !== exports.unset ? (_a = this._value.units) !== null && _a !== void 0 ? _a : this.default_units : this.default_units;
        }
        set units(units) {
            if (this._value !== exports.unset) {
                if (units != this.default_units)
                    this._value.units = units;
                else
                    delete this._value.units;
            }
            else
                throw new Error(`${this.obj}.${this.attr} is unset`);
        }
    }
    exports.UnitsSpec = UnitsSpec;
    UnitsSpec.__name__ = "UnitsSpec";
    class NumberUnitsSpec extends UnitsSpec {
        array(source) {
            return new Float64Array(super.array(source));
        }
    }
    exports.NumberUnitsSpec = NumberUnitsSpec;
    NumberUnitsSpec.__name__ = "NumberUnitsSpec";
    class BaseCoordinateSpec extends DataSpec {
    }
    exports.BaseCoordinateSpec = BaseCoordinateSpec;
    BaseCoordinateSpec.__name__ = "BaseCoordinateSpec";
    class CoordinateSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSpec = CoordinateSpec;
    CoordinateSpec.__name__ = "CoordinateSpec";
    class CoordinateSeqSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSeqSpec = CoordinateSeqSpec;
    CoordinateSeqSpec.__name__ = "CoordinateSeqSpec";
    class CoordinateSeqSeqSeqSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSeqSeqSeqSpec = CoordinateSeqSeqSeqSpec;
    CoordinateSeqSeqSeqSpec.__name__ = "CoordinateSeqSeqSeqSpec";
    class XCoordinateSpec extends CoordinateSpec {
        constructor() {
            super(...arguments);
            this.dimension = "x";
        }
    }
    exports.XCoordinateSpec = XCoordinateSpec;
    XCoordinateSpec.__name__ = "XCoordinateSpec";
    class YCoordinateSpec extends CoordinateSpec {
        constructor() {
            super(...arguments);
            this.dimension = "y";
        }
    }
    exports.YCoordinateSpec = YCoordinateSpec;
    YCoordinateSpec.__name__ = "YCoordinateSpec";
    class XCoordinateSeqSpec extends CoordinateSeqSpec {
        constructor() {
            super(...arguments);
            this.dimension = "x";
        }
    }
    exports.XCoordinateSeqSpec = XCoordinateSeqSpec;
    XCoordinateSeqSpec.__name__ = "XCoordinateSeqSpec";
    class YCoordinateSeqSpec extends CoordinateSeqSpec {
        constructor() {
            super(...arguments);
            this.dimension = "y";
        }
    }
    exports.YCoordinateSeqSpec = YCoordinateSeqSpec;
    YCoordinateSeqSpec.__name__ = "YCoordinateSeqSpec";
    class XCoordinateSeqSeqSeqSpec extends CoordinateSeqSeqSeqSpec {
        constructor() {
            super(...arguments);
            this.dimension = "x";
        }
    }
    exports.XCoordinateSeqSeqSeqSpec = XCoordinateSeqSeqSeqSpec;
    XCoordinateSeqSeqSeqSpec.__name__ = "XCoordinateSeqSeqSeqSpec";
    class YCoordinateSeqSeqSeqSpec extends CoordinateSeqSeqSeqSpec {
        constructor() {
            super(...arguments);
            this.dimension = "y";
        }
    }
    exports.YCoordinateSeqSeqSeqSpec = YCoordinateSeqSeqSeqSpec;
    YCoordinateSeqSeqSeqSpec.__name__ = "YCoordinateSeqSeqSeqSpec";
    class AngleSpec extends NumberUnitsSpec {
        get default_units() { return "rad"; }
        get valid_units() { return [...enums.AngleUnits]; }
        materialize(value) {
            const coeff = -(0, math_1.to_radians_coeff)(this.units);
            return value * coeff;
        }
        v_materialize(values) {
            const coeff = -(0, math_1.to_radians_coeff)(this.units);
            const result = new Float32Array(values.length);
            (0, arrayable_1.mul)(values, coeff, result); // TODO: in-place?
            return result;
        }
        array(_source) {
            throw new Error("not supported");
        }
    }
    exports.AngleSpec = AngleSpec;
    AngleSpec.__name__ = "AngleSpec";
    class DistanceSpec extends NumberUnitsSpec {
        get default_units() { return "data"; }
        get valid_units() { return [...enums.SpatialUnits]; }
    }
    exports.DistanceSpec = DistanceSpec;
    DistanceSpec.__name__ = "DistanceSpec";
    class NullDistanceSpec extends DistanceSpec {
        materialize(value) {
            return value !== null && value !== void 0 ? value : NaN;
        }
    }
    exports.NullDistanceSpec = NullDistanceSpec;
    NullDistanceSpec.__name__ = "NullDistanceSpec";
    class BooleanSpec extends DataSpec {
        v_materialize(values) {
            return new Uint8Array(values);
        }
        array(source) {
            return new Uint8Array(super.array(source));
        }
    }
    exports.BooleanSpec = BooleanSpec;
    BooleanSpec.__name__ = "BooleanSpec";
    class IntSpec extends DataSpec {
        v_materialize(values) {
            return (0, types_2.isTypedArray)(values) ? values : new Int32Array(values);
        }
        array(source) {
            return new Int32Array(super.array(source));
        }
    }
    exports.IntSpec = IntSpec;
    IntSpec.__name__ = "IntSpec";
    class NumberSpec extends DataSpec {
        v_materialize(values) {
            return (0, types_2.isTypedArray)(values) ? values : new Float64Array(values);
        }
        array(source) {
            return new Float64Array(super.array(source));
        }
    }
    exports.NumberSpec = NumberSpec;
    NumberSpec.__name__ = "NumberSpec";
    class ScreenSizeSpec extends NumberSpec {
        valid(value) {
            return (0, types_2.isNumber)(value) && value >= 0;
        }
    }
    exports.ScreenSizeSpec = ScreenSizeSpec;
    ScreenSizeSpec.__name__ = "ScreenSizeSpec";
    class ColorSpec extends DataSpec {
        materialize(color) {
            return (0, color_1.encode_rgba)((0, color_1.color2rgba)(color));
        }
        v_materialize(colors) {
            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) {
                    const [n] = colors.shape;
                    const array = new types_1.RGBAArray(4 * n);
                    let j = 0;
                    for (const gray of colors) {
                        array[j++] = gray;
                        array[j++] = gray;
                        array[j++] = gray;
                        array[j++] = 255;
                    }
                    return new types_1.ColorArray(array.buffer);
                }
                else if (colors.dtype == "uint8" && colors.dimension == 2) {
                    const [n, d] = colors.shape;
                    if (d == 4) {
                        return new types_1.ColorArray(colors.buffer);
                    }
                    else if (d == 3) {
                        const array = new types_1.RGBAArray(4 * n);
                        for (let 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) {
                    const [n, d] = colors.shape;
                    if (d == 3 || d == 4) {
                        const array = new types_1.RGBAArray(4 * n);
                        for (let 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 if (colors.dtype == "object" && colors.dimension == 1) {
                    return this._from_css_array(colors);
                }
            }
            else {
                return this._from_css_array(colors);
            }
            throw new Error("invalid color array");
        }
        _from_css_array(colors) {
            const n = colors.length;
            const array = new types_1.RGBAArray(4 * n);
            let j = 0;
            for (const color of colors) {
                const [r, g, b, a] = (0, color_1.color2rgba)(color);
                array[j++] = r;
                array[j++] = g;
                array[j++] = b;
                array[j++] = a;
            }
            return new types_1.ColorArray(array.buffer);
        }
        vector(values) {
            return new uniforms_1.ColorUniformVector(values);
        }
    }
    exports.ColorSpec = ColorSpec;
    ColorSpec.__name__ = "ColorSpec";
    class NDArraySpec extends DataSpec {
    }
    exports.NDArraySpec = NDArraySpec;
    NDArraySpec.__name__ = "NDArraySpec";
    class AnySpec extends DataSpec {
    }
    exports.AnySpec = AnySpec;
    AnySpec.__name__ = "AnySpec";
    class StringSpec extends DataSpec {
    }
    exports.StringSpec = StringSpec;
    StringSpec.__name__ = "StringSpec";
    class NullStringSpec extends DataSpec {
    }
    exports.NullStringSpec = NullStringSpec;
    NullStringSpec.__name__ = "NullStringSpec";
    class ArraySpec extends DataSpec {
    }
    exports.ArraySpec = ArraySpec;
    ArraySpec.__name__ = "ArraySpec";
    class MarkerSpec extends DataSpec {
    }
    exports.MarkerSpec = MarkerSpec;
    MarkerSpec.__name__ = "MarkerSpec";
    class LineJoinSpec extends DataSpec {
    }
    exports.LineJoinSpec = LineJoinSpec;
    LineJoinSpec.__name__ = "LineJoinSpec";
    class LineCapSpec extends DataSpec {
    }
    exports.LineCapSpec = LineCapSpec;
    LineCapSpec.__name__ = "LineCapSpec";
    class LineDashSpec extends DataSpec {
    }
    exports.LineDashSpec = LineDashSpec;
    LineDashSpec.__name__ = "LineDashSpec";
    class FontSpec extends DataSpec {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.FontSpec = FontSpec;
    FontSpec.__name__ = "FontSpec";
    class FontSizeSpec extends DataSpec {
    }
    exports.FontSizeSpec = FontSizeSpec;
    FontSizeSpec.__name__ = "FontSizeSpec";
    class FontStyleSpec extends DataSpec {
    }
    exports.FontStyleSpec = FontStyleSpec;
    FontStyleSpec.__name__ = "FontStyleSpec";
    class TextAlignSpec extends DataSpec {
    }
    exports.TextAlignSpec = TextAlignSpec;
    TextAlignSpec.__name__ = "TextAlignSpec";
    class TextBaselineSpec extends DataSpec {
    }
    exports.TextBaselineSpec = TextBaselineSpec;
    TextBaselineSpec.__name__ = "TextBaselineSpec";
},
/* core/logging.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    // This is based on https://github.com/pimterry/loglevel
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    const _loggers = {};
    class LogLevel {
        constructor(name, level) {
            this.name = name;
            this.level = level;
        }
    }
    exports.LogLevel = LogLevel;
    LogLevel.__name__ = "LogLevel";
    class Logger {
        static get levels() {
            return Object.keys(Logger.log_levels);
        }
        static get(name, level = Logger.INFO) {
            if (name.length > 0) {
                if (name in _loggers)
                    return _loggers[name];
                else
                    return _loggers[name] = new Logger(name, level);
            }
            else
                throw new TypeError("Logger.get() expects a non-empty string name and an optional log-level");
        }
        constructor(name, level = Logger.INFO) {
            this._name = name;
            this.set_level(level);
        }
        get level() {
            return this.get_level();
        }
        get_level() {
            return this._log_level;
        }
        set_level(log_level) {
            if (log_level instanceof LogLevel)
                this._log_level = log_level;
            else if ((0, types_1.isString)(log_level) && log_level in Logger.log_levels)
                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");
            const logger_name = `[${this._name}]`;
            for (const [name, log_level] of (0, object_1.entries)(Logger.log_levels)) {
                if (log_level.level < this._log_level.level || this._log_level.level === Logger.OFF.level)
                    this[name] = function () { };
                else
                    this[name] = _method_factory(name, logger_name);
            }
        }
        trace(..._args) { }
        debug(..._args) { }
        info(..._args) { }
        warn(..._args) { }
        error(..._args) { }
    }
    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
            return console.log.bind(console, logger_name);
    }
    exports.logger = Logger.get("bokeh");
    function set_log_level(level) {
        const previous_level = exports.logger.level;
        if ((0, types_1.isString)(level) && !(level in Logger.log_levels)) {
            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) {
        const 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.ToolIcon = exports.VerticalAlign = exports.UpdateMode = exports.TooltipAttachment = exports.LabelOrientation = exports.TextureRepetition = exports.TextBaseline = exports.TextAlign = exports.TapGesture = exports.TapBehavior = exports.StepMode = exports.StartEnd = exports.SpatialUnits = void 0;
    const kinds_1 = require(21) /* ./kinds */;
    exports.Align = (0, kinds_1.Enum)("start", "center", "end");
    exports.HAlign = (0, kinds_1.Enum)("left", "center", "right");
    exports.VAlign = (0, kinds_1.Enum)("top", "center", "bottom");
    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.AlternationPolicy = (0, kinds_1.Enum)("none", "even", "odd", "every");
    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.Clock = (0, kinds_1.Enum)("12h", "24h");
    exports.CoordinateUnits = (0, kinds_1.Enum)("canvas", "screen", "data");
    exports.ContextWhich = (0, kinds_1.Enum)("start", "center", "end", "all");
    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.Face = (0, kinds_1.Enum)("front", "back");
    exports.FlowMode = (0, kinds_1.Enum)("block", "inline");
    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.ImageOrigin = (0, kinds_1.Enum)("bottom_left", "top_left", "bottom_right", "top_right");
    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.LineDash = (0, kinds_1.Enum)("solid", "dashed", "dotted", "dotdash", "dashdot");
    exports.LineJoin = (0, kinds_1.Enum)("miter", "round", "bevel");
    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.MapType = (0, kinds_1.Enum)("satellite", "roadmap", "terrain", "hybrid");
    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.ResetPolicy = (0, kinds_1.Enum)("standard", "event_only");
    exports.RoundingFunction = (0, kinds_1.Enum)("round", "nearest", "floor", "rounddown", "ceil", "roundup");
    exports.ScrollbarPolicy = (0, kinds_1.Enum)("auto", "visible", "hidden");
    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", "inherit");
    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.TapGesture = (0, kinds_1.Enum)("tap", "doubletap");
    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.LabelOrientation = (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");
    exports.ToolIcon = (0, kinds_1.Enum)("append_mode", "box_edit", "box_select", "box_zoom", "clear_selection", "copy", "crosshair", "freehand_draw", "help", "hover", "intersect_mode", "lasso_select", "line_edit", "pan", "point_draw", "poly_draw", "poly_edit", "polygon_select", "range", "redo", "replace_mode", "reset", "save", "subtract_mode", "tap_select", "undo", "wheel_pan", "wheel_zoom", "xpan", "ypan", "zoom_in", "zoom_out");
},
/* core/kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tp = tslib_1.__importStar(require(8) /* ./util/types */);
    const color_1 = require(22) /* ./util/color */;
    const object_1 = require(9) /* ./util/object */;
    const refs_1 = require(17) /* ./util/refs */;
    const ESMap = globalThis.Map;
    const ESSet = globalThis.Set;
    const { hasOwnProperty } = Object.prototype;
    class Kind {
    }
    exports.Kind = Kind;
    Kind.__name__ = "Kind";
    (function (Kinds) {
        class Primitive extends Kind {
            may_have_refs() {
                return false;
            }
        }
        Primitive.__name__ = "Primitive";
        Kinds.Primitive = Primitive;
        class Any extends Primitive {
            valid(value) {
                return value !== undefined;
            }
            toString() {
                return "Any";
            }
            may_have_refs() {
                return true;
            }
        }
        Any.__name__ = "Any";
        Kinds.Any = Any;
        class Unknown extends Primitive {
            valid(value) {
                return value !== undefined;
            }
            toString() {
                return "Unknown";
            }
            may_have_refs() {
                return true;
            }
        }
        Unknown.__name__ = "Unknown";
        Kinds.Unknown = Unknown;
        class Boolean extends Primitive {
            valid(value) {
                return tp.isBoolean(value);
            }
            toString() {
                return "Boolean";
            }
        }
        Boolean.__name__ = "Boolean";
        Kinds.Boolean = Boolean;
        class Ref extends Kind {
            constructor(obj_type) {
                super();
                this.obj_type = obj_type;
            }
            valid(value) {
                return value instanceof this.obj_type;
            }
            toString() {
                var _a;
                const tp = this.obj_type;
                // NOTE: `__name__` is injected by a compiler transform
                const name = (_a = tp.__name__) !== null && _a !== void 0 ? _a : tp.toString();
                return `Ref(${name})`;
            }
            may_have_refs() {
                const { obj_type } = this;
                return refs_1.has_refs in obj_type ? obj_type[refs_1.has_refs] : true;
            }
        }
        Ref.__name__ = "Ref";
        Kinds.Ref = Ref;
        class AnyRef extends Kind {
            valid(value) {
                return tp.isObject(value);
            }
            toString() {
                return "AnyRef";
            }
            may_have_refs() {
                return true;
            }
        }
        AnyRef.__name__ = "AnyRef";
        Kinds.AnyRef = AnyRef;
        class Number extends Primitive {
            valid(value) {
                return tp.isNumber(value);
            }
            toString() {
                return "Number";
            }
        }
        Number.__name__ = "Number";
        Kinds.Number = Number;
        class Int extends Number {
            valid(value) {
                return super.valid(value) && tp.isInteger(value);
            }
            toString() {
                return "Int";
            }
        }
        Int.__name__ = "Int";
        Kinds.Int = Int;
        class Percent extends Number {
            valid(value) {
                return super.valid(value) && 0 <= value && value <= 1;
            }
            toString() {
                return "Percent";
            }
        }
        Percent.__name__ = "Percent";
        Kinds.Percent = Percent;
        class Or extends Kind {
            constructor(types) {
                super();
                this.types = types;
                this.types = types;
            }
            valid(value) {
                return this.types.some((type) => type.valid(value));
            }
            toString() {
                return `Or(${this.types.map((type) => type.toString()).join(", ")})`;
            }
            may_have_refs() {
                return this.types.some((type) => type.may_have_refs());
            }
        }
        Or.__name__ = "Or";
        Kinds.Or = Or;
        class Tuple extends Kind {
            constructor(types) {
                super();
                this.types = types;
                this.types = types;
            }
            valid(value) {
                if (!tp.isArray(value))
                    return false;
                for (let i = 0; i < this.types.length; i++) {
                    const type = this.types[i];
                    const item = value[i];
                    if (!type.valid(item))
                        return false;
                }
                return true;
            }
            toString() {
                return `Tuple(${this.types.map((type) => type.toString()).join(", ")})`;
            }
            may_have_refs() {
                return this.types.some((type) => type.may_have_refs());
            }
        }
        Tuple.__name__ = "Tuple";
        Kinds.Tuple = Tuple;
        class Struct extends Kind {
            constructor(struct_type) {
                super();
                this.struct_type = struct_type;
            }
            valid(value) {
                if (!tp.isPlainObject(value))
                    return false;
                const { struct_type } = this;
                for (const key of (0, object_1.keys)(value)) {
                    if (!hasOwnProperty.call(struct_type, key))
                        return false;
                }
                for (const key in struct_type) {
                    if (hasOwnProperty.call(struct_type, key)) {
                        const item_type = struct_type[key];
                        const item = value[key];
                        if (!item_type.valid(item))
                            return false;
                    }
                }
                return true;
            }
            toString() {
                const items = (0, object_1.typed_entries)(this.struct_type).map(([key, kind]) => `${key.toString()}: ${kind}`).join(", ");
                return `Struct({${items}})`;
            }
            may_have_refs() {
                return (0, object_1.typed_values)(this.struct_type).some((kind) => kind.may_have_refs());
            }
        }
        Struct.__name__ = "Struct";
        Kinds.Struct = Struct;
        class PartialStruct extends Kind {
            constructor(struct_type) {
                super();
                this.struct_type = struct_type;
            }
            valid(value) {
                if (!tp.isPlainObject(value))
                    return false;
                const { struct_type } = this;
                for (const key of (0, object_1.keys)(value)) {
                    if (!hasOwnProperty.call(struct_type, key))
                        return false;
                }
                for (const key in struct_type) {
                    if (!hasOwnProperty.call(value, key))
                        continue;
                    if (hasOwnProperty.call(struct_type, key)) {
                        const item_type = struct_type[key];
                        const item = value[key];
                        if (!item_type.valid(item))
                            return false;
                    }
                }
                return true;
            }
            toString() {
                const items = (0, object_1.typed_entries)(this.struct_type).map(([key, kind]) => `${key.toString()}?: ${kind}`).join(", ");
                return `Struct({${items}})`;
            }
            may_have_refs() {
                return (0, object_1.typed_values)(this.struct_type).some((kind) => kind.may_have_refs());
            }
        }
        PartialStruct.__name__ = "PartialStruct";
        Kinds.PartialStruct = PartialStruct;
        class Iterable extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isIterable(value);
            }
            toString() {
                return `Iterable(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Iterable.__name__ = "Iterable";
        Kinds.Iterable = Iterable;
        class Arrayable extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isArray(value) || tp.isTypedArray(value); // TODO: too specific
            }
            toString() {
                return `Arrayable(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Arrayable.__name__ = "Arrayable";
        Kinds.Arrayable = Arrayable;
        class Array extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isArray(value) && value.every((item) => this.item_type.valid(item));
            }
            toString() {
                return `Array(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Array.__name__ = "Array";
        Kinds.Array = Array;
        class Null extends Primitive {
            valid(value) {
                return value === null;
            }
            toString() {
                return "Null";
            }
        }
        Null.__name__ = "Null";
        Kinds.Null = Null;
        class Nullable extends Kind {
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return value === null || this.base_type.valid(value);
            }
            toString() {
                return `Nullable(${this.base_type.toString()})`;
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Nullable.__name__ = "Nullable";
        Kinds.Nullable = Nullable;
        class Opt extends Kind {
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return value === undefined || this.base_type.valid(value);
            }
            toString() {
                return `Opt(${this.base_type.toString()})`;
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Opt.__name__ = "Opt";
        Kinds.Opt = Opt;
        class Bytes extends Kind {
            valid(value) {
                return value instanceof ArrayBuffer;
            }
            toString() {
                return "Bytes";
            }
            may_have_refs() {
                return false;
            }
        }
        Bytes.__name__ = "Bytes";
        Kinds.Bytes = Bytes;
        class String extends Primitive {
            valid(value) {
                return tp.isString(value);
            }
            toString() {
                return "String";
            }
        }
        String.__name__ = "String";
        Kinds.String = String;
        class Regex extends String {
            constructor(regex) {
                super();
                this.regex = regex;
            }
            valid(value) {
                return super.valid(value) && this.regex.test(value);
            }
            toString() {
                return `Regex(${this.regex.toString()})`;
            }
        }
        Regex.__name__ = "Regex";
        Kinds.Regex = Regex;
        class Enum extends Primitive {
            constructor(values) {
                super();
                this.values = new ESSet(values);
            }
            valid(value) {
                return this.values.has(value);
            }
            *[Symbol.iterator]() {
                yield* this.values;
            }
            toString() {
                return `Enum(${[...this.values].map((v) => v.toString()).join(", ")})`;
            }
        }
        Enum.__name__ = "Enum";
        Kinds.Enum = Enum;
        class Dict extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                if (!tp.isPlainObject(value))
                    return false;
                for (const key in value) {
                    if (hasOwnProperty.call(value, key)) {
                        const item = value[key];
                        if (!this.item_type.valid(item))
                            return false;
                    }
                }
                return true;
            }
            toString() {
                return `Dict(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Dict.__name__ = "Dict";
        Kinds.Dict = Dict;
        class Map extends Kind {
            constructor(key_type, item_type) {
                super();
                this.key_type = key_type;
                this.item_type = item_type;
            }
            valid(value) {
                if (!(value instanceof ESMap))
                    return false;
                for (const [key, item] of value.entries()) {
                    if (!(this.key_type.valid(key) && this.item_type.valid(item)))
                        return false;
                }
                return true;
            }
            toString() {
                return `Map(${this.key_type.toString()}, ${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.key_type.may_have_refs() || this.item_type.may_have_refs();
            }
        }
        Map.__name__ = "Map";
        Kinds.Map = Map;
        class Set extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                if (!(value instanceof ESSet))
                    return false;
                for (const item of value) {
                    if (!this.item_type.valid(item))
                        return false;
                }
                return true;
            }
            toString() {
                return `Set(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Set.__name__ = "Set";
        Kinds.Set = Set;
        class Color extends Kind {
            valid(value) {
                return (0, color_1.is_Color)(value);
            }
            toString() {
                return "Color";
            }
            may_have_refs() {
                return false;
            }
        }
        Color.__name__ = "Color";
        Kinds.Color = Color;
        class CSSLength extends String {
            /*
            override valid(value: unknown): value is string {
              return super.valid(value) // TODO: && this._parse(value)
            }
            */
            toString() {
                return "CSSLength";
            }
        }
        CSSLength.__name__ = "CSSLength";
        Kinds.CSSLength = CSSLength;
        class Function extends Kind {
            valid(value) {
                return tp.isFunction(value);
            }
            toString() {
                return "Function(...)";
            }
            may_have_refs() {
                return false;
            }
        }
        Function.__name__ = "Function";
        Kinds.Function = Function;
        class NonNegative extends Kind {
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return this.base_type.valid(value) && value >= 0;
            }
            toString() {
                return `NonNegative(${this.base_type.toString()})`;
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        NonNegative.__name__ = "NonNegative";
        Kinds.NonNegative = NonNegative;
        class Positive extends Kind {
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return this.base_type.valid(value) && value > 0;
            }
            toString() {
                return `Positive(${this.base_type.toString()})`;
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Positive.__name__ = "Positive";
        Kinds.Positive = Positive;
        class DOMNode extends Kind {
            valid(value) {
                return value instanceof Node;
            }
            toString() {
                return "DOMNode";
            }
            may_have_refs() {
                return false;
            }
        }
        DOMNode.__name__ = "DOMNode";
        Kinds.DOMNode = DOMNode;
    })(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.Bytes = new exports.Kinds.Bytes();
    exports.String = new exports.Kinds.String();
    const Regex = (regex) => new exports.Kinds.Regex(regex);
    exports.Regex = Regex;
    exports.Null = new exports.Kinds.Null();
    const Nullable = (base_type) => new exports.Kinds.Nullable(base_type);
    exports.Nullable = Nullable;
    const Opt = (base_type) => new exports.Kinds.Opt(base_type);
    exports.Opt = Opt;
    const Or = (...types) => new exports.Kinds.Or(types);
    exports.Or = Or;
    const Tuple = (...types) => new exports.Kinds.Tuple(types);
    exports.Tuple = Tuple;
    const Struct = (struct_type) => new exports.Kinds.Struct(struct_type);
    exports.Struct = Struct;
    const PartialStruct = (struct_type) => new exports.Kinds.PartialStruct(struct_type);
    exports.PartialStruct = PartialStruct;
    const Iterable = (item_type) => new exports.Kinds.Iterable(item_type);
    exports.Iterable = Iterable;
    const Arrayable = (item_type) => new exports.Kinds.Arrayable(item_type);
    exports.Arrayable = Arrayable;
    const Array = (item_type) => new exports.Kinds.Array(item_type);
    exports.Array = Array;
    const Dict = (item_type) => new exports.Kinds.Dict(item_type);
    exports.Dict = Dict;
    const Map = (key_type, item_type) => new exports.Kinds.Map(key_type, item_type);
    exports.Map = Map;
    const Set = (item_type) => new exports.Kinds.Set(item_type);
    exports.Set = Set;
    const Enum = (...values) => new exports.Kinds.Enum(values);
    exports.Enum = Enum;
    const Ref = (obj_type) => new exports.Kinds.Ref(obj_type);
    exports.Ref = Ref;
    const AnyRef = () => new exports.Kinds.AnyRef();
    exports.AnyRef = AnyRef;
    const Function = () => new exports.Kinds.Function();
    exports.Function = Function;
    exports.DOMNode = new exports.Kinds.DOMNode();
    const NonNegative = (base_type) => new exports.Kinds.NonNegative(base_type);
    exports.NonNegative = NonNegative;
    const Positive = (base_type) => new exports.Kinds.Positive(base_type);
    exports.Positive = Positive;
    exports.Percent = new exports.Kinds.Percent();
    exports.Alpha = exports.Percent;
    exports.Color = new exports.Kinds.Color();
    exports.Auto = (0, exports.Enum)("auto");
    exports.CSSLength = new exports.Kinds.CSSLength();
    exports.FontSize = exports.String;
    exports.Font = exports.String;
    exports.Angle = exports.Number;
},
/* core/util/color.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const svg_colors_1 = require(23) /* ./svg_colors */;
    const math_1 = require(11) /* ./math */;
    const types_1 = require(8) /* ./types */;
    const { round, sqrt } = Math;
    function byte(v) {
        return (0, math_1.clamp)(round(v), 0, 255);
    }
    exports.byte = byte;
    function transparent() {
        return [0, 0, 0, 0];
    }
    exports.transparent = transparent;
    function encode_rgba([r, g, b, a]) {
        return r << 24 | g << 16 | b << 8 | a;
    }
    exports.encode_rgba = encode_rgba;
    function decode_rgba(rgba) {
        const r = (rgba >> 24) & 0xff;
        const g = (rgba >> 16) & 0xff;
        const b = (rgba >> 8) & 0xff;
        const a = rgba & 0xff;
        return [r, g, b, a];
    }
    exports.decode_rgba = decode_rgba;
    function color2rgba(color, alpha = 1.0) {
        const [r, g, b, a] = (() => {
            var _a;
            if (color == null)
                return transparent();
            else if ((0, types_1.isInteger)(color))
                return decode_rgba(color);
            else if ((0, types_1.isString)(color))
                return (_a = css4_parse(color)) !== null && _a !== void 0 ? _a : transparent();
            else {
                if (color.length == 2) {
                    const [name, alpha] = color;
                    return color2rgba(name, alpha);
                }
                else {
                    const [r, g, b, a = 1.0] = color;
                    return [r, g, b, byte(a * 255)];
                }
            }
        })();
        return [r, g, b, byte(alpha * a)];
    }
    exports.color2rgba = color2rgba;
    const _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) {
        const [r, g, b, a] = color2rgba(color, alpha);
        return `rgba(${r}, ${g}, ${b}, ${a / 255})`;
    }
    exports.color2css = color2css;
    function color2hex(color, alpha) {
        const [r, g, b, a] = color2rgba(color, alpha);
        const rgb = `#${hex(r)}${hex(g)}${hex(b)}`;
        return a == 255 ? rgb : `${rgb}${hex(a)}`;
    }
    exports.color2hex = color2hex;
    function color2hexrgb(color) {
        const [r, g, b] = color2rgba(color);
        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
    }
    */
    const rgb_modern = /^rgba?\(\s*(?<r>[^\s,]+?)\s+(?<g>[^\s,]+?)\s+(?<b>[^\s,]+?)(?:\s*\/\s*(?<a>[^\s,]+?))?\s*\)$/;
    const rgb_legacy = /^rgba?\(\s*(?<r>[^\s,]+?)\s*,\s*(?<g>[^\s,]+?)\s*,\s*(?<b>[^\s,]+?)(?:\s*,\s*(?<a>[^\s,]+?))?\s*\)$/;
    const css4_normalize = (() => {
        const canvas = document.createElement("canvas");
        canvas.width = 1;
        canvas.height = 1;
        const ctx = canvas.getContext("2d");
        const gradient = ctx.createLinearGradient(0, 0, 1, 1);
        return (color) => {
            ctx.fillStyle = gradient; // lgtm [js/useless-assignment-to-property]
            ctx.fillStyle = color;
            const 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] == "#") {
            const v = Number(`0x${color.substring(1)}`);
            if (isNaN(v))
                return null;
            switch (color.length - 1) {
                case 3: {
                    const r = (v >> 8) & 0xf;
                    const g = (v >> 4) & 0xf;
                    const b = (v >> 0) & 0xf;
                    const rr = (r << 4) | r;
                    const gg = (g << 4) | g;
                    const bb = (b << 4) | b;
                    return [rr, gg, bb, 255];
                }
                case 4: {
                    const r = (v >> 12) & 0xf;
                    const g = (v >> 8) & 0xf;
                    const b = (v >> 4) & 0xf;
                    const a = (v >> 0) & 0xf;
                    const rr = (r << 4) | r;
                    const gg = (g << 4) | g;
                    const bb = (b << 4) | b;
                    const aa = (a << 4) | a;
                    return [rr, gg, bb, aa];
                }
                case 6: {
                    const rr = (v >> 16) & 0xff;
                    const gg = (v >> 8) & 0xff;
                    const bb = (v >> 0) & 0xff;
                    return [rr, gg, bb, 255];
                }
                case 8: {
                    const rr = (v >> 24) & 0xff;
                    const gg = (v >> 16) & 0xff;
                    const bb = (v >> 8) & 0xff;
                    const aa = (v >> 0) & 0xff;
                    return [rr, gg, bb, aa];
                }
            }
        }
        else if (color.startsWith("rgb")) {
            const result = (_a = color.match(rgb_modern)) !== null && _a !== void 0 ? _a : color.match(rgb_legacy);
            if ((result === null || result === void 0 ? void 0 : result.groups) != null) {
                let { r, g, b, a = "1" } = result.groups;
                const rp = r.endsWith("%");
                const gp = g.endsWith("%");
                const bp = b.endsWith("%");
                const 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);
                let R = Number(r);
                let G = Number(g);
                let B = Number(b);
                let 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 {
            const 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([r, g, b]) {
        const l = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        return l >= 0.6;
    }
    exports.is_dark = is_dark;
    function brightness(color) {
        // Perceived brightness of a color in [0, 1] range.
        // http://alienryderflex.com/hsp.html
        const [r, g, b] = color2rgba(color);
        return sqrt(0.299 * r ** 2 + 0.587 * g ** 2 + 0.114 * b ** 2) / 255;
    }
    exports.brightness = brightness;
},
/* core/util/svg_colors.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const _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();
    const tslib_1 = require(1) /* tslib */;
    exports.GeneratorFunction = Object.getPrototypeOf(function* () { }).constructor;
    exports.AsyncGeneratorFunction = Object.getPrototypeOf(function () { return tslib_1.__asyncGenerator(this, arguments, function* () { }); }).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(25) /* ./util/bitset */;
    __esExport("Indices", bitset_1.BitSet);
},
/* core/util/bitset.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const eq_1 = require(26) /* ./eq */;
    const assert_1 = require(12) /* ./assert */;
    const refs_1 = require(17) /* ./refs */;
    class BitSet {
        constructor(size, init = 0) {
            this[_a] = "BitSet";
            this._count = null;
            this.size = size;
            this._nwords = Math.ceil(size / BitSet._word_length);
            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;
            }
        }
        clone() {
            return new BitSet(this.size, new Uint32Array(this._array));
        }
        [(_a = Symbol.toStringTag, _b = refs_1.has_refs, eq_1.equals)](that, cmp) {
            if (!cmp.eq(this.size, that.size))
                return false;
            const { _nwords } = this;
            const trailing = this.size % BitSet._word_length;
            const n = trailing == 0 ? _nwords : _nwords - 1;
            for (let i = 0; i < n; i++) {
                if (this._array[i] != that._array[i])
                    return false;
            }
            if (trailing == 0)
                return true;
            else {
                const msb = 1 << (trailing - 1);
                const mask = (msb - 1) ^ msb;
                return (this._array[n] & mask) == (that._array[n] & mask);
            }
        }
        static all_set(size) {
            return new BitSet(size, 1);
        }
        static all_unset(size) {
            return new BitSet(size, 0);
        }
        static from_indices(size, indices) {
            const bits = new BitSet(size);
            for (const i of indices) {
                bits.set(i);
            }
            return bits;
        }
        static from_booleans(size, booleans) {
            const bits = new BitSet(size);
            let i = 0;
            for (const boolean of booleans) {
                if (i == size) {
                    break;
                }
                if (boolean) {
                    bits.set(i);
                }
                i += 1;
            }
            return bits;
        }
        _check_bounds(k) {
            (0, assert_1.assert)(0 <= k && k < this.size, `Out of bounds: 0 <= ${k} < ${this.size}`);
        }
        get(k) {
            this._check_bounds(k);
            const i = k >>> 5; // Math.floor(k/32)
            const j = k & 0x1f; // k % 32
            return ((this._array[i] >> j) & 0b1) == 0b1;
        }
        set(k, v = true) {
            this._check_bounds(k);
            this._count = null;
            const i = k >>> 5; // Math.floor(k/32)
            const j = k & 0x1f; // k % 32
            if (v)
                this._array[i] |= 0b1 << j;
            else
                this._array[i] &= ~(0b1 << j);
        }
        unset(k) {
            this.set(k, false);
        }
        *[Symbol.iterator]() {
            yield* this.ones();
        }
        get count() {
            let count = this._count;
            if (count == null)
                this._count = count = this._get_count();
            return count;
        }
        _get_count() {
            const { _array, _nwords, size } = this;
            let c = 0;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0) {
                    k += BitSet._word_length;
                }
                else {
                    for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                        if (((word >>> j) & 0b1) == 0b1)
                            c += 1;
                    }
                }
            }
            return c;
        }
        *ones() {
            const { _array, _nwords, size } = this;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0) {
                    k += BitSet._word_length;
                    continue;
                }
                for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                    if (((word >>> j) & 0b1) == 0b1)
                        yield k;
                }
            }
        }
        *zeros() {
            const { _array, _nwords, size } = this;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0xffffffff) {
                    k += BitSet._word_length;
                    continue;
                }
                for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                    if (((word >>> j) & 0b1) == 0b0)
                        yield k;
                }
            }
        }
        _check_size(other) {
            (0, assert_1.assert)(this.size == other.size, `Size mismatch (${this.size} != ${other.size})`);
        }
        invert() {
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] = ~this._array[i] >>> 0;
            }
        }
        add(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] |= other._array[i];
            }
        }
        intersect(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] &= other._array[i];
            }
        }
        subtract(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                const a = this._array[i];
                const b = other._array[i];
                this._array[i] = (a ^ b) & a;
            }
        }
        symmetric_subtract(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] ^= other._array[i];
            }
        }
        inversion() {
            const result = this.clone();
            result.invert();
            return result;
        }
        union(other) {
            const result = this.clone();
            result.add(other);
            return result;
        }
        intersection(other) {
            const result = this.clone();
            result.intersect(other);
            return result;
        }
        difference(other) {
            const result = this.clone();
            result.subtract(other);
            return result;
        }
        symmetric_difference(other) {
            const result = this.clone();
            result.symmetric_subtract(other);
            return result;
        }
        select(array) {
            (0, assert_1.assert)(this.size <= array.length, "Size mismatch");
            const n = this.count;
            const result = new array.constructor(n);
            let i = 0;
            for (const j of this) {
                result[i++] = array[j];
            }
            return result;
        }
    }
    exports.BitSet = BitSet;
    BitSet.__name__ = "BitSet";
    BitSet[_b] = false;
    BitSet._word_length = 32;
},
/* core/util/eq.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    // Based on Underscore.js 1.8.3 (http://underscorejs.org)
    const types_1 = require(8) /* ./types */;
    const { hasOwnProperty } = Object.prototype;
    exports.equals = Symbol("equals");
    function is_Equatable(obj) {
        return (0, types_1.isObject)(obj) && exports.equals in obj;
    }
    exports.wildcard = Symbol("wildcard");
    const toString = Object.prototype.toString;
    class Comparator {
        constructor(options) {
            var _a;
            this.a_stack = [];
            this.b_stack = [];
            this.structural = (_a = options === null || options === void 0 ? void 0 : options.structural) !== null && _a !== void 0 ? _a : false;
        }
        eq(a, b) {
            if (Object.is(a, b))
                return true;
            if (a === exports.wildcard || b === exports.wildcard)
                return true;
            if (a == null || b == null)
                return a === b;
            const 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 Symbol]":
                    return 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.
            const { a_stack, b_stack } = this;
            let length = a_stack.length;
            while (length-- > 0) {
                // 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);
            const result = (() => {
                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 (typeof Node !== "undefined" && 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;
        }
        numbers(a, b) {
            return Object.is(a, b);
        }
        arrays(a, b) {
            const { length } = a;
            if (length != b.length)
                return false;
            for (let i = 0; i < length; i++) {
                if (!this.eq(a[i], b[i]))
                    return false;
            }
            return true;
        }
        iterables(a, b) {
            var _a, _b;
            const ai = a[Symbol.iterator]();
            const bi = b[Symbol.iterator]();
            while (true) {
                const an = ai.next();
                const bn = bi.next();
                const an_done = (_a = an.done) !== null && _a !== void 0 ? _a : false;
                const bn_done = (_b = bn.done) !== null && _b !== void 0 ? _b : false;
                if (an_done && bn_done)
                    return true;
                if (an_done || bn_done)
                    return false;
                if (!this.eq(an.value, bn.value))
                    return false;
            }
        }
        maps(a, b) {
            if (a.size != b.size)
                return false;
            if (this.structural)
                return this.iterables(a.entries(), b.entries());
            else {
                for (const [key, val] of a) {
                    if (!b.has(key) || !this.eq(val, b.get(key)))
                        return false;
                }
                return true;
            }
        }
        sets(a, b) {
            if (a.size != b.size)
                return false;
            if (this.structural)
                return this.iterables(a.entries(), b.entries());
            else {
                for (const key of a) {
                    if (!b.has(key))
                        return false;
                }
                return true;
            }
        }
        objects(a, b) {
            const keys = Object.keys(a);
            if (keys.length != Object.keys(b).length)
                return false;
            for (const key of keys) {
                if (!hasOwnProperty.call(b, key) || !this.eq(a[key], b[key]))
                    return false;
            }
            return true;
        }
        nodes(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;
        }
    }
    exports.Comparator = Comparator;
    Comparator.__name__ = "Comparator";
    const { abs } = Math;
    class SimilarComparator extends Comparator {
        constructor(tolerance = 1e-4) {
            super();
            this.tolerance = tolerance;
        }
        numbers(a, b) {
            return super.numbers(a, b) || abs(a - b) < this.tolerance;
        }
    }
    exports.SimilarComparator = SimilarComparator;
    SimilarComparator.__name__ = "SimilarComparator";
    function is_equal(a, b) {
        const comparator = new Comparator();
        return comparator.eq(a, b);
    }
    exports.is_equal = is_equal;
    function is_structurally_equal(a, b) {
        const comparator = new Comparator({ structural: true });
        return comparator.eq(a, b);
    }
    exports.is_structurally_equal = is_structurally_equal;
    function is_similar(a, b, tolerance) {
        const comparator = new SimilarComparator(tolerance);
        return comparator.eq(a, b);
    }
    exports.is_similar = is_similar;
},
/* core/util/platform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_mobile = (() => {
        return "ontouchstart" in globalThis || (typeof navigator !== "undefined" && navigator.maxTouchPoints > 0);
    })();
    exports.is_little_endian = (() => {
        const buf = new ArrayBuffer(4);
        const buf8 = new Uint8Array(buf);
        const buf32 = new Uint32Array(buf);
        buf32[1] = 0x0a0b0c0d;
        let 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) {
        if (exports.is_little_endian) {
            const result = new Uint32Array(values.length);
            const view = new DataView(result.buffer);
            let j = 0;
            for (const color of values) {
                view.setUint32(j, color);
                j += 4;
            }
            return result;
        }
        else
            return values;
    }
    exports.to_big_endian = to_big_endian;
},
/* core/vectorization.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ./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;
},
/* core/settings.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class Settings {
        constructor() {
            this._dev = false;
            this._wireframe = false;
            this._force_webgl = false;
        }
        set dev(dev) {
            this._dev = dev;
        }
        get dev() {
            return this._dev;
        }
        set wireframe(wireframe) {
            this._wireframe = wireframe;
        }
        get wireframe() {
            return this._wireframe;
        }
        set force_webgl(force_webgl) {
            this._force_webgl = force_webgl;
        }
        get force_webgl() {
            return this._force_webgl;
        }
    }
    exports.Settings = Settings;
    Settings.__name__ = "Settings";
    exports.settings = new Settings();
},
/* core/util/ndarray.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    __esModule();
    const types_1 = require(8) /* ./types */;
    const platform_1 = require(27) /* ./platform */;
    const eq_1 = require(26) /* ./eq */;
    const cloneable_1 = require(31) /* ./cloneable */;
    const serialization_1 = require(32) /* ../serialization */;
    const __ndarray__ = Symbol("__ndarray__");
    function encode_NDArray(array, serializer) {
        const encoded = serializer.encode(array.dtype == "object" ? Array.from(array) : array.buffer);
        return {
            type: "ndarray",
            array: encoded,
            order: platform_1.BYTE_ORDER,
            dtype: array.dtype,
            shape: array.shape,
        };
    }
    class BoolNDArray extends Uint8Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_a] = true;
            this.dtype = "bool";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_a = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new BoolNDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i] == 1;
        }
    }
    exports.BoolNDArray = BoolNDArray;
    BoolNDArray.__name__ = "BoolNDArray";
    class Uint8NDArray extends Uint8Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_b] = true;
            this.dtype = "uint8";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_b = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint8NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint8NDArray = Uint8NDArray;
    Uint8NDArray.__name__ = "Uint8NDArray";
    class Int8NDArray extends Int8Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_c] = true;
            this.dtype = "int8";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_c = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int8NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int8NDArray = Int8NDArray;
    Int8NDArray.__name__ = "Int8NDArray";
    class Uint16NDArray extends Uint16Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_d] = true;
            this.dtype = "uint16";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_d = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint16NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint16NDArray = Uint16NDArray;
    Uint16NDArray.__name__ = "Uint16NDArray";
    class Int16NDArray extends Int16Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_e] = true;
            this.dtype = "int16";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_e = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int16NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int16NDArray = Int16NDArray;
    Int16NDArray.__name__ = "Int16NDArray";
    class Uint32NDArray extends Uint32Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_f] = true;
            this.dtype = "uint32";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_f = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint32NDArray = Uint32NDArray;
    Uint32NDArray.__name__ = "Uint32NDArray";
    class Int32NDArray extends Int32Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_g] = true;
            this.dtype = "int32";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_g = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int32NDArray = Int32NDArray;
    Int32NDArray.__name__ = "Int32NDArray";
    class Float32NDArray extends Float32Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_h] = true;
            this.dtype = "float32";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_h = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Float32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Float32NDArray = Float32NDArray;
    Float32NDArray.__name__ = "Float32NDArray";
    class Float64NDArray extends Float64Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_j] = true;
            this.dtype = "float64";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_j = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Float64NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Float64NDArray = Float64NDArray;
    Float64NDArray.__name__ = "Float64NDArray";
    class ObjectNDArray extends Array {
        get shape() {
            var _l;
            return (_l = this._shape) !== null && _l !== void 0 ? _l : [this.length];
        }
        get dimension() {
            return this.shape.length;
        }
        constructor(init_, shape) {
            const init = init_ instanceof ArrayBuffer ? new Float64Array(init_) : init_;
            const size = (0, types_1.isNumber)(init) ? init : init.length;
            super(size);
            this[_k] = true;
            this.dtype = "object";
            if (!(0, types_1.isNumber)(init)) {
                for (let i = 0; i < init.length; i++) {
                    this[i] = init[i];
                }
            }
            this._shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(init) ? init.shape : undefined);
        }
        [(_k = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new ObjectNDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.ObjectNDArray = ObjectNDArray;
    ObjectNDArray.__name__ = "ObjectNDArray";
    function is_NDArray(v) {
        return (0, types_1.isObject)(v) && __ndarray__ in v;
    }
    exports.is_NDArray = is_NDArray;
    function ndarray(init, { dtype, shape } = {}) {
        if (dtype == null) {
            dtype = (() => {
                switch (true) {
                    case init instanceof Uint8Array: return "uint8";
                    case init instanceof Int8Array: return "int8";
                    case init instanceof Uint16Array: return "uint16";
                    case init instanceof Int16Array: return "int16";
                    case init instanceof Uint32Array: return "uint32";
                    case init instanceof Int32Array: return "int32";
                    case init instanceof Float32Array: return "float32";
                    case init instanceof ArrayBuffer:
                    case init instanceof Float64Array: return "float64";
                    default: return "object";
                }
            })();
        }
        switch (dtype) {
            case "bool": return new BoolNDArray(init, shape);
            case "uint8": return new Uint8NDArray(init, shape);
            case "int8": return new Int8NDArray(init, shape);
            case "uint16": return new Uint16NDArray(init, shape);
            case "int16": return new Int16NDArray(init, shape);
            case "uint32": return new Uint32NDArray(init, shape);
            case "int32": return new Int32NDArray(init, shape);
            case "float32": return new Float32NDArray(init, shape);
            case "float64": return new Float64NDArray(init, shape);
            case "object": return new ObjectNDArray(init, shape);
        }
    }
    exports.ndarray = ndarray;
},
/* core/util/cloneable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const object_1 = require(9) /* ./object */;
    const types_1 = require(8) /* ./types */;
    exports.clone = Symbol("clone");
    function is_Cloneable(obj) {
        return (0, types_1.isObject)(obj) && exports.clone in obj;
    }
    exports.is_Cloneable = is_Cloneable;
    class CloningError extends Error {
    }
    exports.CloningError = CloningError;
    CloningError.__name__ = "CloningError";
    class Cloner {
        constructor() { }
        clone(obj) {
            if (is_Cloneable(obj)) {
                return obj[exports.clone](this);
            }
            else if ((0, types_1.isPrimitive)(obj)) {
                return obj;
            }
            else if ((0, types_1.isArray)(obj)) {
                const n = obj.length;
                const result = new Array(n);
                for (let i = 0; i < n; i++) {
                    const value = obj[i];
                    result[i] = this.clone(value);
                }
                return result;
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                const result = {};
                for (const [key, value] of (0, object_1.entries)(obj)) {
                    result[key] = this.clone(value);
                }
                return result;
            }
            else if (obj instanceof Map) {
                return new Map([...obj].map(([k, v]) => [this.clone(k), this.clone(v)]));
            }
            else if (obj instanceof Set) {
                return new Set([...obj].map((v) => this.clone(v)));
            }
            else
                throw new CloningError(`${Object.prototype.toString.call(obj)} is not cloneable`);
        }
    }
    exports.Cloner = Cloner;
    Cloner.__name__ = "Cloner";
},
/* core/serialization/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var serializer_1 = require(33) /* ./serializer */;
    __esExport("Serializer", serializer_1.Serializer);
    __esExport("SerializationError", serializer_1.SerializationError);
    __esExport("serialize", serializer_1.serialize);
    var buffer_1 = require(35) /* ./buffer */;
    __esExport("Buffer", buffer_1.Buffer);
    __esExport("Base64Buffer", buffer_1.Base64Buffer);
    tslib_1.__exportStar(require(37) /* ./reps */, exports);
},
/* core/serialization/serializer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const assert_1 = require(12) /* ../util/assert */;
    const object_1 = require(9) /* ../util/object */;
    const types_1 = require(8) /* ../util/types */;
    const iterator_1 = require(34) /* ../util/iterator */;
    const platform_1 = require(27) /* ../util/platform */;
    const buffer_1 = require(35) /* ./buffer */;
    // TypedArray?
    exports.serialize = Symbol("serialize");
    function is_Serializable(obj) {
        return (0, types_1.isObject)(obj) && exports.serialize in obj;
    }
    class SerializationError extends Error {
    }
    exports.SerializationError = SerializationError;
    SerializationError.__name__ = "SerializationError";
    class Serialized {
        constructor(value) {
            this.value = value;
        }
        to_json() {
            return JSON.stringify(this.value);
        }
    }
    Serialized.__name__ = "Serialized";
    class Serializer {
        constructor(options) {
            var _a, _b;
            this._circular = new WeakSet();
            this.binary = (_a = options === null || options === void 0 ? void 0 : options.binary) !== null && _a !== void 0 ? _a : false;
            this.include_defaults = (_b = options === null || options === void 0 ? void 0 : options.include_defaults) !== null && _b !== void 0 ? _b : false;
            const references = options === null || options === void 0 ? void 0 : options.references;
            this._references = references != null ? new Map(references) : new Map();
        }
        get_ref(obj) {
            return this._references.get(obj);
        }
        add_ref(obj, ref) {
            (0, assert_1.assert)(!this._references.has(obj));
            this._references.set(obj, ref);
        }
        to_serializable(obj) {
            return new Serialized(this.encode(obj));
        }
        encode(obj) {
            const ref = this.get_ref(obj);
            if (ref != null) {
                return ref;
            }
            if (!(0, types_1.isObject)(obj)) {
                return this._encode(obj);
            }
            else {
                if (this._circular.has(obj)) {
                    this.error("circular reference");
                }
                this._circular.add(obj);
                try {
                    return this._encode(obj);
                }
                finally {
                    this._circular.delete(obj);
                }
            }
        }
        _encode(obj) {
            if (is_Serializable(obj))
                return obj[exports.serialize](this);
            else if ((0, types_1.isArray)(obj)) {
                const n = obj.length;
                const result = new Array(n);
                for (let i = 0; i < n; i++) {
                    const value = obj[i];
                    result[i] = this.encode(value);
                }
                return result;
            }
            else if ((0, types_1.isTypedArray)(obj)) {
                return this._encode_typed_array(obj);
            }
            else if (obj instanceof ArrayBuffer) {
                const data = this.binary ? new buffer_1.Buffer(obj) : new buffer_1.Base64Buffer(obj);
                return { type: "bytes", data };
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                const items = (0, object_1.entries)(obj);
                if (items.length == 0)
                    return { type: "map" };
                else
                    return { type: "map", entries: [...(0, iterator_1.map)(items, ([key, val]) => [this.encode(key), this.encode(val)])] };
                /*
                } else if (isBasicObject(obj)) {
                  return {type: "map", entries: [...map(entries(obj), ([key, val]) => [this.encode(key), this.encode(val)])]}
                } else if (isPlainObject(obj)) {
                  const result: {[key: string]: unknown} = {}
                  for (const [key, value] of entries(obj)) {
                    result[key] = this.encode(value)
                  }
                  return result
                */
            }
            else if (obj === null || (0, types_1.isBoolean)(obj) || (0, types_1.isString)(obj)) {
                return obj;
            }
            else if ((0, types_1.isNumber)(obj)) {
                if (isNaN(obj))
                    return { type: "number", value: "nan" };
                else if (!isFinite(obj))
                    return { type: "number", value: `${obj < 0 ? "-" : "+"}inf` };
                else
                    return obj;
            }
            else if (obj instanceof Date) {
                const iso = obj.toISOString();
                return { type: "date", iso };
            }
            else if (obj instanceof Set) {
                if (obj.size == 0)
                    return { type: "set" };
                else
                    return { type: "set", entries: [...(0, iterator_1.map)(obj.values(), (val) => this.encode(val))] };
            }
            else if (obj instanceof Map) {
                if (obj.size == 0)
                    return { type: "map" };
                else
                    return { type: "map", entries: [...(0, iterator_1.map)(obj.entries(), ([key, val]) => [this.encode(key), this.encode(val)])] };
            }
            else if ((0, types_1.isSymbol)(obj) && obj.description != null) {
                return { type: "symbol", name: obj.description };
            }
            else
                throw new SerializationError(`${Object.prototype.toString.call(obj)} is not serializable`);
        }
        encode_struct(struct) {
            const result = {};
            for (const [key, val] of (0, object_1.entries)(struct)) {
                if (val !== undefined)
                    result[key] = this.encode(val);
            }
            return result;
        }
        error(message) {
            throw new SerializationError(message);
        }
        _encode_typed_array(obj) {
            const array = this.encode(obj.buffer);
            const dtype = (() => {
                switch (obj.constructor) {
                    case Uint8Array: return "uint8";
                    case Int8Array: return "int8";
                    case Uint16Array: return "uint16";
                    case Int16Array: return "int16";
                    case Uint32Array: return "uint32";
                    case Int32Array: return "int32";
                    // case BigUint64Array: return "uint64"
                    // case BigInt64Array: return "int64"
                    case Float32Array: return "float32";
                    case Float64Array: return "float64";
                    default:
                        this.error(`can't serialize typed array of type '${obj[Symbol.toStringTag]}'`);
                }
            })();
            return {
                type: "typed_array",
                array,
                order: platform_1.BYTE_ORDER,
                dtype,
            };
        }
    }
    exports.Serializer = Serializer;
    Serializer.__name__ = "Serializer";
},
/* core/util/iterator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(10) /* ./array */;
    const assert_1 = require(12) /* ./assert */;
    var arrayable_1 = require(13) /* ./arrayable */;
    __esExport("min", arrayable_1.min);
    __esExport("max", arrayable_1.max);
    function* range(start, stop, step = 1) {
        (0, assert_1.assert)(step > 0);
        const { abs, ceil, max } = Math;
        if (stop == null) {
            stop = start;
            start = 0;
        }
        const delta = start <= stop ? step : -step;
        const length = max(ceil(abs(stop - start) / step), 0);
        for (let i = 0; i < length; i++, start += delta) {
            yield start;
        }
    }
    exports.range = range;
    function* reverse(array) {
        const n = array.length;
        for (let i = 0; i < n; i++) {
            yield array[n - i - 1];
        }
    }
    exports.reverse = reverse;
    function* enumerate(seq) {
        let i = 0;
        for (const item of seq) {
            yield [item, i++];
        }
    }
    exports.enumerate = enumerate;
    function* take(seq, n) {
        (0, assert_1.assert)(n >= 0);
        let i = 0;
        for (const item of seq) {
            if (i++ < n)
                yield item;
            else
                break;
        }
    }
    exports.take = take;
    function* skip(seq, n) {
        (0, assert_1.assert)(n >= 0);
        for (const value of seq) {
            if (n == 0)
                yield value;
            else
                n -= 1;
        }
    }
    exports.skip = skip;
    function* tail(seq) {
        yield* skip(seq, 1);
    }
    exports.tail = tail;
    function* join(seq, separator) {
        let first = true;
        for (const entry of seq) {
            if (first)
                first = false;
            else if (separator != null)
                yield separator();
            yield* entry;
        }
    }
    exports.join = join;
    function* zip(iterable0, iterable1) {
        const it0 = iterable0[Symbol.iterator]();
        const it1 = iterable1[Symbol.iterator]();
        do {
            const r0 = it0.next();
            const r1 = it1.next();
            if (r0.done === true || r1.done === true)
                break;
            else
                yield [r0.value, r1.value];
        } while (true);
    }
    exports.zip = zip;
    function* interleave(seq, separator) {
        let first = true;
        for (const entry of seq) {
            if (first)
                first = false;
            else
                yield separator();
            yield entry;
        }
    }
    exports.interleave = interleave;
    function* map(iterable, fn) {
        let i = 0;
        for (const item of iterable) {
            yield fn(item, i++);
        }
    }
    exports.map = map;
    function* flat_map(iterable, fn) {
        let i = 0;
        for (const item of iterable) {
            yield* fn(item, i++);
        }
    }
    exports.flat_map = flat_map;
    function every(iterable, predicate) {
        for (const item of iterable) {
            if (!predicate(item))
                return false;
        }
        return true;
    }
    exports.every = every;
    function some(iterable, predicate) {
        for (const item of iterable) {
            if (predicate(item))
                return true;
        }
        return false;
    }
    exports.some = some;
    // https://docs.python.org/3.8/library/itertools.html#itertools.combinations
    function* combinations(seq, r) {
        const n = seq.length;
        if (r > n)
            return;
        const indices = (0, array_1.range)(r);
        yield indices.map((i) => seq[i]);
        while (true) {
            let k;
            for (const i of reverse((0, array_1.range)(r))) {
                if (indices[i] != i + n - r) {
                    k = i;
                    break;
                }
            }
            if (k == null)
                return;
            indices[k] += 1;
            for (const j of (0, array_1.range)(k + 1, r)) {
                indices[j] = indices[j - 1] + 1;
            }
            yield indices.map((i) => seq[i]);
        }
    }
    exports.combinations = combinations;
    function* subsets(seq) {
        for (const k of (0, array_1.range)(seq.length + 1)) {
            yield* combinations(seq, k);
        }
    }
    exports.subsets = subsets;
},
/* core/serialization/buffer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const buffer_1 = require(36) /* ../util/buffer */;
    const eq_1 = require(26) /* ../util/eq */;
    class Buffer {
        constructor(buffer) {
            this.buffer = buffer;
        }
        to_base64() {
            return (0, buffer_1.buffer_to_base64)(this.buffer);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.buffer, that.buffer);
        }
    }
    exports.Buffer = Buffer;
    Buffer.__name__ = "Buffer";
    class Base64Buffer extends Buffer {
        toJSON() {
            return this.to_base64();
        }
    }
    exports.Base64Buffer = Base64Buffer;
    Base64Buffer.__name__ = "Base64Buffer";
},
/* core/util/buffer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function buffer_to_base64(buffer) {
        const bytes = new Uint8Array(buffer);
        const chars = Array.from(bytes).map((b) => String.fromCharCode(b));
        return btoa(chars.join(""));
    }
    exports.buffer_to_base64 = buffer_to_base64;
    function base64_to_buffer(base64) {
        const binary_string = atob(base64);
        const len = binary_string.length;
        const bytes = new Uint8Array(len);
        for (let 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) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 2) {
            const t = x[i];
            x[i] = x[i + 1];
            x[i + 1] = t;
        }
    }
    function swap32(buffer) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 4) {
            let 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) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 8) {
            let 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;
            case "object":
            case "uint8":
            case "int8":
            case "bool":
                break;
        }
    }
    exports.swap = swap;
},
/* core/serialization/reps.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
},
/* core/diagnostics.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class Diagnostics {
        constructor() {
            this.listeners = new Set();
        }
        connect(listener) {
            this.listeners.add(listener);
        }
        disconnect(listener) {
            this.listeners.delete(listener);
        }
        report(obj) {
            for (const listener of this.listeners) {
                listener(obj);
            }
        }
    }
    exports.Diagnostics = Diagnostics;
    Diagnostics.__name__ = "Diagnostics";
    exports.diagnostics = new Diagnostics();
},
/* core/uniforms.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const eq_1 = require(26) /* ./util/eq */;
    const arrayable = tslib_1.__importStar(require(13) /* ./util/arrayable */);
    class Uniform {
        is_Scalar() { return this.is_scalar; }
        is_Vector() { return !this.is_scalar; }
    }
    exports.Uniform = Uniform;
    Uniform.__name__ = "Uniform";
    class UniformScalar extends Uniform {
        constructor(value, length) {
            super();
            this.is_scalar = true;
            this.value = value;
            this.length = length;
        }
        get(_i) {
            return this.value;
        }
        *[Symbol.iterator]() {
            const { length, value } = this;
            for (let i = 0; i < length; i++) {
                yield value;
            }
        }
        select(indices) {
            return new UniformScalar(this.value, indices.count);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.length, that.length) && cmp.eq(this.value, that.value);
        }
    }
    exports.UniformScalar = UniformScalar;
    UniformScalar.__name__ = "UniformScalar";
    class UniformVector extends Uniform {
        constructor(array) {
            super();
            this.is_scalar = false;
            this.array = array;
            this.length = this.array.length;
        }
        get(i) {
            return this.array[i];
        }
        *[Symbol.iterator]() {
            yield* this.array;
        }
        select(indices) {
            const array = indices.select(this.array);
            return new this.constructor(array);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.length, that.length) && cmp.eq(this.array, that.array);
        }
    }
    exports.UniformVector = UniformVector;
    UniformVector.__name__ = "UniformVector";
    class ColorUniformVector extends UniformVector {
        constructor(array) {
            super(array);
            this.array = array;
            this._view = new DataView(array.buffer);
        }
        get(i) {
            return this._view.getUint32(4 * i);
        }
        *[Symbol.iterator]() {
            const n = this.length;
            for (let i = 0; i < n; i++)
                yield this.get(i);
        }
    }
    exports.ColorUniformVector = ColorUniformVector;
    ColorUniformVector.__name__ = "ColorUniformVector";
    function min(u) {
        return u.is_Scalar() ? u.value : arrayable.min(u.array);
    }
    exports.min = min;
    function max(u) {
        return u.is_Scalar() ? u.value : arrayable.max(u.array);
    }
    exports.max = max;
},
/* core/util/string.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const settings_1 = require(29) /* ../settings */;
    function uuid4() {
        // from ipython project
        // http://www.ietf.org/rfc/rfc4122.txt
        const s = new Array(32);
        const hex_digits = "0123456789ABCDEF";
        for (let i = 0; i < 32; i++) {
            s[i] = hex_digits[Math.floor(Math.random() * 0x10)];
        }
        s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[16] = hex_digits[(s[16].charCodeAt(0) & 0x3) | 0x8]; // bits 6-7 of the clock_seq_hi_and_reserved to 01
        return s.join("");
    }
    exports.uuid4 = uuid4;
    let counter = 1000;
    function unique_id(prefix) {
        const id = settings_1.settings.dev ? `j${counter++}` : uuid4();
        if (prefix != null)
            return `${prefix}-${id}`;
        else
            return id;
    }
    exports.unique_id = unique_id;
    function escape(s) {
        return s.replace(/(?:[&<>"'`])/g, (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, (_, 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;
    function insert_text_on_position(destination, position, text_to_be_inserted) {
        const result_text = [];
        result_text.push(destination.slice(0, position));
        result_text.push(text_to_be_inserted);
        result_text.push(destination.slice(position));
        return result_text.join("");
    }
    exports.insert_text_on_position = insert_text_on_position;
},
/* document/events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(26) /* ../core/util/eq */;
    const serialization_1 = require(32) /* ../core/serialization */;
    class DocumentEvent {
        constructor(document) {
            this.document = document;
        }
        get [Symbol.toStringTag]() {
            return this.constructor.__name__;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.document, that.document);
        }
    }
    exports.DocumentEvent = DocumentEvent;
    DocumentEvent.__name__ = "DocumentEvent";
    class DocumentEventBatch extends DocumentEvent {
        constructor(document, events) {
            super(document);
            this.events = events;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.events, that.events);
        }
    }
    exports.DocumentEventBatch = DocumentEventBatch;
    DocumentEventBatch.__name__ = "DocumentEventBatch";
    class DocumentChangedEvent extends DocumentEvent {
    }
    exports.DocumentChangedEvent = DocumentChangedEvent;
    DocumentChangedEvent.__name__ = "DocumentChangedEvent";
    class MessageSentEvent extends DocumentChangedEvent {
        constructor(document, msg_type, msg_data) {
            super(document);
            this.kind = "MessageSent";
            this.msg_type = msg_type;
            this.msg_data = msg_data;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.msg_type, that.msg_type) &&
                cmp.eq(this.msg_data, that.msg_data);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                msg_type: this.msg_type,
                msg_data: serializer.encode(this.msg_data),
            };
        }
    }
    exports.MessageSentEvent = MessageSentEvent;
    MessageSentEvent.__name__ = "MessageSentEvent";
    class ModelChangedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, value) {
            super(document);
            this.kind = "ModelChanged";
            this.model = model;
            this.attr = attr;
            this.value = value;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.value, that.value);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                new: serializer.encode(this.value),
            };
        }
    }
    exports.ModelChangedEvent = ModelChangedEvent;
    ModelChangedEvent.__name__ = "ModelChangedEvent";
    class ColumnDataChangedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, data, cols) {
            super(document);
            this.kind = "ColumnDataChanged";
            this.model = model;
            this.attr = attr;
            this.data = data;
            this.cols = cols;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.data, that.data) &&
                cmp.eq(this.cols, that.cols);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                data: serializer.encode(this.data),
                cols: this.cols,
            };
        }
    }
    exports.ColumnDataChangedEvent = ColumnDataChangedEvent;
    ColumnDataChangedEvent.__name__ = "ColumnDataChangedEvent";
    class ColumnsStreamedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, data, rollover) {
            super(document);
            this.kind = "ColumnsStreamed";
            this.model = model;
            this.attr = attr;
            this.data = data;
            this.rollover = rollover;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.data, that.data) &&
                cmp.eq(this.rollover, that.rollover);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                data: serializer.encode(this.data),
                rollover: this.rollover,
            };
        }
    }
    exports.ColumnsStreamedEvent = ColumnsStreamedEvent;
    ColumnsStreamedEvent.__name__ = "ColumnsStreamedEvent";
    class ColumnsPatchedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, patches) {
            super(document);
            this.kind = "ColumnsPatched";
            this.model = model;
            this.attr = attr;
            this.patches = patches;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.patches, that.patches);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                attr: this.attr,
                model: this.model.ref(),
                patches: serializer.encode(this.patches),
            };
        }
    }
    exports.ColumnsPatchedEvent = ColumnsPatchedEvent;
    ColumnsPatchedEvent.__name__ = "ColumnsPatchedEvent";
    class TitleChangedEvent extends DocumentChangedEvent {
        constructor(document, title) {
            super(document);
            this.kind = "TitleChanged";
            this.title = title;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.title, that.title);
        }
        [serialization_1.serialize](_serializer) {
            return {
                kind: this.kind,
                title: this.title,
            };
        }
    }
    exports.TitleChangedEvent = TitleChangedEvent;
    TitleChangedEvent.__name__ = "TitleChangedEvent";
    class RootAddedEvent extends DocumentChangedEvent {
        constructor(document, model) {
            super(document);
            this.kind = "RootAdded";
            this.model = model;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: serializer.encode(this.model),
            };
        }
    }
    exports.RootAddedEvent = RootAddedEvent;
    RootAddedEvent.__name__ = "RootAddedEvent";
    class RootRemovedEvent extends DocumentChangedEvent {
        constructor(document, model) {
            super(document);
            this.kind = "RootRemoved";
            this.model = model;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model);
        }
        [serialization_1.serialize](_serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
            };
        }
    }
    exports.RootRemovedEvent = RootRemovedEvent;
    RootRemovedEvent.__name__ = "RootRemovedEvent";
},
/* core/util/pretty.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ./types */;
    const object_1 = require(9) /* ./object */;
    exports.pretty = Symbol("pretty");
    function is_Printable(obj) {
        return (0, types_1.isObject)(obj) && exports.pretty in obj;
    }
    class Printer {
        constructor(options) {
            this.visited = new Set();
            this.precision = options === null || options === void 0 ? void 0 : options.precision;
        }
        to_string(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 if (obj instanceof ArrayBuffer)
                return this.array_buffer(obj);
            else
                return `${obj}`;
        }
        token(val) {
            return val;
        }
        boolean(val) {
            return `${val}`;
        }
        number(val) {
            if (this.precision != null)
                return val.toFixed(this.precision);
            else
                return `${val}`;
        }
        string(val) {
            const sq = val.includes("'");
            const dq = val.includes('"');
            if (sq && dq)
                return `\`${val.replace(/`/g, "\\`")}\``;
            else if (dq)
                return `'${val}'`;
            else
                return `"${val}"`;
        }
        symbol(val) {
            return val.toString();
        }
        array(obj) {
            const T = this.token;
            const items = [];
            for (const entry of obj) {
                items.push(this.to_string(entry));
            }
            return `${T("[")}${items.join(`${T(",")} `)}${T("]")}`;
        }
        iterable(obj) {
            var _a;
            const T = this.token;
            const tag = (_a = Object(obj)[Symbol.toStringTag]) !== null && _a !== void 0 ? _a : "Object";
            const items = this.array(obj);
            return `${tag}${T("(")}${items}${T(")")}`;
        }
        object(obj) {
            const T = this.token;
            const items = [];
            for (const [key, val] of (0, object_1.entries)(obj)) {
                items.push(`${key}${T(":")} ${this.to_string(val)}`);
            }
            return `${T("{")}${items.join(`${T(",")} `)}${T("}")}`;
        }
        array_buffer(obj) {
            return `ArrayBuffer(#${obj.byteLength})`;
        }
    }
    exports.Printer = Printer;
    Printer.__name__ = "Printer";
    function to_string(obj, options) {
        const printer = new Printer(options);
        return printer.to_string(obj);
    }
    exports.to_string = to_string;
},
/* core/patching.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    const set_1 = require(44) /* ./util/set */;
    const typed_array = tslib_1.__importStar(require(45) /* ./util/typed_array */);
    // exported for testing
    function stream_to_column(col, new_col, rollover) {
        if ((0, types_1.isArray)(col) && (0, types_1.isArray)(new_col)) {
            const result = col.concat(new_col);
            if (rollover != null && result.length > rollover)
                return result.slice(-rollover);
            else
                return result;
        }
        const total_len = col.length + new_col.length;
        // handle rollover case for typed arrays
        if (rollover != null && total_len > rollover) {
            const start = total_len - rollover;
            const end = col.length;
            // resize col if it is shorter than the rollover length
            const result = (() => {
                if (col.length < rollover) {
                    const ctor = (() => {
                        if ((0, types_1.isTypedArray)(col))
                            return col.constructor;
                        else if ((0, types_1.isTypedArray)(new_col))
                            return new_col.constructor;
                        else
                            throw new Error("unsupported array types");
                    })();
                    const result = new ctor(rollover);
                    result.set(col, 0);
                    return result;
                }
                else
                    return col;
            })();
            // shift values in original col to accommodate new_col
            for (let i = start, endi = end; i < endi; i++) {
                result[i - start] = result[i];
            }
            // update end values in col with new_col
            for (let i = 0, endi = new_col.length; i < endi; i++) {
                result[i + (end - start)] = new_col[i];
            }
            return result;
        }
        else {
            const col_ = (() => {
                if ((0, types_1.isTypedArray)(col))
                    return col;
                else if ((0, types_1.isTypedArray)(new_col))
                    return new new_col.constructor(col);
                else
                    throw new Error("unsupported array types");
            })();
            return typed_array.concat(col_, new_col);
        }
    }
    exports.stream_to_column = stream_to_column;
    // exported for testing
    function slice(ind, length) {
        let 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) {
        const patched = new Set();
        let patched_range = false;
        for (const [ind, val] of patch) {
            // make the single index case look like the length-3 multi-index case
            let shape;
            let item;
            let index;
            let value;
            if ((0, types_1.isArray)(ind)) {
                const [i] = ind;
                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
            let flat_index = 0;
            const [istart, istop, istep] = slice(index[1], shape[0]);
            const [jstart, jstop, jstep] = slice(index[2], shape[1]);
            for (let i = istart; i < istop; i += istep) {
                for (let j = jstart; j < jstop; j += jstep) {
                    if (patched_range) {
                        patched.add(j);
                    }
                    item[i * shape[1] + j] = value[flat_index];
                    flat_index++;
                }
            }
        }
        return patched;
    }
    exports.patch_to_column = patch_to_column;
    function stream_to_columns(data, new_data, rollover) {
        for (const [name, new_column] of (0, object_1.entries)(new_data)) {
            data[name] = stream_to_column(data[name], new_column, rollover);
        }
    }
    exports.stream_to_columns = stream_to_columns;
    function patch_to_columns(data, patches) {
        let patched = new Set();
        for (const [column, patch] of (0, object_1.entries)(patches)) {
            patched = (0, set_1.union)(patched, patch_to_column(data[column], patch)); // XXX
        }
        return patched;
    }
    exports.patch_to_columns = patch_to_columns;
},
/* core/util/set.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function union(...sets) {
        const result = new Set();
        for (const set of sets) {
            for (const item of set) {
                result.add(item);
            }
        }
        return result;
    }
    exports.union = union;
    function intersection(set, ...sets) {
        const result = new Set();
        top: for (const item of set) {
            for (const other of sets) {
                if (!other.has(item))
                    continue top;
            }
            result.add(item);
        }
        return result;
    }
    exports.intersection = intersection;
    function difference(set, ...sets) {
        const result = new Set(set);
        for (const item of union(...sets)) {
            result.delete(item);
        }
        return result;
    }
    exports.difference = difference;
},
/* core/util/typed_array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function concat(array0, ...arrays) {
        let n = array0.length;
        for (const array of arrays)
            n += array.length;
        const result = new array0.constructor(n);
        result.set(array0, 0);
        let i = array0.length;
        for (const array of arrays) {
            result.set(array, i);
            i += array.length;
        }
        return result;
    }
    exports.concat = concat;
},
/* core/resolvers.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class ModelResolver {
        constructor(parent, models = []) {
            this._known_models = new Map();
            this.parent = parent;
            for (const model of models) {
                this.register(model);
            }
        }
        get(name) {
            var _a, _b, _c;
            return (_c = (_a = this._known_models.get(name)) !== null && _a !== void 0 ? _a : (_b = this.parent) === null || _b === void 0 ? void 0 : _b.get(name)) !== null && _c !== void 0 ? _c : null;
        }
        register(model, force = false) {
            const name = model.__qualified__;
            if (force || this.get(name) == null)
                this._known_models.set(name, model);
            else
                console.warn(`Model '${name}' was already registered with this resolver`);
        }
        get names() {
            return [...this._known_models.keys()];
        }
    }
    exports.ModelResolver = ModelResolver;
    ModelResolver.__name__ = "ModelResolver";
},
/* core/serialization/deserializer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const logging_1 = require(19) /* ../logging */;
    const refs_1 = require(17) /* ../util/refs */;
    const ndarray_1 = require(30) /* ../util/ndarray */;
    const object_1 = require(9) /* ../util/object */;
    const array_1 = require(10) /* ../util/array */;
    const platform_1 = require(27) /* ../util/platform */;
    const buffer_1 = require(36) /* ../util/buffer */;
    const types_1 = require(8) /* ../util/types */;
    const slice_1 = require(48) /* ../util/slice */;
    const _decoders = new Map();
    class DeserializationError extends Error {
    }
    exports.DeserializationError = DeserializationError;
    DeserializationError.__name__ = "DeserializationError";
    class Deserializer {
        static register(type, decoder) {
            if (!_decoders.has(type))
                _decoders.set(type, decoder);
            else
                throw new Error(`'${type}' already registered for decoding`);
        }
        constructor(resolver, references = new Map(), finalize) {
            this._decoding = false;
            this._buffers = new Map();
            this._finalizable = new Set();
            this.resolver = resolver;
            this.references = references;
            this.finalize = finalize;
        }
        decode(obj /*AnyVal*/, buffers) {
            var _a;
            if (buffers != null) {
                for (const [id, buffer] of buffers) {
                    this._buffers.set(id, buffer);
                }
            }
            if (this._decoding) {
                return this._decode(obj);
            }
            this._decoding = true;
            let finalizable;
            const decoded = (() => {
                try {
                    return this._decode(obj);
                }
                finally {
                    finalizable = new Set(this._finalizable);
                    this._decoding = false;
                    this._buffers.clear();
                    this._finalizable.clear();
                }
            })();
            for (const instance of finalizable) {
                (_a = this.finalize) === null || _a === void 0 ? void 0 : _a.call(this, instance);
                instance.finalize();
                instance.assert_initialized();
            }
            // `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 (const instance of finalizable) {
                instance.connect_signals();
            }
            return decoded;
        }
        _decode(obj /*AnyVal*/) {
            if ((0, types_1.isArray)(obj)) {
                return this._decode_plain_array(obj);
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                if ((0, types_1.isString)(obj.type)) {
                    const decoder = _decoders.get(obj.type);
                    if (decoder != null) {
                        return decoder(obj, this);
                    }
                    switch (obj.type) {
                        case "ref":
                            return this._decode_ref(obj);
                        case "symbol":
                            return this._decode_symbol(obj);
                        case "number":
                            return this._decode_number(obj);
                        case "array":
                            return this._decode_array(obj);
                        case "set":
                            return this._decode_set(obj);
                        case "map":
                            return this._decode_map(obj);
                        case "bytes":
                            return this._decode_bytes(obj);
                        case "slice":
                            return this._decode_slice(obj);
                        case "date":
                            return this._decode_date(obj);
                        case "value":
                            return this._decode_value(obj);
                        case "field":
                            return this._decode_field(obj);
                        case "expr":
                            return this._decode_expr(obj);
                        case "typed_array":
                            return this._decode_typed_array(obj);
                        case "ndarray":
                            return this._decode_ndarray(obj);
                        case "object": {
                            if ((0, types_1.isString)(obj.id)) {
                                return this._decode_object_ref(obj);
                            }
                            else {
                                return this._decode_object(obj);
                            }
                        }
                        default: {
                            this.error(`unable to decode an object of type '${obj.type}'`);
                        }
                    }
                }
                else if ((0, types_1.isString)(obj.id)) {
                    return this._decode_ref(obj);
                }
                else {
                    return this._decode_plain_object(obj);
                }
            }
            else
                return obj;
        }
        _decode_symbol(obj) {
            this.error(`can't resolve named symbol '${obj.name}'`); // TODO: implement symbol resolution
        }
        _decode_number(obj) {
            if ("value" in obj) {
                const { value } = obj;
                if ((0, types_1.isString)(value)) {
                    switch (value) {
                        case "nan": return NaN;
                        case "+inf": return +Infinity;
                        case "-inf": return -Infinity;
                    }
                }
                else if ((0, types_1.isNumber)(value))
                    return value;
            }
            this.error(`invalid number representation '${obj}'`);
        }
        _decode_plain_array(obj) {
            return (0, array_1.map)(obj, (item) => this._decode(item));
        }
        _decode_plain_object(obj) {
            const decoded = {};
            for (const [key, val] of (0, object_1.entries)(obj)) {
                decoded[key] = this._decode(val);
            }
            return decoded;
        }
        _decode_array(obj) {
            var _a;
            const decoded = [];
            for (const entry of (_a = obj.entries) !== null && _a !== void 0 ? _a : []) {
                decoded.push(this._decode(entry));
            }
            return decoded;
        }
        _decode_set(obj) {
            var _a;
            const decoded = new Set();
            for (const entry of (_a = obj.entries) !== null && _a !== void 0 ? _a : []) {
                decoded.add(this._decode(entry));
            }
            return decoded;
        }
        _decode_map(obj) {
            var _a;
            const decoded = (0, array_1.map)((_a = obj.entries) !== null && _a !== void 0 ? _a : [], ([key, val]) => [this._decode(key), this._decode(val)]);
            const is_str = (0, array_1.every)(decoded, ([key]) => (0, types_1.isString)(key));
            if (is_str) {
                const obj = {}; // Object.create(null)
                for (const [key, val] of decoded) {
                    obj[key] = val;
                }
                return obj;
            }
            else
                return new Map(decoded);
        }
        _decode_bytes(obj) {
            const { data } = obj;
            if ((0, refs_1.is_ref)(data)) {
                const buffer = this._buffers.get(data.id);
                if (buffer != null)
                    return buffer;
                else
                    this.error(`buffer for id=${data.id} not found`);
            }
            else if ((0, types_1.isString)(data))
                return (0, buffer_1.base64_to_buffer)(data);
            else
                return data.buffer;
        }
        _decode_slice(obj) {
            const start = this._decode(obj.start);
            const stop = this._decode(obj.stop);
            const step = this._decode(obj.step);
            return new slice_1.Slice({ start, stop, step });
        }
        _decode_date(obj) {
            const iso = this._decode(obj.iso);
            return new Date(iso);
        }
        _decode_value(obj) {
            const value = this._decode(obj.value);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { value, transform, units };
        }
        _decode_field(obj) {
            const field = this._decode(obj.field);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { field, transform, units };
        }
        _decode_expr(obj) {
            const expr = this._decode(obj.expr);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { expr, transform, units };
        }
        _decode_typed_array(obj) {
            const { array, order, dtype } = obj;
            const buffer = this._decode(array);
            if (order != platform_1.BYTE_ORDER) {
                (0, buffer_1.swap)(buffer, dtype);
            }
            switch (dtype) {
                case "uint8": return new Uint8Array(buffer);
                case "int8": return new Int8Array(buffer);
                case "uint16": return new Uint16Array(buffer);
                case "int16": return new Int16Array(buffer);
                case "uint32": return new Uint32Array(buffer);
                case "int32": return new Int32Array(buffer);
                // case "uint64": return new BigInt64Array(buffer)
                // case "int64":  return new BigInt64Array(buffer)
                case "float32": return new Float32Array(buffer);
                case "float64": return new Float64Array(buffer);
                default:
                    this.error(`unsupported dtype '${dtype}'`);
            }
        }
        _decode_ndarray(obj) {
            const { array, order, dtype, shape } = obj;
            const decoded = this._decode(array);
            if (decoded instanceof ArrayBuffer && order != platform_1.BYTE_ORDER) {
                (0, buffer_1.swap)(decoded, dtype);
            }
            return (0, ndarray_1.ndarray)(decoded /*XXX*/, { dtype, shape });
        }
        _decode_object(obj) {
            const { type, attributes } = obj;
            const cls = this._resolve_type(type);
            if (attributes != null)
                return new cls(this._decode(attributes));
            else
                return new cls();
        }
        _decode_ref(obj) {
            const instance = this.references.get(obj.id);
            if (instance != null)
                return instance;
            else
                this.error(`reference ${obj.id} isn't known`);
        }
        _decode_object_ref(obj) {
            const ref = this.references.get(obj.id);
            if (ref != null) {
                this.warning(`reference already known '${obj.id}'`);
                return ref;
            }
            const { id, name: type, attributes } = obj;
            const cls = this._resolve_type(type);
            const instance = new cls({ id });
            this.references.set(id, instance);
            const decoded_attributes = this._decode(attributes !== null && attributes !== void 0 ? attributes : {});
            instance.initialize_props(new object_1.Dict(decoded_attributes));
            this._finalizable.add(instance);
            return instance;
        }
        error(message) {
            throw new DeserializationError(message);
        }
        warning(message) {
            logging_1.logger.warn(message);
        }
        _resolve_type(type) {
            const cls = this.resolver.get(type);
            if (cls != null)
                return cls;
            else
                this.error(`could not resolve type '${type}', which could be due to a widget or a custom model not being registered before first usage`);
        }
    }
    exports.Deserializer = Deserializer;
    Deserializer.__name__ = "Deserializer";
},
/* core/util/slice.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const serialization_1 = require(32) /* ../serialization */;
    class Slice {
        constructor({ start, stop, step } = {}) {
            this.start = start !== null && start !== void 0 ? start : null;
            this.stop = stop !== null && stop !== void 0 ? stop : null;
            this.step = step !== null && step !== void 0 ? step : null;
        }
        [serialization_1.serialize](serializer) {
            return {
                type: "slice",
                start: serializer.encode(this.start),
                stop: serializer.encode(this.stop),
                step: serializer.encode(this.step),
            };
        }
    }
    exports.Slice = Slice;
    Slice.__name__ = "Slice";
},
/* core/util/version.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function pyify_version(version) {
        return version.replace(/-(dev|rc)\./, ".$1");
    }
    exports.pyify_version = pyify_version;
},
/* model.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const has_props_1 = require(14) /* ./core/has_props */;
    const types_1 = require(8) /* ./core/util/types */;
    const object_1 = require(9) /* ./core/util/object */;
    const eq_1 = require(26) /* ./core/util/eq */;
    const logging_1 = require(19) /* ./core/logging */;
    class Model extends has_props_1.HasProps {
        get is_syncable() {
            return this.syncable;
        }
        [eq_1.equals](that, cmp) {
            return (cmp.structural ? true : cmp.eq(this.id, that.id)) && super[eq_1.equals](that, cmp);
        }
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._js_callbacks = new Map();
        }
        connect_signals() {
            super.connect_signals();
            this._update_property_callbacks();
            this.connect(this.properties.js_property_callbacks.change, () => this._update_property_callbacks());
            this.connect(this.properties.js_event_callbacks.change, () => this._update_event_callbacks());
            this.connect(this.properties.subscribed_events.change, () => this._update_event_callbacks());
        }
        /*protected*/ _process_event(event) {
            var _b;
            for (const callback of (_b = (0, object_1.dict)(this.js_event_callbacks).get(event.event_name)) !== null && _b !== void 0 ? _b : [])
                callback.execute(event);
            if (this.document != null && this.subscribed_events.has(event.event_name))
                this.document.event_manager.send_event(event);
        }
        trigger_event(event) {
            if (this.document != null) {
                event.origin = this;
                this.document.event_manager.trigger(event);
            }
        }
        _update_event_callbacks() {
            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);
        }
        _update_property_callbacks() {
            const signal_for = (event) => {
                const [evt, attr = null] = event.split(":");
                return attr != null ? this.properties[attr][evt] : this[evt];
            };
            for (const [event, callbacks] of this._js_callbacks) {
                const signal = signal_for(event);
                for (const cb of callbacks)
                    this.disconnect(signal, cb);
            }
            this._js_callbacks.clear();
            for (const [event, callbacks] of (0, object_1.dict)(this.js_property_callbacks)) {
                const wrappers = callbacks.map((cb) => () => cb.execute(this));
                this._js_callbacks.set(event, wrappers);
                const signal = signal_for(event);
                for (const cb of wrappers)
                    this.connect(signal, cb);
            }
        }
        _doc_attached() {
            if (!(0, object_1.dict)(this.js_event_callbacks).is_empty || this.subscribed_events.size != 0)
                this._update_event_callbacks();
        }
        _doc_detached() {
            this.document.event_manager.subscribed_models.delete(this);
        }
        select(selector) {
            if ((0, types_1.isString)(selector))
                return [...this.references()].filter((ref) => ref instanceof _a && ref.name === selector);
            else if ((0, types_1.isPlainObject)(selector) && "type" in selector)
                return [...this.references()].filter((ref) => ref.type == selector.type);
            else if (selector.prototype instanceof has_props_1.HasProps)
                return [...this.references()].filter((ref) => ref instanceof selector);
            else
                throw new Error(`invalid selector ${selector}`);
        }
        select_one(selector) {
            const 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 ${selector}`);
            }
        }
        on_event(event, callback) {
            var _b;
            const name = (0, types_1.isString)(event) ? event : event.prototype.event_name;
            this.js_event_callbacks[name] = [
                ...(_b = (0, object_1.dict)(this.js_event_callbacks).get(name)) !== null && _b !== void 0 ? _b : [],
                (0, types_1.isFunction)(callback) ? { execute: callback } : callback,
            ];
        }
    }
    exports.Model = Model;
    _a = Model;
    Model.__name__ = "Model";
    (() => {
        _a.define(({ Any, Unknown, Boolean, String, Array, Set, Dict, Nullable }) => ({
            tags: [Array(Unknown), []],
            name: [Nullable(String), null],
            js_property_callbacks: [Dict(Array(Any /*TODO*/)), {}],
            js_event_callbacks: [Dict(Array(Any /*TODO*/)), {}],
            subscribed_events: [Set(String), new globalThis.Set()],
            syncable: [Boolean, true],
        }));
    })();
},
/* document/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(50) /* ../model */;
    const kinds = tslib_1.__importStar(require(21) /* ../core/kinds */);
    const types_1 = require(8) /* ../core/util/types */;
    const object_1 = require(9) /* ../core/util/object */;
    function decode_def(def, deserializer) {
        var _a, _b;
        var _c;
        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 "Bytes": return kinds.Bytes;
                    case "String": return kinds.String;
                    case "Null": return kinds.Null;
                }
            }
            else {
                switch (ref[0]) {
                    case "Regex": {
                        const [, regex, flags] = ref;
                        return kinds.Regex(new RegExp(regex, flags));
                    }
                    case "Nullable": {
                        const [, subref] = ref;
                        return kinds.Nullable(kind_of(subref));
                    }
                    case "Or": {
                        const [, subref, ...subrefs] = ref;
                        return kinds.Or(kind_of(subref), ...subrefs.map(kind_of));
                    }
                    case "Tuple": {
                        const [, subref, ...subrefs] = ref;
                        return kinds.Tuple(kind_of(subref), ...subrefs.map(kind_of));
                    }
                    case "Array": {
                        const [, subref] = ref;
                        return kinds.Array(kind_of(subref));
                    }
                    case "Struct": {
                        const [, ...entryrefs] = ref;
                        const entries = entryrefs.map(([key, valref]) => [key, kind_of(valref)]);
                        return kinds.Struct((0, object_1.to_object)(entries));
                    }
                    case "Dict": {
                        const [, valref] = ref;
                        return kinds.Dict(kind_of(valref));
                    }
                    case "Map": {
                        const [, keyref, valref] = ref;
                        return kinds.Map(kind_of(keyref), kind_of(valref));
                    }
                    case "Enum": {
                        const [, ...items] = ref;
                        return kinds.Enum(...items);
                    }
                    case "Ref": {
                        const [, modelref] = ref;
                        const model = deserializer.resolver.get(modelref.id);
                        if (model != null)
                            return kinds.Ref(model);
                        else
                            throw new Error(`${modelref.id} wasn't defined before referencing it`);
                    }
                    case "AnyRef": {
                        return kinds.AnyRef();
                    }
                }
            }
        }
        const base = (() => {
            var _a, _b;
            const name = (_b = (_a = def.extends) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : "Model";
            if (name == "Model") // TODO: support base classes in general
                return model_1.Model;
            const base = deserializer.resolver.get(name);
            if (base != null)
                return base;
            else
                throw new Error(`base model ${name} of ${def.name} is not defined`);
        })();
        const model = (_c = class extends base {
        },
            tslib_1.__setFunctionName(_c, "model"),
            _c.__qualified__ = def.name,
            _c);
        function decode(value) {
            if (value === undefined)
                return value;
            else
                return deserializer.decode(value);
        }
        for (const prop of (_a = def.properties) !== null && _a !== void 0 ? _a : []) {
            const kind = kind_of(prop.kind);
            model.define({ [prop.name]: [kind, decode(prop.default)] });
        }
        for (const prop of (_b = def.overrides) !== null && _b !== void 0 ? _b : []) {
            model.override({ [prop.name]: decode(prop.default) });
        }
        deserializer.resolver.register(model);
        return model;
    }
    exports.decode_def = decode_def;
},
/* core/bokeh_events.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3;
    __esModule();
    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;
    };
    const serialization_1 = require(32) /* ./serialization */;
    const eq_1 = require(26) /* ./util/eq */;
    const kinds_1 = require(21) /* ./kinds */;
    exports.KeyModifiers = (0, kinds_1.PartialStruct)({
        shift: kinds_1.Boolean,
        ctrl: kinds_1.Boolean,
        alt: kinds_1.Boolean,
    });
    function event(event_name) {
        return (cls) => {
            cls.prototype.event_name = event_name;
        };
    }
    class BokehEvent {
        [serialization_1.serialize](serializer) {
            const { event_name: name, event_values } = this;
            const values = serializer.encode(event_values);
            return { type: "event", name, values };
        }
        [eq_1.equals](that, cmp) {
            return this.event_name == that.event_name && cmp.eq(this.event_values, that.event_values);
        }
    }
    exports.BokehEvent = BokehEvent;
    _a = BokehEvent;
    BokehEvent.__name__ = "BokehEvent";
    (() => {
        _a.prototype.publish = true;
    })();
    class ModelEvent extends BokehEvent {
        constructor() {
            super(...arguments);
            this.origin = null;
        }
        get event_values() {
            return { model: this.origin };
        }
    }
    exports.ModelEvent = ModelEvent;
    ModelEvent.__name__ = "ModelEvent";
    class DocumentEvent extends BokehEvent {
    }
    exports.DocumentEvent = DocumentEvent;
    DocumentEvent.__name__ = "DocumentEvent";
    let DocumentReady = (_b = class DocumentReady extends DocumentEvent {
        get event_values() {
            return {};
        }
    },
        _b.__name__ = "DocumentReady",
        _b);
    exports.DocumentReady = DocumentReady;
    exports.DocumentReady = DocumentReady = __decorate([
        event("document_ready")
    ], DocumentReady);
    class ConnectionEvent extends DocumentEvent {
    }
    exports.ConnectionEvent = ConnectionEvent;
    ConnectionEvent.__name__ = "ConnectionEvent";
    class ConnectionLost extends ConnectionEvent {
        constructor() {
            super(...arguments);
            this.timestamp = new Date();
        }
        get event_values() {
            const { timestamp } = this;
            return { timestamp };
        }
    }
    exports.ConnectionLost = ConnectionLost;
    _c = ConnectionLost;
    ConnectionLost.__name__ = "ConnectionLost";
    (() => {
        _c.prototype.event_name = "connection_lost";
        _c.prototype.publish = false;
    })();
    let ButtonClick = (_d = class ButtonClick extends ModelEvent {
    },
        _d.__name__ = "ButtonClick",
        _d);
    exports.ButtonClick = ButtonClick;
    exports.ButtonClick = ButtonClick = __decorate([
        event("button_click")
    ], ButtonClick);
    let MenuItemClick = (_e = class MenuItemClick extends ModelEvent {
        constructor(item) {
            super();
            this.item = item;
        }
        get event_values() {
            const { item } = this;
            return Object.assign(Object.assign({}, super.event_values), { item });
        }
    },
        _e.__name__ = "MenuItemClick",
        _e);
    exports.MenuItemClick = MenuItemClick;
    exports.MenuItemClick = MenuItemClick = __decorate([
        event("menu_item_click")
    ], MenuItemClick);
    let ValueSubmit = (_f = class ValueSubmit extends ModelEvent {
        constructor(value) {
            super();
            this.value = value;
        }
        get event_values() {
            const { value } = this;
            return Object.assign(Object.assign({}, super.event_values), { value });
        }
    },
        _f.__name__ = "ValueSubmit",
        _f);
    exports.ValueSubmit = ValueSubmit;
    exports.ValueSubmit = ValueSubmit = __decorate([
        event("value_submit")
    ], ValueSubmit);
    // A UIEvent is an event originating on a canvas this includes.
    // DOM events such as keystrokes as well as hammer, LOD, and range events.
    class UIEvent extends ModelEvent {
    }
    exports.UIEvent = UIEvent;
    UIEvent.__name__ = "UIEvent";
    let LODStart = (_g = class LODStart extends UIEvent {
    },
        _g.__name__ = "LODStart",
        _g);
    exports.LODStart = LODStart;
    exports.LODStart = LODStart = __decorate([
        event("lodstart")
    ], LODStart);
    let LODEnd = (_h = class LODEnd extends UIEvent {
    },
        _h.__name__ = "LODEnd",
        _h);
    exports.LODEnd = LODEnd;
    exports.LODEnd = LODEnd = __decorate([
        event("lodend")
    ], LODEnd);
    let RangesUpdate = (_j = class RangesUpdate extends UIEvent {
        constructor(x0, x1, y0, y1) {
            super();
            this.x0 = x0;
            this.x1 = x1;
            this.y0 = y0;
            this.y1 = y1;
        }
        get event_values() {
            const { x0, x1, y0, y1 } = this;
            return Object.assign(Object.assign({}, super.event_values), { x0, x1, y0, y1 });
        }
    },
        _j.__name__ = "RangesUpdate",
        _j);
    exports.RangesUpdate = RangesUpdate;
    exports.RangesUpdate = RangesUpdate = __decorate([
        event("rangesupdate")
    ], RangesUpdate);
    let SelectionGeometry = (_k = class SelectionGeometry extends UIEvent {
        constructor(geometry, final) {
            super();
            this.geometry = geometry;
            this.final = final;
        }
        get event_values() {
            const { geometry, final } = this;
            return Object.assign(Object.assign({}, super.event_values), { geometry, final });
        }
    },
        _k.__name__ = "SelectionGeometry",
        _k);
    exports.SelectionGeometry = SelectionGeometry;
    exports.SelectionGeometry = SelectionGeometry = __decorate([
        event("selectiongeometry")
    ], SelectionGeometry);
    let Reset = (_l = class Reset extends UIEvent {
    },
        _l.__name__ = "Reset",
        _l);
    exports.Reset = Reset;
    exports.Reset = Reset = __decorate([
        event("reset")
    ], Reset);
    class PointEvent extends UIEvent {
        constructor(sx, sy, x, y, modifiers) {
            super();
            this.sx = sx;
            this.sy = sy;
            this.x = x;
            this.y = y;
            this.modifiers = modifiers;
        }
        get event_values() {
            const { sx, sy, x, y, modifiers } = this;
            return Object.assign(Object.assign({}, super.event_values), { sx, sy, x, y, modifiers });
        }
    }
    exports.PointEvent = PointEvent;
    PointEvent.__name__ = "PointEvent";
    let Pan = (_m = class Pan extends PointEvent {
        /* TODO: direction: -1 | 1 */
        constructor(sx, sy, x, y, delta_x, delta_y, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.delta_x = delta_x;
            this.delta_y = delta_y;
        }
        get event_values() {
            const { delta_x, delta_y /*, direction*/ } = this;
            return Object.assign(Object.assign({}, super.event_values), { delta_x, delta_y /*, direction*/ });
        }
    },
        _m.__name__ = "Pan",
        _m);
    exports.Pan = Pan;
    exports.Pan = Pan = __decorate([
        event("pan")
    ], Pan);
    let Pinch = (_o = class Pinch extends PointEvent {
        constructor(sx, sy, x, y, scale, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.scale = scale;
        }
        get event_values() {
            const { scale } = this;
            return Object.assign(Object.assign({}, super.event_values), { scale });
        }
    },
        _o.__name__ = "Pinch",
        _o);
    exports.Pinch = Pinch;
    exports.Pinch = Pinch = __decorate([
        event("pinch")
    ], Pinch);
    let Rotate = (_p = class Rotate extends PointEvent {
        constructor(sx, sy, x, y, rotation, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.rotation = rotation;
        }
        get event_values() {
            const { rotation } = this;
            return Object.assign(Object.assign({}, super.event_values), { rotation });
        }
    },
        _p.__name__ = "Rotate",
        _p);
    exports.Rotate = Rotate;
    exports.Rotate = Rotate = __decorate([
        event("rotate")
    ], Rotate);
    let MouseWheel = (_q = class MouseWheel extends PointEvent {
        constructor(sx, sy, x, y, delta, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.delta = delta;
        }
        get event_values() {
            const { delta } = this;
            return Object.assign(Object.assign({}, super.event_values), { delta });
        }
    },
        _q.__name__ = "MouseWheel",
        _q);
    exports.MouseWheel = MouseWheel;
    exports.MouseWheel = MouseWheel = __decorate([
        event("wheel")
    ], MouseWheel);
    let MouseMove = (_r = class MouseMove extends PointEvent {
    },
        _r.__name__ = "MouseMove",
        _r);
    exports.MouseMove = MouseMove;
    exports.MouseMove = MouseMove = __decorate([
        event("mousemove")
    ], MouseMove);
    let MouseEnter = (_s = class MouseEnter extends PointEvent {
    },
        _s.__name__ = "MouseEnter",
        _s);
    exports.MouseEnter = MouseEnter;
    exports.MouseEnter = MouseEnter = __decorate([
        event("mouseenter")
    ], MouseEnter);
    let MouseLeave = (_t = class MouseLeave extends PointEvent {
    },
        _t.__name__ = "MouseLeave",
        _t);
    exports.MouseLeave = MouseLeave;
    exports.MouseLeave = MouseLeave = __decorate([
        event("mouseleave")
    ], MouseLeave);
    let Tap = (_u = class Tap extends PointEvent {
    },
        _u.__name__ = "Tap",
        _u);
    exports.Tap = Tap;
    exports.Tap = Tap = __decorate([
        event("tap")
    ], Tap);
    let DoubleTap = (_v = class DoubleTap extends PointEvent {
    },
        _v.__name__ = "DoubleTap",
        _v);
    exports.DoubleTap = DoubleTap;
    exports.DoubleTap = DoubleTap = __decorate([
        event("doubletap")
    ], DoubleTap);
    let Press = (_w = class Press extends PointEvent {
    },
        _w.__name__ = "Press",
        _w);
    exports.Press = Press;
    exports.Press = Press = __decorate([
        event("press")
    ], Press);
    let PressUp = (_x = class PressUp extends PointEvent {
    },
        _x.__name__ = "PressUp",
        _x);
    exports.PressUp = PressUp;
    exports.PressUp = PressUp = __decorate([
        event("pressup")
    ], PressUp);
    let PanStart = (_y = class PanStart extends PointEvent {
    },
        _y.__name__ = "PanStart",
        _y);
    exports.PanStart = PanStart;
    exports.PanStart = PanStart = __decorate([
        event("panstart")
    ], PanStart);
    let PanEnd = (_z = class PanEnd extends PointEvent {
    },
        _z.__name__ = "PanEnd",
        _z);
    exports.PanEnd = PanEnd;
    exports.PanEnd = PanEnd = __decorate([
        event("panend")
    ], PanEnd);
    let PinchStart = (_0 = class PinchStart extends PointEvent {
    },
        _0.__name__ = "PinchStart",
        _0);
    exports.PinchStart = PinchStart;
    exports.PinchStart = PinchStart = __decorate([
        event("pinchstart")
    ], PinchStart);
    let PinchEnd = (_1 = class PinchEnd extends PointEvent {
    },
        _1.__name__ = "PinchEnd",
        _1);
    exports.PinchEnd = PinchEnd;
    exports.PinchEnd = PinchEnd = __decorate([
        event("pinchend")
    ], PinchEnd);
    let RotateStart = (_2 = class RotateStart extends PointEvent {
    },
        _2.__name__ = "RotateStart",
        _2);
    exports.RotateStart = RotateStart;
    exports.RotateStart = RotateStart = __decorate([
        event("rotatestart")
    ], RotateStart);
    let RotateEnd = (_3 = class RotateEnd extends PointEvent {
    },
        _3.__name__ = "RotateEnd",
        _3);
    exports.RotateEnd = RotateEnd;
    exports.RotateEnd = RotateEnd = __decorate([
        event("rotateend")
    ], RotateEnd);
},
/* embed/standalone.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const document_1 = require(5) /* ../document */;
    const view_1 = require(54) /* ../core/view */;
    const dom_view_1 = require(55) /* ../core/dom_view */;
    const build_views_1 = require(59) /* ../core/build_views */;
    const types_1 = require(8) /* ../core/util/types */;
    // A map from the root model IDs to their views.
    exports.index = new Proxy(new view_1.ViewManager(), {
        get(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return view;
                }
            }
            return Reflect.get(manager, property);
        },
        has(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return true;
                }
            }
            return Reflect.has(manager, property);
        },
        ownKeys(manager) {
            return manager.roots.map((root) => root.model.id);
        },
        getOwnPropertyDescriptor(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return { configurable: true, enumerable: true, writable: false, value: view };
                }
            }
            return Reflect.getOwnPropertyDescriptor(manager, property);
        },
    });
    async function add_document_standalone(document, element, roots = [], use_for_title = false) {
        // this is a LOCAL index of views used only by this particular rendering
        // call, so we can remove the views we create.
        const views = new view_1.ViewManager([], delete_view);
        async function render_view(model) {
            var _a;
            const view = await (0, build_views_1.build_view)(model, { parent: null, owner: views });
            if (view instanceof dom_view_1.DOMView) {
                const i = document.roots().indexOf(model);
                const root_el = (_a = roots[i]) !== null && _a !== void 0 ? _a : element;
                view.render_to(root_el);
            }
            views.add(view);
            exports.index.add(view);
        }
        async function render_model(model) {
            if (model.default_view != null) {
                await render_view(model);
            }
            else {
                document.notify_idle(model);
            }
        }
        function unrender_model(model) {
            const view = views.get(model);
            if (view != null) {
                delete_view(view);
            }
        }
        function delete_view(view) {
            view.remove();
            views.delete(view);
            exports.index.delete(view);
        }
        for (const model of document.roots()) {
            await render_model(model);
        }
        if (use_for_title) {
            window.document.title = document.title();
        }
        document.on_change((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 views;
    }
    exports.add_document_standalone = add_document_standalone;
},
/* core/view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const signaling_1 = require(15) /* ./signaling */;
    const types_1 = require(8) /* ./util/types */;
    class View {
        get ready() {
            return this._ready;
        }
        *children() { }
        mark_finished() {
            this._has_finished = true;
        }
        connect(signal, slot) {
            let new_slot = this._slots.get(slot);
            if (new_slot == null) {
                new_slot = (args, sender) => {
                    const promise = Promise.resolve(slot.call(this, args, sender));
                    this._ready = this._ready.then(() => promise);
                    if (this.root != this) {
                        this.root._ready = this.root._ready.then(() => this._ready);
                    }
                };
                this._slots.set(slot, new_slot);
            }
            return signal.connect(new_slot, this);
        }
        disconnect(signal, slot) {
            return signal.disconnect(slot, this);
        }
        constructor(options) {
            this.removed = new signaling_1.Signal0(this, "removed");
            this._ready = Promise.resolve(undefined);
            /** @internal */
            this._slots = new WeakMap();
            this._removed = false;
            this._idle_notified = false;
            const { model, parent, owner } = options;
            this.model = model;
            this.parent = parent;
            if (parent == null) {
                this.root = this;
                this.owner = owner !== null && owner !== void 0 ? owner : new ViewManager([this]);
            }
            else {
                this.root = parent.root;
                this.owner = this.root.owner;
            }
        }
        initialize() {
            this._has_finished = false;
        }
        async lazy_initialize() { }
        remove() {
            this.disconnect_signals();
            this.removed.emit();
            this._removed = true;
        }
        toString() {
            return `${this.model.type}View(${this.model.id})`;
        }
        serializable_state() {
            return { type: this.model.type };
        }
        get is_root() {
            return this.parent == null;
        }
        has_finished() {
            return this._has_finished;
        }
        get is_idle() {
            return this.has_finished();
        }
        connect_signals() { }
        disconnect_signals() {
            signaling_1.Signal.disconnect_receiver(this);
        }
        on_change(properties, fn) {
            for (const property of (0, types_1.isArray)(properties) ? properties : [properties]) {
                this.connect(property.change, fn);
            }
        }
        cursor(_sx, _sy) {
            return null;
        }
        notify_finished() {
            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);
                    }
                }
            }
        }
    }
    exports.View = View;
    View.__name__ = "View";
    class ViewManager {
        constructor(roots = [], drop) {
            this.drop = drop;
            this._roots = new Set(roots);
        }
        toString() {
            const views = [...this._roots].map((view) => `${view}`).join(", ");
            return `ViewManager(${views})`;
        }
        get(model) {
            for (const view of this._roots) {
                if (view.model == model)
                    return view;
            }
            return null;
        }
        get_by_id(id) {
            for (const view of this._roots) {
                if (view.model.id == id)
                    return view;
            }
            return null;
        }
        add(view) {
            this._roots.add(view);
        }
        delete(view) {
            this._roots.delete(view);
        }
        clear() {
            var _a;
            const drop = (_a = this.drop) !== null && _a !== void 0 ? _a : ((view) => this.delete(view));
            for (const view of this) {
                drop(view);
            }
        }
        /* TODO (TS 5.2)
        [Symbol.dispose](): void {
          this.clear()
        }
        */
        get roots() {
            return [...this._roots];
        }
        *[Symbol.iterator]() {
            yield* this._roots;
        }
        *views() {
            yield* this.query(() => true);
        }
        *query(fn) {
            const visited = new Set();
            function* descend(view) {
                if (visited.has(view)) {
                    return;
                }
                visited.add(view);
                if (fn(view)) {
                    yield view;
                }
                for (const child of view.children()) {
                    yield* descend(child);
                }
            }
            for (const root of this._roots) {
                yield* descend(root);
            }
        }
        query_one(fn) {
            for (const view of this.query(fn)) {
                return view;
            }
            return null;
        }
        *find(model) {
            yield* this.query((view) => view.model == model);
        }
        *find_by_id(id) {
            yield* this.query((view) => view.model.id == id);
        }
        find_one(model) {
            for (const view of this.find(model)) {
                return view;
            }
            return null;
        }
        find_one_by_id(id) {
            for (const view of this.find_by_id(id)) {
                return view;
            }
            return null;
        }
        get_one(model) {
            const view = this.find_one(model);
            if (view != null)
                return view;
            else
                throw new Error(`cannot find a view for ${model}`);
        }
        get_one_by_id(id) {
            const view = this.find_one_by_id(id);
            if (view != null)
                return view;
            else
                throw new Error(`cannot find a view for a model with '${id}' identity`);
        }
        find_all(model) {
            return [...this.find(model)];
        }
        find_all_by_id(id) {
            return [...this.find_by_id(id)];
        }
    }
    exports.ViewManager = ViewManager;
    ViewManager.__name__ = "ViewManager";
},
/* core/dom_view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const view_1 = require(54) /* ./view */;
    const dom_1 = require(56) /* ./dom */;
    const types_1 = require(8) /* ./util/types */;
    const base_css_1 = tslib_1.__importDefault(require(58) /* ../styles/base.css */);
    class DOMView extends view_1.View {
        get children_el() {
            var _a;
            return (_a = this.shadow_el) !== null && _a !== void 0 ? _a : this.el;
        }
        initialize() {
            super.initialize();
            this.el = this._createElement();
        }
        remove() {
            (0, dom_1.remove)(this.el);
            super.remove();
        }
        stylesheets() {
            return [];
        }
        css_classes() {
            return [];
        }
        render_to(element) {
            element.appendChild(this.el);
            this.render();
        }
        finish() {
            this._has_finished = true;
            this.notify_finished();
        }
        _createElement() {
            return (0, dom_1.createElement)(this.constructor.tag_name, { class: this.css_classes() });
        }
    }
    exports.DOMView = DOMView;
    DOMView.__name__ = "DOMView";
    DOMView.tag_name = "div";
    class DOMElementView extends DOMView {
        initialize() {
            super.initialize();
            this.class_list = new dom_1.ClassList(this.el.classList);
        }
    }
    exports.DOMElementView = DOMElementView;
    DOMElementView.__name__ = "DOMElementView";
    class DOMComponentView extends DOMElementView {
        constructor() {
            super(...arguments);
            this._applied_stylesheets = [];
            this._applied_css_classes = [];
        }
        initialize() {
            super.initialize();
            this.shadow_el = this.el.attachShadow({ mode: "open" });
        }
        stylesheets() {
            return [...super.stylesheets(), base_css_1.default];
        }
        empty() {
            (0, dom_1.empty)(this.shadow_el);
            this.class_list.clear();
            this._applied_css_classes = [];
            this._applied_stylesheets = [];
        }
        render() {
            this.empty();
            this._update_stylesheets();
            this._update_css_classes();
        }
        *_stylesheets() {
            for (const style of this.stylesheets()) {
                yield (0, types_1.isString)(style) ? new dom_1.InlineStyleSheet(style) : style;
            }
        }
        *_css_classes() {
            yield `bk-${this.model.type.replace(/\./g, "-")}`;
            yield* this.css_classes();
        }
        _apply_stylesheets(stylesheets) {
            this._applied_stylesheets.push(...stylesheets);
            stylesheets.forEach((stylesheet) => stylesheet.install(this.shadow_el));
        }
        _apply_css_classes(classes) {
            this._applied_css_classes.push(...classes);
            this.class_list.add(...classes);
        }
        _update_stylesheets() {
            this._applied_stylesheets.forEach((stylesheet) => stylesheet.uninstall());
            this._applied_stylesheets = [];
            this._apply_stylesheets([...this._stylesheets()]);
        }
        _update_css_classes() {
            this.class_list.remove(this._applied_css_classes);
            this._applied_css_classes = [];
            this._apply_css_classes([...this._css_classes()]);
        }
    }
    exports.DOMComponentView = DOMComponentView;
    DOMComponentView.__name__ = "DOMComponentView";
},
/* core/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.supports_adopted_stylesheets = exports.px = exports.dom_ready = exports.GlobalImportedStyleSheet = void 0;
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    const bbox_1 = require(57) /* ./util/bbox */;
    const _createElement = (tag) => {
        return (attrs = {}, ...children) => {
            const element = document.createElement(tag);
            if (!(0, types_1.isPlainObject)(attrs)) {
                children = [attrs, ...children];
                attrs = {};
            }
            for (let [attr, value] of (0, object_1.entries)(attrs)) {
                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)) {
                        for (const cls of value) {
                            if (cls != null)
                                element.classList.add(cls);
                        }
                        continue;
                    }
                }
                if (attr === "style" && (0, types_1.isPlainObject)(value)) {
                    for (const [prop, data] of (0, object_1.entries)(value)) {
                        element.style[prop] = data;
                    }
                    continue;
                }
                if (attr === "data" && (0, types_1.isPlainObject)(value)) {
                    for (const [key, data] of (0, object_1.entries)(value)) {
                        element.dataset[key] = data; // XXX: attrs needs a better type
                    }
                    continue;
                }
                element.setAttribute(attr, value);
            }
            function append(child) {
                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) {
                    for (const el of child) {
                        element.appendChild(el);
                    }
                }
                else if (child != null && child !== false)
                    throw new Error(`expected a DOM element, string, false or null, got ${JSON.stringify(child)}`);
            }
            for (const child of children) {
                if ((0, types_1.isArray)(child)) {
                    for (const _child of child)
                        append(_child);
                }
                else
                    append(child);
            }
            return element;
        };
    };
    function createElement(tag, attrs, ...children) {
        return _createElement(tag)(attrs, ...children);
    }
    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.legend = _createElement("legend"), exports.fieldset = _createElement("fieldset"), exports.input = _createElement("input"), exports.select = _createElement("select"), exports.option = _createElement("option"), exports.optgroup = _createElement("optgroup"), exports.textarea = _createElement("textarea");
    function createSVGElement(tag, attrs = null, ...children) {
        const element = document.createElementNS("http://www.w3.org/2000/svg", tag);
        for (const [attr, value] of (0, object_1.entries)(attrs !== null && attrs !== void 0 ? attrs : {})) {
            if (value == null || value === false)
                continue;
            element.setAttribute(attr, value);
        }
        function append(child) {
            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) {
                for (const el of child) {
                    element.appendChild(el);
                }
            }
            else if (child != null && child !== false)
                throw new Error(`expected a DOM element, string, false or null, got ${JSON.stringify(child)}`);
        }
        for (const child of children) {
            if ((0, types_1.isArray)(child)) {
                for (const _child of child)
                    append(_child);
            }
            else
                append(child);
        }
        return element;
    }
    exports.createSVGElement = createSVGElement;
    function text(str) {
        return document.createTextNode(str);
    }
    exports.text = text;
    function nbsp() {
        return text("\u00a0");
    }
    exports.nbsp = nbsp;
    function append(element, ...children) {
        for (const child of children)
            element.appendChild(child);
    }
    exports.append = append;
    function remove(element) {
        const parent = element.parentNode;
        if (parent != null) {
            parent.removeChild(element);
        }
    }
    exports.remove = remove;
    function replaceWith(element, replacement) {
        const parent = element.parentNode;
        if (parent != null) {
            parent.replaceChild(replacement, element);
        }
    }
    exports.replaceWith = replaceWith;
    function prepend(element, ...nodes) {
        const first = element.firstChild;
        for (const node of nodes) {
            element.insertBefore(node, first);
        }
    }
    exports.prepend = prepend;
    function empty(node, attrs = false) {
        let child;
        while ((child = node.firstChild) != null) {
            node.removeChild(child);
        }
        if (attrs && node instanceof Element) {
            for (const attr of node.attributes) {
                node.removeAttributeNode(attr);
            }
        }
    }
    exports.empty = empty;
    function contains(element, child) {
        /**
         * Like Node.contains(), but traverses Shadow DOM boundaries.
         */
        let current = child;
        while (current.parentNode != null) {
            const parent = current.parentNode;
            if (parent == element) {
                return true;
            }
            else if (parent instanceof ShadowRoot) {
                current = parent.host;
            }
            else {
                current = parent;
            }
        }
        return false;
    }
    exports.contains = contains;
    function display(element, display = true) {
        element.style.display = display ? "" : "none";
    }
    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_bbox(element) {
        const { top, left, width, height } = element.getBoundingClientRect();
        return new bbox_1.BBox({
            left: left + scrollX - document.documentElement.clientLeft,
            top: top + scrollY - document.documentElement.clientTop,
            width,
            height,
        });
    }
    exports.offset_bbox = offset_bbox;
    function parent(el, selector) {
        let node = el;
        while ((node = node.parentElement) != null) {
            if (node.matches(selector))
                return node;
        }
        return null;
    }
    exports.parent = parent;
    function num(value) {
        const num = parseFloat(value);
        return isFinite(num) ? num : 0;
    }
    function extents(el) {
        const 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) {
        const 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) {
        const { margin: { left, right, top, bottom } } = extents(el);
        const { width, height } = size(el);
        return {
            width: Math.ceil(width + left + right),
            height: Math.ceil(height + top + bottom),
        };
    }
    exports.outer_size = outer_size;
    function content_size(el) {
        var _a;
        const { left, top } = el.getBoundingClientRect();
        const { padding } = extents(el);
        let width = 0;
        let height = 0;
        for (const child of ((_a = el.shadowRoot) !== null && _a !== void 0 ? _a : el).children) {
            const 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));
        }
        return { width, height };
    }
    exports.content_size = content_size;
    function bounding_box(el) {
        const { x, y, width, height } = el.getBoundingClientRect();
        return new bbox_1.BBox({ x, y, width, height });
    }
    exports.bounding_box = bounding_box;
    function box_size(el) {
        const { width, height } = el.getBoundingClientRect();
        return { width, height };
    }
    exports.box_size = box_size;
    function position(el, box, margin) {
        const { style } = el;
        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 {
            const { top, right, bottom, left } = margin;
            style.margin = `${top}px ${right}px ${bottom}px ${left}px`;
        }
    }
    exports.position = position;
    class ClassList {
        constructor(class_list) {
            this.class_list = class_list;
        }
        get values() {
            const values = [];
            for (let i = 0; i < this.class_list.length; i++) {
                const item = this.class_list.item(i);
                if (item != null)
                    values.push(item);
            }
            return values;
        }
        has(cls) {
            return this.class_list.contains(cls);
        }
        add(...classes) {
            for (const cls of classes)
                this.class_list.add(cls);
            return this;
        }
        remove(...classes) {
            for (const cls of classes) {
                if ((0, types_1.isArray)(cls)) {
                    cls.forEach((cls) => this.class_list.remove(cls));
                }
                else {
                    this.class_list.remove(cls);
                }
            }
            return this;
        }
        clear() {
            for (const cls of this.values) {
                this.class_list.remove(cls);
            }
            return this;
        }
        toggle(cls, activate) {
            const add = activate != null ? activate : !this.has(cls);
            if (add)
                this.add(cls);
            else
                this.remove(cls);
            return this;
        }
    }
    exports.ClassList = ClassList;
    ClassList.__name__ = "ClassList";
    function classes(el) {
        return new ClassList(el.classList);
    }
    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 (MouseButton) {
        MouseButton[MouseButton["None"] = 0] = "None";
        MouseButton[MouseButton["Primary"] = 1] = "Primary";
        MouseButton[MouseButton["Secondary"] = 2] = "Secondary";
        MouseButton[MouseButton["Auxiliary"] = 4] = "Auxiliary";
        MouseButton[MouseButton["Left"] = 1] = "Left";
        MouseButton[MouseButton["Right"] = 2] = "Right";
        MouseButton[MouseButton["Middle"] = 4] = "Middle";
    })(exports.MouseButton || (exports.MouseButton = {}));
    class StyleSheet {
        install(el) {
            el.append(this.el);
        }
        uninstall() {
            this.el.remove();
        }
    }
    exports.StyleSheet = StyleSheet;
    StyleSheet.__name__ = "StyleSheet";
    class InlineStyleSheet extends StyleSheet {
        constructor(css) {
            super();
            this.el = (0, exports.style)({ type: "text/css" }, css);
        }
        clear() {
            this.replace("");
        }
        *_to_rules(styles) {
            // TODO: prefixing
            for (const [attr, value] of (0, object_1.entries)(styles)) {
                if (value != null) {
                    const name = attr.replace(/_/g, "-");
                    yield `${name}: ${value};`;
                }
            }
        }
        _to_css(css, styles) {
            if (styles == null)
                return css;
            else
                return `${css}{${[...this._to_rules(styles)].join("")}}`;
        }
        replace(css, styles) {
            this.el.textContent = this._to_css(css, styles);
        }
        prepend(css, styles) {
            var _a;
            const text = (_a = this.el.textContent) !== null && _a !== void 0 ? _a : "";
            this.el.textContent = `${this._to_css(css, styles)}\n${text}`;
        }
        append(css, styles) {
            var _a;
            const text = (_a = this.el.textContent) !== null && _a !== void 0 ? _a : "";
            this.el.textContent = `${text}\n${this._to_css(css, styles)}`;
        }
        remove() {
            remove(this.el);
        }
    }
    exports.InlineStyleSheet = InlineStyleSheet;
    InlineStyleSheet.__name__ = "InlineStyleSheet";
    class GlobalInlineStyleSheet extends InlineStyleSheet {
        install() {
            if (!this.el.isConnected) {
                document.head.appendChild(this.el);
            }
        }
    }
    exports.GlobalInlineStyleSheet = GlobalInlineStyleSheet;
    GlobalInlineStyleSheet.__name__ = "GlobalInlineStyleSheet";
    class ImportedStyleSheet extends StyleSheet {
        constructor(url) {
            super();
            this.el = (0, exports.link)({ rel: "stylesheet", href: url });
        }
        replace(url) {
            this.el.href = url;
        }
        remove() {
            remove(this.el);
        }
    }
    exports.ImportedStyleSheet = ImportedStyleSheet;
    ImportedStyleSheet.__name__ = "ImportedStyleSheet";
    class GlobalImportedStyleSheet extends ImportedStyleSheet {
        install() {
            if (!this.el.isConnected) {
                document.head.appendChild(this.el);
            }
        }
    }
    exports.GlobalImportedStyleSheet = GlobalImportedStyleSheet;
    GlobalImportedStyleSheet.__name__ = "GlobalImportedStyleSheet";
    async function dom_ready() {
        if (document.readyState == "loading") {
            return new Promise((resolve, _reject) => {
                document.addEventListener("DOMContentLoaded", () => resolve(), { once: true });
            });
        }
    }
    exports.dom_ready = dom_ready;
    function px(value) {
        return `${value}px`;
    }
    exports.px = px;
    exports.supports_adopted_stylesheets = "adoptedStyleSheets" in ShadowRoot.prototype;
},
/* core/util/bbox.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(24) /* ../types */;
    const eq_1 = require(26) /* ./eq */;
    const arrayable_1 = require(13) /* ./arrayable */;
    const { min, max, round } = Math;
    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 _min(a, b) {
        if (isNaN(a))
            return b;
        else if (isNaN(b))
            return a;
        else
            return min(a, b);
    }
    function _max(a, b) {
        if (isNaN(a))
            return b;
        else if (isNaN(b))
            return a;
        else
            return max(a, b);
    }
    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;
    class BBox {
        constructor(box, correct = false) {
            if (box == null) {
                this.x0 = 0;
                this.y0 = 0;
                this.x1 = 0;
                this.y1 = 0;
            }
            else if ("x0" in box) {
                const { x0, y0, x1, y1 } = box;
                if (!isFinite(x0 + y0 + x1 + y1)) {
                    this.x0 = NaN;
                    this.y0 = NaN;
                    this.x1 = NaN;
                    this.y1 = NaN;
                }
                else {
                    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) {
                const { x, y, width, height } = box;
                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 {
                let left, right;
                let top, bottom;
                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 {
                        const 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 {
                        const h2 = box.height / 2;
                        top = box.vcenter - h2;
                        bottom = box.vcenter + h2;
                    }
                }
                else {
                    top = box.top;
                    bottom = box.bottom;
                }
                if (left > right || top > bottom) {
                    if (correct) {
                        if (left > right)
                            left = right;
                        if (top > bottom)
                            top = bottom;
                    }
                    else
                        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;
            }
        }
        static from_lrtb({ left, right, top, bottom }) {
            return new BBox({
                x0: Math.min(left, right),
                y0: Math.min(top, bottom),
                x1: Math.max(left, right),
                y1: Math.max(top, bottom),
            });
        }
        clone() {
            return new BBox(this);
        }
        equals(that) {
            return this.x0 == that.x0 && this.y0 == that.y0 &&
                this.x1 == that.x1 && this.y1 == that.y1;
        }
        [eq_1.equals](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);
        }
        toString() {
            return `BBox({left: ${this.left}, top: ${this.top}, width: ${this.width}, height: ${this.height}})`;
        }
        get is_valid() {
            const { x0, x1, y0, y1 } = this;
            return isFinite(x0 + x1 + y0 + y1);
        }
        get is_empty() {
            const { x0, x1, y0, y1 } = this;
            return x0 == 0 && x1 == 0 && y0 == 0 && y1 == 0;
        }
        get left() { return this.x0; }
        get top() { return this.y0; }
        get right() { return this.x1; }
        get bottom() { return this.y1; }
        get p0() { return { x: this.x0, y: this.y0 }; }
        get p1() { return { x: this.x1, y: this.y1 }; }
        get x() { return this.x0; }
        get y() { return this.y0; }
        get width() { return this.x1 - this.x0; }
        get height() { return this.y1 - this.y0; }
        get size() { return { width: this.width, height: this.height }; }
        get rect() {
            const { x0, y0, x1, y1 } = this;
            return {
                p0: { x: x0, y: y0 },
                p1: { x: x1, y: y0 },
                p2: { x: x1, y: y1 },
                p3: { x: x0, y: y1 },
            };
        }
        get box() {
            const { x, y, width, height } = this;
            return { x, y, width, height };
        }
        get lrtb() {
            const { left, right, top, bottom } = this;
            return { left, right, top, bottom };
        }
        get x_range() { return { start: this.x0, end: this.x1 }; }
        get y_range() { return { start: this.y0, end: this.y1 }; }
        get h_range() { return this.x_range; }
        get v_range() { return this.y_range; }
        get ranges() { return [this.x_range, this.y_range]; }
        get aspect() { return this.width / this.height; }
        get hcenter() { return (this.left + this.right) / 2; }
        get vcenter() { return (this.top + this.bottom) / 2; }
        get area() { return this.width * this.height; }
        round() {
            return new BBox({
                x0: round(this.x0),
                x1: round(this.x1),
                y0: round(this.y0),
                y1: round(this.y1),
            });
        }
        relative() {
            const { width, height } = this;
            return new BBox({ x: 0, y: 0, width, height });
        }
        translate(tx, ty) {
            const { x, y, width, height } = this;
            return new BBox({ x: tx + x, y: ty + y, width, height });
        }
        scale(factor) {
            return new BBox({
                x0: this.x0 * factor,
                x1: this.x1 * factor,
                y0: this.y0 * factor,
                y1: this.y1 * factor,
            });
        }
        relativize(x, y) {
            return [x - this.x, y - this.y];
        }
        contains(x, y) {
            return this.x0 <= x && x <= this.x1 && this.y0 <= y && y <= this.y1;
        }
        clip(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];
        }
        grow_by(size) {
            return new BBox({
                left: this.left - size,
                right: this.right + size,
                top: this.top - size,
                bottom: this.bottom + size,
            });
        }
        shrink_by(size) {
            return new BBox({
                left: this.left + size,
                right: this.right - size,
                top: this.top + size,
                bottom: this.bottom - size,
            }, true);
        }
        union(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),
            });
        }
        intersection(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),
                });
            }
        }
        intersects(that) {
            return !(that.x1 < this.x0 || that.x0 > this.x1 ||
                that.y1 < this.y0 || that.y0 > this.y1);
        }
        get x_screen() {
            var _a;
            const self = this;
            return (_a = this._x_screen) !== null && _a !== void 0 ? _a : (this._x_screen = {
                compute(x) {
                    return self.left + x;
                },
                invert(sx) {
                    return sx - self.left;
                },
                v_compute(xs) {
                    const { left } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(xs, (x) => left + x));
                },
                v_invert(sxs) {
                    const { left } = self;
                    return (0, arrayable_1.map)(sxs, (sx) => sx - left);
                },
                get source_range() {
                    return self.x_range;
                },
                get target_range() {
                    return self.x_range;
                },
            });
        }
        get y_screen() {
            var _a;
            const self = this;
            return (_a = this._y_screen) !== null && _a !== void 0 ? _a : (this._y_screen = {
                compute(y) {
                    return self.top + y;
                },
                invert(sy) {
                    return sy - self.top;
                },
                v_compute(ys) {
                    const { top } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(ys, (y) => top + y));
                },
                v_invert(sys) {
                    const { top } = self;
                    return (0, arrayable_1.map)(sys, (sy) => sy - top);
                },
                get source_range() {
                    return self.y_range;
                },
                get target_range() {
                    return self.y_range;
                },
            });
        }
        get x_view() {
            var _a;
            const self = this;
            return (_a = this._x_view) !== null && _a !== void 0 ? _a : (this._x_view = {
                compute(x) {
                    return self.left + x;
                },
                invert(sx) {
                    return sx - self.left;
                },
                v_compute(xs) {
                    const { left } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(xs, (x) => left + x));
                },
                v_invert(sxs) {
                    const { left } = self;
                    return (0, arrayable_1.map)(sxs, (sx) => sx - left);
                },
                get source_range() {
                    return self.x_range;
                },
                get target_range() {
                    return self.x_range;
                },
            });
        }
        get y_view() {
            var _a;
            const self = this;
            return (_a = this._y_view) !== null && _a !== void 0 ? _a : (this._y_view = {
                compute(y) {
                    return self.bottom - y;
                },
                invert(sy) {
                    return self.bottom - sy;
                },
                v_compute(ys) {
                    const { bottom } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(ys, (y) => bottom - y));
                },
                v_invert(sys) {
                    const { bottom } = self;
                    return (0, arrayable_1.map)(sys, (sy) => bottom - sy);
                },
                get source_range() {
                    return self.y_range;
                },
                get target_range() {
                    return { start: self.bottom, end: self.top };
                },
            });
        }
        get xview() {
            return this.x_view;
        }
        get yview() {
            return this.y_view;
        }
    }
    exports.BBox = BBox;
    BBox.__name__ = "BBox";
},
/* styles/base.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{--base-font:var(--bokeh-base-font, Helvetica, Arial, sans-serif);--mono-font:var(--bokeh-mono-font, monospace);--font-size:12px;--line-height:calc(20 / 14);--line-height-computed:calc(var(--font-size) * var(--line-height));--border-radius:4px;--padding-vertical:6px;--padding-horizontal:12px;}:host{box-sizing:border-box;font-family:var(--base-font);font-size:13px;line-height:var(--line-height);}*,*:before,*:after{box-sizing:inherit;font-family:inherit;}pre,code{font-family:var(--mono-font);margin:0;}`;
},
/* core/build_views.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(10) /* ./util/array */;
    const assert_1 = require(12) /* ./util/assert */;
    async function _build_view(view_cls, model, options) {
        (0, assert_1.assert)(view_cls != null, "model doesn't implement a view");
        const view = new view_cls(Object.assign(Object.assign({}, options), { model }));
        view.initialize();
        await view.lazy_initialize();
        return view;
    }
    async function build_view(model, options = { parent: null }, cls = (model) => model.default_view) {
        const view = await _build_view(cls(model), model, options);
        view.connect_signals();
        return view;
    }
    exports.build_view = build_view;
    async function build_views(view_storage, models, options = { parent: null }, cls = (model) => model.default_view) {
        const to_remove = (0, array_1.difference)([...view_storage.keys()], models);
        const removed_views = [];
        for (const model of to_remove) {
            const view = view_storage.get(model);
            if (view != null) {
                view_storage.delete(model);
                removed_views.push(view);
                view.remove();
            }
        }
        const created_views = [];
        const new_models = models.filter((model) => !view_storage.has(model));
        for (const model of new_models) {
            const view = await _build_view(cls(model), model, options);
            view_storage.set(model, view);
            created_views.push(view);
        }
        for (const view of created_views)
            view.connect_signals();
        return {
            created: created_views,
            removed: removed_views,
        };
    }
    exports.build_views = build_views;
    function remove_views(view_storage) {
        for (const [model, view] of view_storage) {
            view.remove();
            view_storage.delete(model);
        }
    }
    exports.remove_views = remove_views;
},
/* embed/server.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const connection_1 = require(61) /* ../client/connection */;
    const logging_1 = require(19) /* ../core/logging */;
    const standalone_1 = require(53) /* ./standalone */;
    // @internal
    function _get_ws_url(app_path, absolute_url) {
        let protocol = "ws:";
        if (window.location.protocol == "https:")
            protocol = "wss:";
        let 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;
    const _sessions = new Map();
    function _get_session(websocket_url, token, args_string) {
        const session_id = (0, connection_1.parse_token)(token).session_id;
        if (!_sessions.has(websocket_url))
            _sessions.set(websocket_url, new Map());
        const subsessions = _sessions.get(websocket_url);
        if (!subsessions.has(session_id))
            subsessions.set(session_id, (0, connection_1.pull_session)(websocket_url, token, args_string));
        return subsessions.get(session_id);
    }
    // Fill element with the roots from token
    async function add_document_from_session(websocket_url, token, element, roots = [], use_for_title = false) {
        const args_string = window.location.search.substring(1);
        let session;
        try {
            session = await _get_session(websocket_url, token, args_string);
        }
        catch (error) {
            const session_id = (0, connection_1.parse_token)(token).session_id;
            logging_1.logger.error(`Failed to load Bokeh session ${session_id}: ${error}`);
            throw error;
        }
        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();
    const logging_1 = require(19) /* ../core/logging */;
    const document_1 = require(5) /* ../document */;
    const message_1 = require(62) /* ../protocol/message */;
    const receiver_1 = require(63) /* ../protocol/receiver */;
    const session_1 = require(64) /* ./session */;
    exports.DEFAULT_SERVER_WEBSOCKET_URL = "ws://localhost:5006/ws";
    exports.DEFAULT_TOKEN = "eyJzZXNzaW9uX2lkIjogImRlZmF1bHQifQ";
    let _connection_count = 0;
    function parse_token(token) {
        let payload = token.split(".")[0];
        const 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;
    class ClientConnection {
        constructor(url = exports.DEFAULT_SERVER_WEBSOCKET_URL, token = exports.DEFAULT_TOKEN, args_string = null) {
            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.url = url;
            this.token = token;
            this.args_string = args_string;
            this.id = parse_token(token).session_id.split(".")[0];
            logging_1.logger.debug(`Creating websocket ${this._number} to '${this.url}' session '${this.id}'`);
        }
        async connect() {
            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 {
                let 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 new Promise((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 = () => this._on_open(resolve, reject);
                    this.socket.onmessage = (event) => this._on_message(event);
                    this.socket.onclose = (event) => this._on_close(event, reject);
                    this.socket.onerror = () => this._on_error(reject);
                });
            }
            catch (error) {
                logging_1.logger.error(`websocket creation failed to url: ${this.url}`);
                logging_1.logger.error(` - ${error}`);
                throw error;
            }
        }
        close() {
            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();
            }
        }
        _schedule_reconnect(milliseconds) {
            const retry = () => {
                var _a;
                // 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`);
                    (_a = this.session) === null || _a === void 0 ? void 0 : _a.notify_connection_lost();
                }
                return;
                /*
                } else {
                  logger.debug(`Attempting to reconnect websocket ${this._number}`)
                  this.connect()
                }
                */
            };
            setTimeout(retry, milliseconds);
        }
        send(message) {
            if (this.socket != null)
                message.send(this.socket);
            else
                logging_1.logger.error("not connected so cannot send", message);
        }
        async send_with_reply(message) {
            const reply = await new Promise((resolve, reject) => {
                this._pending_replies.set(message.msgid(), { resolve, reject });
                this.send(message);
            });
            if (reply.msgtype() == "ERROR")
                throw new Error(`Error reply ${reply.content.text}`);
            else
                return reply;
        }
        async _pull_doc_json() {
            const message = message_1.Message.create("PULL-DOC-REQ", {}, {});
            const reply = await this.send_with_reply(message);
            if (!("doc" in reply.content))
                throw new Error("No 'doc' field in PULL-DOC-REPLY");
            return reply.content.doc;
        }
        async _repull_session_doc(resolve, reject) {
            logging_1.logger.debug(this.session != null ? "Repulling session" : "Pulling session for first time");
            try {
                const doc_json = await this._pull_doc_json();
                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 {
                        const events = [];
                        const document = document_1.Document.from_json(doc_json, events);
                        this.session = new session_1.ClientSession(this, document);
                        // Send back change events that happend during model initialization.
                        for (const event of events) {
                            document._trigger_on_change(event);
                        }
                        for (const msg of this._pending_messages) {
                            this.session.handle(msg);
                        }
                        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.
                }
            }
            catch (error) {
                console.trace(error);
                logging_1.logger.error(`Failed to repull session ${error}`);
                reject(error instanceof Error ? error : `${error}`);
            }
        }
        _on_open(resolve, reject) {
            logging_1.logger.info(`Websocket connection ${this._number} is now open`);
            this._current_handler = (message) => {
                this._awaiting_ack_handler(message, resolve, reject);
            };
        }
        _on_message(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}`);
            }
            const msg = this._receiver.message;
            if (msg != null) {
                const problem = msg.problem();
                if (problem != null)
                    this._close_bad_protocol(problem);
                this._current_handler(msg);
            }
        }
        _on_close(event, reject) {
            logging_1.logger.info(`Lost websocket ${this._number} connection, ${event.code} (${event.reason})`);
            this.socket = null;
            this._pending_replies.forEach((pr) => 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})`));
        }
        _on_error(reject) {
            logging_1.logger.debug(`Websocket error on socket ${this._number}`);
            const msg = "Could not open websocket";
            logging_1.logger.error(`Failed to connect to Bokeh server: ${msg}`);
            reject(new Error(msg));
        }
        _close_bad_protocol(detail) {
            logging_1.logger.error(`Closing connection: ${detail}`);
            if (this.socket != null)
                this.socket.close(1002, detail); // 1002 = protocol error
        }
        _awaiting_ack_handler(message, resolve, reject) {
            if (message.msgtype() === "ACK") {
                this._current_handler = (message) => 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");
        }
        _steady_state_handler(message) {
            const reqid = message.reqid();
            const pr = this._pending_replies.get(reqid);
            if (pr != null) {
                this._pending_replies.delete(reqid);
                pr.resolve(message);
            }
            else if (this.session != null) {
                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);
            }
        }
    }
    exports.ClientConnection = ClientConnection;
    ClientConnection.__name__ = "ClientConnection";
    function pull_session(url, token, args_string) {
        const 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();
    const serialization_1 = require(32) /* ../core/serialization */;
    const string_1 = require(40) /* ../core/util/string */;
    const assert_1 = require(12) /* ../core/util/assert */;
    class Message {
        get buffers() {
            return this._buffers;
        }
        constructor(header, metadata, content) {
            this._buffers = new Map();
            this.header = header;
            this.metadata = metadata;
            this.content = content;
        }
        static assemble(header_json, metadata_json, content_json) {
            const header = JSON.parse(header_json);
            const metadata = JSON.parse(metadata_json);
            const content = JSON.parse(content_json);
            return new Message(header, metadata, content);
        }
        assemble_buffer(buf_header, buf_payload) {
            var _a;
            const nb = (_a = this.header.num_buffers) !== null && _a !== void 0 ? _a : 0;
            if (nb <= this._buffers.size)
                throw new Error(`too many buffers received, expecting ${nb}`);
            const { id } = JSON.parse(buf_header);
            this._buffers.set(id, buf_payload);
        }
        static create(msgtype, metadata, content) {
            const header = Message.create_header(msgtype);
            return new Message(header, metadata, content);
        }
        static create_header(msgtype) {
            return {
                msgid: (0, string_1.unique_id)(),
                msgtype,
            };
        }
        complete() {
            const { num_buffers } = this.header;
            return num_buffers == null || this._buffers.size == num_buffers;
        }
        send(socket) {
            (0, assert_1.assert)(this.header.num_buffers == null);
            const buffers = [];
            const content_json = JSON.stringify(this.content, (_, val) => {
                if (val instanceof serialization_1.Buffer) {
                    const ref = { id: `${buffers.length}` };
                    buffers.push([ref, val.buffer]);
                    return ref;
                }
                else
                    return val;
            });
            const num_buffers = buffers.length;
            if (num_buffers > 0) {
                this.header.num_buffers = num_buffers;
            }
            const header_json = JSON.stringify(this.header);
            const metadata_json = JSON.stringify(this.metadata);
            socket.send(header_json);
            socket.send(metadata_json);
            socket.send(content_json);
            for (const [ref, buffer] of buffers) {
                socket.send(JSON.stringify(ref));
                socket.send(buffer);
            }
        }
        msgid() {
            return this.header.msgid;
        }
        msgtype() {
            return this.header.msgtype;
        }
        reqid() {
            return this.header.reqid;
        }
        // return the reason we should close on bad protocol, if there is one
        problem() {
            if (!("msgid" in this.header))
                return "No msgid in header";
            else if (!("msgtype" in this.header))
                return "No msgtype in header";
            else
                return null;
        }
    }
    exports.Message = Message;
    Message.__name__ = "Message";
},
/* protocol/receiver.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const message_1 = require(62) /* ./message */;
    const types_1 = require(8) /* ../core/util/types */;
    const assert_1 = require(12) /* ../core/util/assert */;
    class Receiver {
        constructor() {
            this.message = null;
            this._partial = null;
            this._fragments = [];
            this._buf_header = null;
            this._current_consumer = this._HEADER;
        }
        consume(fragment) {
            this._current_consumer(fragment);
        }
        _HEADER(fragment) {
            this._assume_text(fragment);
            this.message = null;
            this._partial = null;
            this._fragments = [fragment];
            this._buf_header = null;
            this._current_consumer = this._METADATA;
        }
        _METADATA(fragment) {
            this._assume_text(fragment);
            this._fragments.push(fragment);
            this._current_consumer = this._CONTENT;
        }
        _CONTENT(fragment) {
            this._assume_text(fragment);
            this._fragments.push(fragment);
            const [header_json, metadata_json, content_json] = this._fragments;
            (0, assert_1.assert)(header_json != null && metadata_json != null && content_json != null);
            this._partial = message_1.Message.assemble(header_json, metadata_json, content_json);
            this._check_complete();
        }
        _BUFFER_HEADER(fragment) {
            this._assume_text(fragment);
            this._buf_header = fragment;
            this._current_consumer = this._BUFFER_PAYLOAD;
        }
        _BUFFER_PAYLOAD(fragment) {
            this._assume_binary(fragment);
            (0, assert_1.assert)(this._partial != null && this._buf_header != null);
            this._partial.assemble_buffer(this._buf_header, fragment);
            this._check_complete();
        }
        _assume_text(fragment) {
            if (!(0, types_1.isString)(fragment))
                throw new Error("Expected text fragment but received binary fragment");
        }
        _assume_binary(fragment) {
            if (!(fragment instanceof ArrayBuffer))
                throw new Error("Expected binary fragment but received text fragment");
        }
        _check_complete() {
            if (this._partial.complete()) {
                this.message = this._partial;
                this._current_consumer = this._HEADER;
            }
            else
                this._current_consumer = this._BUFFER_HEADER;
        }
    }
    exports.Receiver = Receiver;
    Receiver.__name__ = "Receiver";
},
/* client/session.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const document_1 = require(5) /* ../document */;
    const bokeh_events_1 = require(52) /* ../core/bokeh_events */;
    const message_1 = require(62) /* ../protocol/message */;
    const logging_1 = require(19) /* ../core/logging */;
    class ClientSession {
        constructor(_connection, document) {
            this._document_listener = (event) => {
                this._document_changed(event);
            };
            this._connection = _connection;
            this.document = document;
            this.document.on_change(this._document_listener, true);
        }
        // XXX: this is only needed in tests
        get id() {
            return this._connection.id;
        }
        handle(message) {
            const msgtype = message.msgtype();
            switch (msgtype) {
                case "PATCH-DOC": {
                    this._handle_patch(message);
                    break;
                }
                case "OK": {
                    this._handle_ok(message);
                    break;
                }
                case "ERROR": {
                    this._handle_error(message);
                    break;
                }
                default:
                    logging_1.logger.debug(`Doing nothing with message '${msgtype}'`);
            }
        }
        notify_connection_lost() {
            this.document.event_manager.send_event(new bokeh_events_1.ConnectionLost());
        }
        close() {
            this._connection.close();
        }
        /*protected*/ _connection_closed() {
            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.
        async request_server_info() {
            const message = message_1.Message.create("SERVER-INFO-REQ", {}, {});
            const reply = await this._connection.send_with_reply(message);
            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.)
        async force_roundtrip() {
            await this.request_server_info();
        }
        _document_changed(event) {
            const events = event instanceof document_1.DocumentEventBatch ? event.events : [event];
            const 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.
            const message = message_1.Message.create("PATCH-DOC", {}, patch);
            this._connection.send(message);
        }
        _handle_patch(message) {
            this.document.apply_json_patch(message.content, message.buffers);
        }
        _handle_ok(message) {
            logging_1.logger.trace(`Unhandled OK reply to ${message.reqid()}`);
        }
        _handle_error(message) {
            logging_1.logger.error(`Unhandled ERROR reply to ${message.reqid()}: ${message.content.text}`);
        }
    }
    exports.ClientSession = ClientSession;
    ClientSession.__name__ = "ClientSession";
},
/* embed/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(56) /* ../core/dom */;
    const types_1 = require(8) /* ../core/util/types */;
    function _get_element(target) {
        let element = (0, types_1.isString)(target) ? document.getElementById(target) : target;
        if (element == null)
            throw new Error(`Error rendering Bokeh model: could not find ${(0, types_1.isString)(target) ? `#${target}` : target} HTML tag`);
        if (!(0, dom_1.contains)(document.body, element))
            throw new Error(`Error rendering Bokeh model: element ${(0, types_1.isString)(target) ? `#${target}` : target} must be under <body>`);
        // If autoload script, replace script tag with div for embedding.
        if (element instanceof HTMLElement && element.tagName == "SCRIPT") {
            const root_el = (0, dom_1.div)();
            (0, dom_1.replaceWith)(element, root_el);
            element = root_el;
        }
        return element;
    }
    function _resolve_element(item) {
        const { elementid } = item;
        if (elementid != null)
            return _get_element(elementid);
        else
            return document.body;
    }
    exports._resolve_element = _resolve_element;
    function _resolve_root_elements(item) {
        const roots = [];
        if (item.root_ids != null && item.roots != null) {
            for (const root_id of item.root_ids)
                roots.push(_get_element(item.roots[root_id]));
        }
        return roots;
    }
    exports._resolve_root_elements = _resolve_root_elements;
},
/* embed/notebook.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const document_1 = require(5) /* ../document */;
    const receiver_1 = require(63) /* ../protocol/receiver */;
    const logging_1 = require(19) /* ../core/logging */;
    const object_1 = require(9) /* ../core/util/object */;
    const standalone_1 = require(53) /* ./standalone */;
    const dom_1 = require(65) /* ./dom */;
    // 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);
        const msg = receiver.message;
        if (msg != null)
            this.apply_json_patch(msg.content, msg.buffers);
    }
    function _init_comms(target, doc) {
        if (typeof Jupyter !== "undefined" && Jupyter.notebook.kernel != null) {
            logging_1.logger.info(`Registering Jupyter comms for target ${target}`);
            const comm_manager = Jupyter.notebook.kernel.comm_manager;
            try {
                comm_manager.register_target(target, (comm) => {
                    logging_1.logger.info(`Registering Jupyter comms for target ${target}`);
                    const 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}`);
            const kernel = exports.kernels[doc.roots()[0].id];
            try {
                kernel.registerCommTarget(target, (comm) => {
                    logging_1.logger.info(`Registering JupyterLab comms for target ${target}`);
                    const 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}`);
            const comm_manager = google.colab.kernel.comms;
            try {
                comm_manager.registerTarget(target, async (comm) => {
                    var _a, e_1, _b, _c;
                    var _d;
                    logging_1.logger.info(`Registering Google Colab comms for target ${target}`);
                    const r = new receiver_1.Receiver();
                    try {
                        for (var _e = true, _f = tslib_1.__asyncValues(comm.messages), _g; _g = await _f.next(), _a = _g.done, !_a; _e = true) {
                            _c = _g.value;
                            _e = false;
                            const message = _c;
                            const content = { data: message.data };
                            const buffers = [];
                            for (const buffer of (_d = message.buffers) !== null && _d !== void 0 ? _d : []) {
                                buffers.push(new DataView(buffer));
                            }
                            const msg = { content, buffers };
                            _handle_notebook_comms.bind(doc)(r, msg);
                        }
                    }
                    catch (e_1_1) {
                        e_1 = { error: e_1_1 };
                    }
                    finally {
                        try {
                            if (!_e && !_a && (_b = _f.return))
                                await _b.call(_f);
                        }
                        finally {
                            if (e_1)
                                throw e_1.error;
                        }
                    }
                });
            }
            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) {
        if ((0, object_1.size)(docs_json) != 1)
            throw new Error("embed_items_notebook expects exactly one document in docs_json");
        const document = document_1.Document.from_json((0, object_1.values)(docs_json)[0]);
        for (const item of render_items) {
            if (item.notebook_comms_target != null)
                _init_comms(item.notebook_comms_target, document);
            const element = (0, dom_1._resolve_element)(item);
            const roots = (0, dom_1._resolve_root_elements)(item);
            (0, standalone_1.add_document_standalone)(document, element, roots);
            for (const root of roots) {
                if (root instanceof HTMLElement) {
                    root.removeAttribute("id");
                }
            }
        }
    }
    exports.embed_items_notebook = embed_items_notebook;
},
/* protocol/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(62) /* ./message */, exports);
    tslib_1.__exportStar(require(63) /* ./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() {
        const body = document.getElementsByTagName("body")[0];
        const col = document.getElementsByClassName("bokeh-test-div");
        if (col.length == 1) {
            body.removeChild(col[0]);
            delete col[0];
        }
        const 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
        const 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
        const 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", () => body.removeChild(box));
        // Make title
        const 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
        const 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
        const body = document.getElementsByTagName("body")[0];
        body.insertBefore(box, body.firstChild);
    }
    function safely(fn, silent = false) {
        try {
            return fn();
        }
        catch (error) {
            const text = error instanceof Error && error.stack != null ? error.stack : `${error}`;
            _burst_into_flames(text);
            if (!silent)
                throw error;
            else
                return;
        }
    }
    exports.safely = safely;
},
/* models/main.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const base_1 = require(7) /* ../base */;
    const AllModels = tslib_1.__importStar(require(71) /* ./ */);
    (0, base_1.register_models)(AllModels);
    const DOMModels = tslib_1.__importStar(require(509) /* ./dom */);
    (0, base_1.register_models)(DOMModels);
},
/* models/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(72) /* ./annotations */, exports);
    tslib_1.__exportStar(require(160) /* ./axes */, exports);
    tslib_1.__exportStar(require(294) /* ./callbacks */, exports);
    tslib_1.__exportStar(require(299) /* ./canvas */, exports);
    tslib_1.__exportStar(require(305) /* ./coordinates */, exports);
    tslib_1.__exportStar(require(306) /* ./expressions */, exports);
    tslib_1.__exportStar(require(315) /* ./filters */, exports);
    tslib_1.__exportStar(require(224) /* ./formatters */, exports);
    tslib_1.__exportStar(require(324) /* ./glyphs */, exports);
    tslib_1.__exportStar(require(363) /* ./graphics */, exports);
    tslib_1.__exportStar(require(364) /* ./graphs */, exports);
    tslib_1.__exportStar(require(368) /* ./grids */, exports);
    tslib_1.__exportStar(require(370) /* ./layouts */, exports);
    tslib_1.__exportStar(require(244) /* ./mappers */, exports);
    tslib_1.__exportStar(require(389) /* ./menus */, exports);
    tslib_1.__exportStar(require(395) /* ./text */, exports);
    tslib_1.__exportStar(require(396) /* ./transforms */, exports);
    tslib_1.__exportStar(require(405) /* ./plots */, exports);
    tslib_1.__exportStar(require(417) /* ./policies */, exports);
    tslib_1.__exportStar(require(418) /* ./random */, exports);
    tslib_1.__exportStar(require(230) /* ./ranges */, exports);
    tslib_1.__exportStar(require(420) /* ./renderers */, exports);
    tslib_1.__exportStar(require(228) /* ./scales */, exports);
    tslib_1.__exportStar(require(423) /* ./selections */, exports);
    tslib_1.__exportStar(require(424) /* ./selectors */, exports);
    tslib_1.__exportStar(require(430) /* ./sources */, exports);
    tslib_1.__exportStar(require(194) /* ./tickers */, exports);
    tslib_1.__exportStar(require(435) /* ./tiles */, exports);
    tslib_1.__exportStar(require(445) /* ./textures */, exports);
    tslib_1.__exportStar(require(449) /* ./ui */, exports);
    tslib_1.__exportStar(require(464) /* ./tools */, exports);
},
/* models/annotations/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var annotation_1 = require(73) /* ./annotation */;
    __esExport("Annotation", annotation_1.Annotation);
    var arrow_1 = require(99) /* ./arrow */;
    __esExport("Arrow", arrow_1.Arrow);
    var arrow_head_1 = require(141) /* ./arrow_head */;
    __esExport("ArrowHead", arrow_head_1.ArrowHead);
    var arrow_head_2 = require(141) /* ./arrow_head */;
    __esExport("OpenHead", arrow_head_2.OpenHead);
    var arrow_head_3 = require(141) /* ./arrow_head */;
    __esExport("NormalHead", arrow_head_3.NormalHead);
    var arrow_head_4 = require(141) /* ./arrow_head */;
    __esExport("TeeHead", arrow_head_4.TeeHead);
    var arrow_head_5 = require(141) /* ./arrow_head */;
    __esExport("VeeHead", arrow_head_5.VeeHead);
    var base_color_bar_1 = require(143) /* ./base_color_bar */;
    __esExport("BaseColorBar", base_color_bar_1.BaseColorBar);
    var band_1 = require(235) /* ./band */;
    __esExport("Band", band_1.Band);
    var box_annotation_1 = require(237) /* ./box_annotation */;
    __esExport("BoxAnnotation", box_annotation_1.BoxAnnotation);
    var color_bar_1 = require(243) /* ./color_bar */;
    __esExport("ColorBar", color_bar_1.ColorBar);
    var contour_color_bar_1 = require(254) /* ./contour_color_bar */;
    __esExport("ContourColorBar", contour_color_bar_1.ContourColorBar);
    var label_1 = require(255) /* ./label */;
    __esExport("Label", label_1.Label);
    var label_set_1 = require(256) /* ./label_set */;
    __esExport("LabelSet", label_set_1.LabelSet);
    var legend_1 = require(257) /* ./legend */;
    __esExport("Legend", legend_1.Legend);
    var legend_item_1 = require(258) /* ./legend_item */;
    __esExport("LegendItem", legend_item_1.LegendItem);
    var poly_annotation_1 = require(259) /* ./poly_annotation */;
    __esExport("PolyAnnotation", poly_annotation_1.PolyAnnotation);
    var scale_bar_1 = require(260) /* ./scale_bar */;
    __esExport("ScaleBar", scale_bar_1.ScaleBar);
    var dimensional_1 = require(261) /* ./dimensional */;
    __esExport("MetricLength", dimensional_1.MetricLength);
    var slope_1 = require(262) /* ./slope */;
    __esExport("Slope", slope_1.Slope);
    var span_1 = require(263) /* ./span */;
    __esExport("Span", span_1.Span);
    var text_annotation_1 = require(145) /* ./text_annotation */;
    __esExport("TextAnnotation", text_annotation_1.TextAnnotation);
    var title_1 = require(144) /* ./title */;
    __esExport("Title", title_1.Title);
    var toolbar_panel_1 = require(264) /* ./toolbar_panel */;
    __esExport("ToolbarPanel", toolbar_panel_1.ToolbarPanel);
    var whisker_1 = require(288) /* ./whisker */;
    __esExport("Whisker", whisker_1.Whisker);
    tslib_1.__exportStar(require(289) /* ./html */, exports);
},
/* models/annotations/annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const renderer_1 = require(74) /* ../renderers/renderer */;
    class AnnotationView extends renderer_1.RendererView {
        get_size() {
            if (this.displayed) {
                const { width, height } = this._get_size();
                return { width: Math.round(width), height: Math.round(height) };
            }
            else
                return { width: 0, height: 0 };
        }
        _get_size() {
            throw new Error("not implemented");
        }
        connect_signals() {
            super.connect_signals();
            const p = this.model.properties;
            this.on_change(p.visible, () => {
                if (this.layout != null) {
                    this.layout.visible = this.model.visible;
                    this.plot_view.request_layout();
                }
            });
        }
        get needs_clip() {
            return this.layout == null; // TODO: change this, when center layout is fully implemented
        }
        serializable_state() {
            var _b, _c, _d;
            const state = super.serializable_state();
            const bbox = (_c = (_b = this.bbox) === null || _b === void 0 ? void 0 : _b.round()) !== null && _c !== void 0 ? _c : (_d = this.layout) === null || _d === void 0 ? void 0 : _d.bbox;
            return bbox == null ? state : Object.assign(Object.assign({}, state), { bbox });
        }
    }
    exports.AnnotationView = AnnotationView;
    AnnotationView.__name__ = "AnnotationView";
    class Annotation extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Annotation = Annotation;
    _a = Annotation;
    Annotation.__name__ = "Annotation";
    (() => {
        _a.override({
            level: "annotation",
        });
    })();
},
/* models/renderers/renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const view_1 = require(54) /* ../../core/view */;
    const visuals = tslib_1.__importStar(require(75) /* ../../core/visuals */);
    const enums_1 = require(20) /* ../../core/enums */;
    const types_1 = require(8) /* ../../core/util/types */;
    const model_1 = require(50) /* ../../model */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const coordinate_mapping_1 = require(84) /* ../coordinates/coordinate_mapping */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    class RendererGroup extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.RendererGroup = RendererGroup;
    _a = RendererGroup;
    RendererGroup.__name__ = "RendererGroup";
    (() => {
        _a.define(({ Boolean }) => ({
            visible: [Boolean, true],
        }));
    })();
    class RendererView extends view_1.View {
        constructor() {
            super(...arguments);
            this._custom_coordinates = null;
        }
        get coordinates() {
            const { _coordinates } = this;
            if (_coordinates != null)
                return _coordinates;
            else
                return this._coordinates = this._initialize_coordinates();
        }
        set coordinates(custom_coordinates) {
            this._custom_coordinates = custom_coordinates;
        }
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        connect_signals() {
            super.connect_signals();
            const { group } = this.model;
            if (group != null) {
                this.on_change(group.properties.visible, () => {
                    this.model.visible = group.visible;
                });
            }
            const { x_range_name, y_range_name } = this.model.properties;
            this.on_change([x_range_name, y_range_name], () => delete this._coordinates);
            this.connect(this.plot_view.frame.change, () => delete this._coordinates);
        }
        _initialize_coordinates() {
            if (this._custom_coordinates != null) {
                return this._custom_coordinates;
            }
            const { coordinates } = this.model;
            const { frame } = this.plot_view;
            if (coordinates != null) {
                return coordinates.get_transform(frame);
            }
            else {
                const { x_range_name, y_range_name } = this.model;
                const x_scale = frame.x_scales.get(x_range_name);
                const y_scale = frame.y_scales.get(y_range_name);
                (0, assert_1.assert)(x_scale != null, `missing '${x_range_name}' range`);
                (0, assert_1.assert)(y_scale != null, `missing '${y_range_name}' range`);
                return new coordinate_mapping_1.CoordinateTransform(x_scale, y_scale);
            }
        }
        get plot_view() {
            return this.parent;
        }
        get plot_model() {
            return this.parent.model;
        }
        get layer() {
            const { overlays, primary } = this.canvas;
            return this.model.level == "overlay" ? overlays : primary;
        }
        get canvas() {
            return this.plot_view.canvas_view;
        }
        request_render() {
            this.request_paint();
        }
        request_paint() {
            this.plot_view.request_paint(this);
        }
        request_layout() {
            this.plot_view.request_layout();
        }
        notify_finished() {
            this.plot_view.notify_finished();
        }
        notify_finished_after_paint() {
            this.plot_view.notify_finished_after_paint();
        }
        get needs_clip() {
            return false;
        }
        get has_webgl() {
            return false;
        }
        /*
        get visible(): boolean {
          const {visible, group} = this.model
          return !visible ? false : (group?.visible ?? true)
        }
        */
        get displayed() {
            return this.model.visible;
        }
        render() {
            if (this.displayed) {
                this._render();
            }
            this._has_finished = true;
        }
        renderer_view(_renderer) {
            return undefined;
        }
        /**
         * Geometry setup that doesn't change between paints.
         */
        update_geometry() { }
        /**
         * Geometry setup that changes between paints.
         */
        compute_geometry() { }
        /**
         * Compute screen coordinates for a symbolic node.
         */
        resolve_node(node) {
            const target = (() => {
                if ((0, types_1.isString)(node.target)) {
                    switch (node.target) {
                        case "canvas": return this.plot_view.canvas;
                        case "frame": return this.plot_view.frame;
                        case "plot": return this.plot_view;
                        case "parent": return this.parent;
                    }
                }
                else {
                    if (node.target instanceof Renderer) {
                        const view = this.plot_view.renderer_view(node.target);
                        if (view != null) {
                            return view;
                        }
                    }
                    return null;
                }
            })();
            function xy(x, y) {
                const { offset } = node;
                return { x: x + offset, y: y + offset };
            }
            if (target == null) {
                return xy(NaN, NaN);
            }
            if (!("bbox" in target && target.bbox instanceof bbox_1.BBox)) {
                return xy(NaN, NaN);
            }
            const { bbox } = target;
            switch (node.symbol) {
                case "top_left": return xy(bbox.left, bbox.top);
                case "top_center": return xy(bbox.hcenter, bbox.top);
                case "top_right": return xy(bbox.right, bbox.top);
                case "center_left": return xy(bbox.left, bbox.vcenter);
                case "center_center": return xy(bbox.hcenter, bbox.vcenter);
                case "center_right": return xy(bbox.right, bbox.vcenter);
                case "bottom_left": return xy(bbox.left, bbox.bottom);
                case "bottom_center": return xy(bbox.hcenter, bbox.bottom);
                case "bottom_right": return xy(bbox.right, bbox.bottom);
                case "center": return xy(bbox.hcenter, bbox.vcenter);
                case "top": return xy(NaN, bbox.top);
                case "left": return xy(bbox.left, NaN);
                case "right": return xy(bbox.right, NaN);
                case "bottom": return xy(NaN, bbox.bottom);
                default: return xy(NaN, NaN);
            }
        }
    }
    exports.RendererView = RendererView;
    RendererView.__name__ = "RendererView";
    class Renderer extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Renderer = Renderer;
    _b = Renderer;
    Renderer.__name__ = "Renderer";
    (() => {
        _b.define(({ Boolean, String, Ref, Nullable }) => ({
            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(coordinate_mapping_1.CoordinateMapping)), null],
            propagate_hover: [Boolean, false],
        }));
    })();
},
/* core/visuals/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const line_1 = require(76) /* ./line */;
    __esExport("Line", line_1.Line);
    __esExport("LineScalar", line_1.LineScalar);
    __esExport("LineVector", line_1.LineVector);
    const fill_1 = require(79) /* ./fill */;
    __esExport("Fill", fill_1.Fill);
    __esExport("FillScalar", fill_1.FillScalar);
    __esExport("FillVector", fill_1.FillVector);
    const text_1 = require(80) /* ./text */;
    __esExport("Text", text_1.Text);
    __esExport("TextScalar", text_1.TextScalar);
    __esExport("TextVector", text_1.TextVector);
    const hatch_1 = require(81) /* ./hatch */;
    __esExport("Hatch", hatch_1.Hatch);
    __esExport("HatchScalar", hatch_1.HatchScalar);
    __esExport("HatchVector", hatch_1.HatchVector);
    const image_1 = require(83) /* ./image */;
    __esExport("Image", image_1.Image);
    __esExport("ImageScalar", image_1.ImageScalar);
    __esExport("ImageVector", image_1.ImageVector);
    const mixins = tslib_1.__importStar(require(78) /* ../property_mixins */);
    const visual_1 = require(77) /* ./visual */;
    __esExport("VisualProperties", visual_1.VisualProperties);
    __esExport("VisualUniforms", visual_1.VisualUniforms);
    class Visuals {
        *[Symbol.iterator]() {
            yield* this._visuals;
        }
        constructor(view) {
            this._visuals = [];
            for (const [prefix, mixin] of view.model._mixins) {
                const visual = (() => {
                    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);
                        case mixins.Image: return new image_1.Image(view, prefix);
                        case mixins.ImageScalar: return new image_1.ImageScalar(view, prefix);
                        case mixins.ImageVector: return new image_1.ImageVector(view, prefix);
                        default:
                            throw new Error("unknown visual");
                    }
                })();
                if (visual instanceof visual_1.VisualProperties)
                    visual.update();
                this._visuals.push(visual);
                Object.defineProperty(this, prefix + visual.type, {
                    get() { return visual; },
                    configurable: false,
                    enumerable: true,
                });
            }
        }
    }
    exports.Visuals = Visuals;
    Visuals.__name__ = "Visuals";
},
/* core/visuals/line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(77) /* ./visual */;
    const mixins = tslib_1.__importStar(require(78) /* ../property_mixins */);
    const color_1 = require(22) /* ../util/color */;
    const types_1 = require(8) /* ../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;
    class Line extends visual_1.VisualProperties {
        get doit() {
            const color = this.line_color.get_value();
            const alpha = this.line_alpha.get_value();
            const width = this.line_width.get_value();
            return !(color == null || alpha == 0 || width == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.stroke();
            }
            return doit;
        }
        values() {
            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(),
            };
        }
        set_value(ctx) {
            const color = this.line_color.get_value();
            const 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.setLineDash(resolve_line_dash(this.line_dash.get_value()));
            ctx.lineDashOffset = this.line_dash_offset.get_value();
        }
    }
    exports.Line = Line;
    Line.__name__ = "Line";
    class LineScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.line_color.value;
            const alpha = this.line_alpha.value;
            const width = this.line_width.value;
            return !(color == 0 || alpha == 0 || width == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.stroke();
            }
            return doit;
        }
        values() {
            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,
            };
        }
        set_value(ctx) {
            const color = this.line_color.value;
            const 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.setLineDash(resolve_line_dash(this.line_dash.value));
            ctx.lineDashOffset = this.line_dash_offset.value;
        }
    }
    exports.LineScalar = LineScalar;
    LineScalar.__name__ = "LineScalar";
    class LineVector extends visual_1.VisualUniforms {
        get doit() {
            const { line_color } = this;
            if (line_color.is_Scalar() && line_color.value == 0)
                return false;
            const { line_alpha } = this;
            if (line_alpha.is_Scalar() && line_alpha.value == 0)
                return false;
            const { line_width } = this;
            if (line_width.is_Scalar() && line_width.value == 0)
                return false;
            return true;
        }
        v_doit(i) {
            if (this.line_color.get(i) == 0)
                return false;
            if (this.line_alpha.get(i) == 0)
                return false;
            if (this.line_width.get(i) == 0)
                return false;
            return true;
        }
        apply(ctx, i) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.stroke();
            }
            return doit;
        }
        values(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),
            };
        }
        set_vectorize(ctx, i) {
            const color = this.line_color.get(i);
            const alpha = this.line_alpha.get(i);
            const width = this.line_width.get(i);
            const join = this.line_join.get(i);
            const cap = this.line_cap.get(i);
            const dash = this.line_dash.get(i);
            const 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.setLineDash(resolve_line_dash(dash));
            ctx.lineDashOffset = offset;
        }
    }
    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();
    class VisualProperties {
        *[Symbol.iterator]() {
            yield* this._props;
        }
        constructor(obj, prefix = "") {
            this.obj = obj;
            this.prefix = prefix;
            const self = this;
            this._props = [];
            for (const attr of this.attrs) {
                const prop = obj.model.properties[prefix + attr];
                prop.change.connect(() => this.update());
                self[attr] = prop;
                this._props.push(prop);
            }
        }
        update() { }
    }
    exports.VisualProperties = VisualProperties;
    VisualProperties.__name__ = "VisualProperties";
    class VisualUniforms {
        *[Symbol.iterator]() {
            for (const attr of this.attrs) {
                yield this.obj.model.properties[this.prefix + attr];
            }
        }
        constructor(obj, prefix = "") {
            this.obj = obj;
            this.prefix = prefix;
            for (const attr of this.attrs) {
                Object.defineProperty(this, attr, {
                    get() {
                        return obj[prefix + attr];
                    },
                });
            }
        }
        update() { }
    }
    exports.VisualUniforms = VisualUniforms;
    VisualUniforms.__name__ = "VisualUniforms";
},
/* core/property_mixins.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(18) /* ./properties */);
    const enums_1 = require(20) /* ./enums */;
    const k = tslib_1.__importStar(require(21) /* ./kinds */);
    const object_1 = require(9) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    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.Image = {
        global_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_outline_color: [k.Nullable(k.Color), null],
        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.ImageScalar = {
        global_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_outline_color: [p.ColorScalar, null],
        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.ImageVector = {
        global_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_outline_color: [p.ColorSpec, null],
        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, new_prefix = false) {
        const attrs = {};
        for (const attr of (0, object_1.keys)(mixin)) {
            const prefixed_attr = `${prefix}${attr}`;
            const value = model[prefixed_attr];
            const new_attr = (() => {
                if ((0, types_1.isString)(new_prefix)) {
                    return `${new_prefix}${attr}`;
                }
                else if (new_prefix) {
                    return prefixed_attr;
                }
                else {
                    return attr;
                }
            })();
            attrs[new_attr] = value;
        }
        return attrs;
    }
    exports.attrs_of = attrs_of;
},
/* core/visuals/fill.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(77) /* ./visual */;
    const mixins = tslib_1.__importStar(require(78) /* ../property_mixins */);
    const color_1 = require(22) /* ../util/color */;
    class Fill extends visual_1.VisualProperties {
        get doit() {
            const color = this.fill_color.get_value();
            const alpha = this.fill_alpha.get_value();
            return !(color == null || alpha == 0);
        }
        apply(ctx, rule) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.fill(rule);
            }
            return doit;
        }
        values() {
            return {
                color: this.fill_color.get_value(),
                alpha: this.fill_alpha.get_value(),
            };
        }
        set_value(ctx) {
            const color = this.fill_color.get_value();
            const alpha = this.fill_alpha.get_value();
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        }
    }
    exports.Fill = Fill;
    Fill.__name__ = "Fill";
    class FillScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.fill_color.value;
            const alpha = this.fill_alpha.value;
            return !(color == 0 || alpha == 0);
        }
        apply(ctx, rule) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.fill(rule);
            }
            return doit;
        }
        values() {
            return {
                color: this.fill_color.value,
                alpha: this.fill_alpha.value,
            };
        }
        set_value(ctx) {
            const color = this.fill_color.value;
            const alpha = this.fill_alpha.value;
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        }
    }
    exports.FillScalar = FillScalar;
    FillScalar.__name__ = "FillScalar";
    class FillVector extends visual_1.VisualUniforms {
        get doit() {
            const { fill_color } = this;
            if (fill_color.is_Scalar() && fill_color.value == 0)
                return false;
            const { fill_alpha } = this;
            if (fill_alpha.is_Scalar() && fill_alpha.value == 0)
                return false;
            return true;
        }
        v_doit(i) {
            if (this.fill_color.get(i) == 0)
                return false;
            if (this.fill_alpha.get(i) == 0)
                return false;
            return true;
        }
        apply(ctx, i, rule) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.fill(rule);
            }
            return doit;
        }
        values(i) {
            return {
                color: this.fill_color.get(i),
                alpha: this.fill_alpha.get(i),
            };
        }
        set_vectorize(ctx, i) {
            const color = this.fill_color.get(i);
            const alpha = this.fill_alpha.get(i);
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        }
    }
    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();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(77) /* ./visual */;
    const mixins = tslib_1.__importStar(require(78) /* ../property_mixins */);
    const color_1 = require(22) /* ../util/color */;
    const _font_cache = new Map();
    function load_font(font, obj) {
        const objs = _font_cache.get(font);
        if (objs == null) {
            const objs = new WeakSet([obj]);
            _font_cache.set(font, objs);
        }
        else if (!objs.has(obj)) {
            objs.add(obj);
        }
        else {
            return;
        }
        const { fonts } = document;
        if (!fonts.check(font)) {
            fonts.load(font).then(() => obj.request_render());
        }
    }
    class Text extends visual_1.VisualProperties {
        get doit() {
            const color = this.text_color.get_value();
            const alpha = this.text_alpha.get_value();
            return !(color == null || alpha == 0);
        }
        update() {
            if (!this.doit)
                return;
            const font = this.font_value();
            load_font(font, this.obj);
        }
        values() {
            return {
                color: this.text_color.get_value(),
                outline_color: this.text_outline_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(),
            };
        }
        set_value(ctx) {
            const color = this.text_color.get_value();
            const outline_color = this.text_outline_color.get_value();
            const alpha = this.text_alpha.get_value();
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.strokeStyle = (0, color_1.color2css)(outline_color, alpha);
            ctx.font = this.font_value();
            ctx.textAlign = this.text_align.get_value();
            ctx.textBaseline = this.text_baseline.get_value();
        }
        font_value() {
            const style = this.text_font_style.get_value();
            const size = this.text_font_size.get_value();
            const face = this.text_font.get_value();
            return `${style} ${size} ${face}`;
        }
    }
    exports.Text = Text;
    Text.__name__ = "Text";
    class TextScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.text_color.value;
            const alpha = this.text_alpha.value;
            return !(color == 0 || alpha == 0);
        }
        update() {
            if (!this.doit)
                return;
            const font = this.font_value();
            load_font(font, this.obj);
        }
        values() {
            return {
                color: this.text_color.value,
                outline_color: this.text_outline_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,
            };
        }
        set_value(ctx) {
            const color = this.text_color.value;
            const alpha = this.text_alpha.value;
            const outline_color = this.text_outline_color.value;
            const font = this.font_value();
            const align = this.text_align.value;
            const baseline = this.text_baseline.value;
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.strokeStyle = (0, color_1.color2css)(outline_color, alpha);
            ctx.font = font;
            ctx.textAlign = align;
            ctx.textBaseline = baseline;
        }
        font_value() {
            const style = this.text_font_style.value;
            const size = this.text_font_size.value;
            const face = this.text_font.value;
            return `${style} ${size} ${face}`;
        }
    }
    exports.TextScalar = TextScalar;
    TextScalar.__name__ = "TextScalar";
    class TextVector extends visual_1.VisualUniforms {
        _assert_font(i) {
            const font = this.font_value(i);
            load_font(font, this.obj);
        }
        values(i) {
            this._assert_font(i);
            return {
                color: this.text_color.get(i),
                outline_color: this.text_outline_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),
            };
        }
        get doit() {
            const { text_color } = this;
            if (text_color.is_Scalar() && text_color.value == 0)
                return false;
            const { text_alpha } = this;
            if (text_alpha.is_Scalar() && text_alpha.value == 0)
                return false;
            return true;
        }
        v_doit(i) {
            if (this.text_color.get(i) == 0)
                return false;
            if (this.text_alpha.get(i) == 0)
                return false;
            return true;
        }
        apply(ctx, i) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
            }
            return doit;
        }
        set_vectorize(ctx, i) {
            this._assert_font(i);
            const color = this.text_color.get(i);
            const outline_color = this.text_outline_color.get(i);
            const alpha = this.text_alpha.get(i);
            const font = this.font_value(i);
            const align = this.text_align.get(i);
            const baseline = this.text_baseline.get(i);
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.strokeStyle = (0, color_1.color2css)(outline_color, alpha);
            ctx.font = font;
            ctx.textAlign = align;
            ctx.textBaseline = baseline;
        }
        font_value(i) {
            const style = this.text_font_style.get(i);
            const size = this.text_font_size.get(i);
            const face = this.text_font.get(i);
            return `${style} ${size} ${face}`;
        }
    }
    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();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(77) /* ./visual */;
    const patterns_1 = require(82) /* ./patterns */;
    const p = tslib_1.__importStar(require(18) /* ../properties */);
    const mixins = tslib_1.__importStar(require(78) /* ../property_mixins */);
    class Hatch extends visual_1.VisualProperties {
        constructor() {
            super(...arguments);
            this._update_iteration = 0;
        }
        update() {
            this._update_iteration++;
            this._hatch_image = null;
            if (!this.doit)
                return;
            const color = this.hatch_color.get_value();
            const alpha = this.hatch_alpha.get_value();
            const scale = this.hatch_scale.get_value();
            const pattern = this.hatch_pattern.get_value();
            const weight = this.hatch_weight.get_value();
            const finalize = (image) => {
                this._hatch_image = image;
            };
            const textures = this.hatch_extra.get_value();
            const texture = textures[pattern];
            if (texture != null) {
                const image = texture.get_pattern(color, alpha, scale, weight);
                if (image instanceof Promise) {
                    const { _update_iteration } = this;
                    image.then((image) => {
                        if (this._update_iteration == _update_iteration) {
                            finalize(image);
                            this.obj.request_render();
                        }
                    });
                }
                else {
                    finalize(image);
                }
            }
            else {
                const layer = this.obj.canvas.create_layer();
                const image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                finalize(image);
            }
        }
        get doit() {
            const color = this.hatch_color.get_value();
            const alpha = this.hatch_alpha.get_value();
            const pattern = this.hatch_pattern.get_value();
            return !(color == null || alpha == 0 || pattern == " " || pattern == "blank" || pattern == null);
        }
        apply(ctx, rule) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.layer.undo_transform(() => ctx.fill(rule));
            }
            return doit;
        }
        set_value(ctx) {
            const pattern = this.pattern(ctx);
            ctx.fillStyle = pattern !== null && pattern !== void 0 ? pattern : "transparent";
        }
        pattern(ctx) {
            const image = this._hatch_image;
            if (image == null)
                return null;
            else
                return ctx.createPattern(image, this.repetition());
        }
        repetition() {
            const pattern = this.hatch_pattern.get_value();
            const 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";
                }
            }
        }
    }
    exports.Hatch = Hatch;
    Hatch.__name__ = "Hatch";
    class HatchScalar extends visual_1.VisualUniforms {
        constructor() {
            super(...arguments);
            this._static_doit = false;
            this._update_iteration = 0;
        }
        _compute_static_doit() {
            const color = this.hatch_color.value;
            const alpha = this.hatch_alpha.value;
            const pattern = this.hatch_pattern.value;
            return !(color == 0 || alpha == 0 || pattern == " " || pattern == "blank" || pattern == null);
        }
        update() {
            this._update_iteration++;
            const 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;
            const color = this.hatch_color.value;
            const alpha = this.hatch_alpha.value;
            const scale = this.hatch_scale.value;
            const pattern = this.hatch_pattern.value;
            const weight = this.hatch_weight.value;
            const finalize = (image) => {
                this._hatch_image = new p.UniformScalar(image, n);
            };
            const textures = this.hatch_extra.value;
            const texture = textures[pattern];
            if (texture != null) {
                const image = texture.get_pattern(color, alpha, scale, weight);
                if (image instanceof Promise) {
                    const { _update_iteration } = this;
                    image.then((image) => {
                        if (this._update_iteration == _update_iteration) {
                            finalize(image);
                            this.obj.request_render();
                        }
                    });
                }
                else {
                    finalize(image);
                }
            }
            else {
                const layer = this.obj.canvas.create_layer();
                const image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                finalize(image);
            }
        }
        get doit() {
            return this._static_doit;
        }
        apply(ctx, rule) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.layer.undo_transform(() => ctx.fill(rule));
            }
            return doit;
        }
        set_value(ctx) {
            var _a;
            ctx.fillStyle = (_a = this.pattern(ctx)) !== null && _a !== void 0 ? _a : "transparent";
        }
        pattern(ctx) {
            const image = this._hatch_image.value;
            if (image == null)
                return null;
            else
                return ctx.createPattern(image, this.repetition());
        }
        repetition() {
            const pattern = this.hatch_pattern.value;
            if (pattern != null) {
                const texture = this.hatch_extra.value[pattern];
                if (texture != null) {
                    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 "repeat";
        }
    }
    exports.HatchScalar = HatchScalar;
    HatchScalar.__name__ = "HatchScalar";
    class HatchVector extends visual_1.VisualUniforms {
        constructor() {
            super(...arguments);
            this._static_doit = false;
            this._update_iteration = 0;
        }
        _compute_static_doit() {
            const { hatch_color } = this;
            if (hatch_color.is_Scalar() && hatch_color.value == 0)
                return false;
            const { hatch_alpha } = this;
            if (hatch_alpha.is_Scalar() && hatch_alpha.value == 0)
                return false;
            const { hatch_pattern } = this;
            if (hatch_pattern.is_Scalar()) {
                const pattern = hatch_pattern.value;
                if (pattern == " " || pattern == "blank" || pattern == null)
                    return false;
            }
            return true;
        }
        update() {
            this._update_iteration++;
            const 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;
            const resolve_image = (pattern, color, alpha, scale, weight, finalize) => {
                const textures = this.hatch_extra.value;
                const texture = textures[pattern];
                if (texture != null) {
                    const image = texture.get_pattern(color, alpha, scale, weight);
                    if (image instanceof Promise) {
                        const { _update_iteration } = this;
                        image.then((image) => {
                            if (this._update_iteration == _update_iteration) {
                                finalize(image);
                                this.obj.request_render();
                            }
                        });
                    }
                    else {
                        finalize(image);
                    }
                }
                else {
                    const layer = this.obj.canvas.create_layer();
                    const 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()) {
                const color = this.hatch_color.value;
                const alpha = this.hatch_alpha.value;
                const scale = this.hatch_scale.value;
                const pattern = this.hatch_pattern.value;
                const weight = this.hatch_weight.value;
                resolve_image(pattern, color, alpha, scale, weight, (image) => {
                    this._hatch_image = new p.UniformScalar(image, n);
                });
            }
            else {
                const images = new Array(n);
                images.fill(null);
                this._hatch_image = new p.UniformVector(images);
                for (let i = 0; i < n; i++) {
                    const color = this.hatch_color.get(i);
                    const alpha = this.hatch_alpha.get(i);
                    const scale = this.hatch_scale.get(i);
                    const pattern = this.hatch_pattern.get(i);
                    const weight = this.hatch_weight.get(i);
                    resolve_image(pattern, color, alpha, scale, weight, (image) => {
                        images[i] = image;
                    });
                }
            }
        }
        get doit() {
            return this._static_doit;
        }
        v_doit(i) {
            if (!this.doit)
                return false;
            if (this.hatch_color.get(i) == 0)
                return false;
            if (this.hatch_alpha.get(i) == 0)
                return false;
            const pattern = this.hatch_pattern.get(i);
            if (pattern == " " || pattern == "blank" || pattern == null)
                return false;
            return true;
        }
        apply(ctx, i, rule) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.layer.undo_transform(() => ctx.fill(rule));
            }
            return doit;
        }
        set_vectorize(ctx, i) {
            var _a;
            ctx.fillStyle = (_a = this.pattern(ctx, i)) !== null && _a !== void 0 ? _a : "transparent";
        }
        pattern(ctx, i) {
            const image = this._hatch_image.get(i);
            if (image == null)
                return null;
            else
                return ctx.createPattern(image, this.repetition(i));
        }
        repetition(i) {
            const pattern = this.hatch_pattern.get(i);
            if (pattern != null) {
                const texture = this.hatch_extra.value[pattern];
                if (texture != null) {
                    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 "repeat";
        }
    }
    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();
    const logging_1 = require(19) /* ../logging */;
    const color_1 = require(22) /* ../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;
        const h = hatch_scale;
        const h2 = h / 2;
        const h4 = h2 / 2;
        const 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": {
                const h30 = h / 30;
                ctx.moveTo(h2, h2);
                for (let i = 0; i < 360; i++) {
                    const angle = 0.1 * i;
                    const x = h2 + (h30 * angle) * Math.cos(angle);
                    const 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();
                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();
                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;
            default:
                logging_1.logger.warn(`unknown hatch pattern: ${hatch_pattern}`);
        }
    }
},
/* core/visuals/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(77) /* ./visual */;
    const mixins = tslib_1.__importStar(require(78) /* ../property_mixins */);
    class Image extends visual_1.VisualProperties {
        get doit() {
            const alpha = this.global_alpha.get_value();
            return !(alpha == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
            }
            return doit;
        }
        values() {
            return {
                global_alpha: this.global_alpha.get_value(),
            };
        }
        set_value(ctx) {
            const alpha = this.global_alpha.get_value();
            ctx.globalAlpha = alpha;
        }
    }
    exports.Image = Image;
    Image.__name__ = "Image";
    class ImageScalar extends visual_1.VisualUniforms {
        get doit() {
            const alpha = this.global_alpha.value;
            return !(alpha == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
            }
            return doit;
        }
        values() {
            return {
                global_alpha: this.global_alpha.value,
            };
        }
        set_value(ctx) {
            const alpha = this.global_alpha.value;
            ctx.globalAlpha = alpha;
        }
    }
    exports.ImageScalar = ImageScalar;
    ImageScalar.__name__ = "ImageScalar";
    class ImageVector extends visual_1.VisualUniforms {
        get doit() {
            const { global_alpha } = this;
            if (global_alpha.is_Scalar() && global_alpha.value == 0)
                return false;
            return true;
        }
        v_doit(i) {
            if (this.global_alpha.get(i) == 0)
                return false;
            return true;
        }
        apply(ctx, i) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
            }
            return doit;
        }
        values(i) {
            return {
                alpha: this.global_alpha.get(i),
            };
        }
        set_vectorize(ctx, i) {
            const alpha = this.global_alpha.get(i);
            ctx.globalAlpha = alpha;
        }
    }
    exports.ImageVector = ImageVector;
    ImageVector.__name__ = "ImageVector";
    Image.prototype.type = "image";
    Image.prototype.attrs = Object.keys(mixins.Image);
    ImageScalar.prototype.type = "image";
    ImageScalar.prototype.attrs = Object.keys(mixins.ImageScalar);
    ImageVector.prototype.type = "image";
    ImageVector.prototype.attrs = Object.keys(mixins.ImageVector);
},
/* models/coordinates/coordinate_mapping.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const scale_1 = require(85) /* ../scales/scale */;
    const linear_scale_1 = require(90) /* ../scales/linear_scale */;
    const log_scale_1 = require(92) /* ../scales/log_scale */;
    const categorical_scale_1 = require(93) /* ../scales/categorical_scale */;
    const composite_scale_1 = require(94) /* ../scales/composite_scale */;
    const range_1 = require(87) /* ../ranges/range */;
    const data_range1d_1 = require(95) /* ../ranges/data_range1d */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    class CoordinateTransform {
        constructor(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];
        }
        map_to_screen(xs, ys) {
            const sxs = this.x_scale.v_compute(xs);
            const sys = this.y_scale.v_compute(ys);
            return [sxs, sys];
        }
        map_from_screen(sxs, sys) {
            const xs = this.x_scale.v_invert(sxs);
            const ys = this.y_scale.v_invert(sys);
            return [xs, ys];
        }
    }
    exports.CoordinateTransform = CoordinateTransform;
    CoordinateTransform.__name__ = "CoordinateTransform";
    class CoordinateMapping extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get x_ranges() {
            return new Map([["default", this.x_source]]);
        }
        get y_ranges() {
            return new Map([["default", this.y_source]]);
        }
        _get_scale(range, scale, target) {
            const factor_range = range instanceof factor_range_1.FactorRange;
            const 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";
            const derived_scale = scale.clone();
            derived_scale.setv({ source_range: range, target_range: target });
            return derived_scale;
        }
        get_transform(frame) {
            const { x_source, x_scale, x_target } = this;
            const x_source_scale = this._get_scale(x_source, x_scale, x_target);
            const { y_source, y_scale, y_target } = this;
            const y_source_scale = this._get_scale(y_source, y_scale, y_target);
            const xscale = new composite_scale_1.CompositeScale({
                source_scale: x_source_scale, source_range: x_source_scale.source_range,
                target_scale: frame.x_scale, target_range: frame.x_target,
            });
            const yscale = new composite_scale_1.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);
        }
    }
    exports.CoordinateMapping = CoordinateMapping;
    _a = CoordinateMapping;
    CoordinateMapping.__name__ = "CoordinateMapping";
    (() => {
        _a.define(({ Ref }) => ({
            x_source: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            y_source: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            y_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            x_target: [Ref(range_1.Range)],
            y_target: [Ref(range_1.Range)],
        }));
    })();
},
/* models/scales/scale.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const transform_1 = require(86) /* ../transforms/transform */;
    const range_1 = require(87) /* ../ranges/range */;
    const range1d_1 = require(88) /* ../ranges/range1d */;
    const types_1 = require(24) /* ../../core/types */;
    class Scale extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        compute(x) {
            return this.s_compute(x);
        }
        v_compute(xs) {
            const result = new types_1.ScreenArray(xs.length);
            const { s_compute } = this;
            for (let i = 0; i < xs.length; i++) {
                result[i] = s_compute(xs[i]);
            }
            return result;
        }
        invert(sx) {
            return this.s_invert(sx);
        }
        v_invert(sxs) {
            const result = new Float64Array(sxs.length);
            const { s_invert } = this;
            for (let i = 0; i < sxs.length; i++) {
                result[i] = s_invert(sxs[i]);
            }
            return result;
        }
        r_compute(x0, x1) {
            const { s_compute } = this;
            if (this.target_range.is_reversed)
                return [s_compute(x1), s_compute(x0)];
            else
                return [s_compute(x0), s_compute(x1)];
        }
        r_invert(sx0, sx1) {
            const { s_invert } = this;
            if (this.target_range.is_reversed)
                return [s_invert(sx1), s_invert(sx0)];
            else
                return [s_invert(sx0), s_invert(sx1)];
        }
    }
    exports.Scale = Scale;
    _a = Scale;
    Scale.__name__ = "Scale";
    (() => {
        _a.internal(({ Ref }) => ({
            source_range: [Ref(range_1.Range)],
            target_range: [Ref(range1d_1.Range1d)],
        }));
    })();
},
/* models/transforms/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class Transform extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Transform = Transform;
    Transform.__name__ = "Transform";
},
/* models/ranges/range.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const Bounds = (0, kinds_1.Nullable)((0, kinds_1.Or)((0, kinds_1.Tuple)((0, kinds_1.Nullable)(kinds_1.Number), (0, kinds_1.Nullable)(kinds_1.Number)), kinds_1.Auto));
    class Range extends model_1.Model {
        constructor(attrs) {
            super(attrs);
            this.have_updated_interactively = false;
            /** internal */
            this.plots = new Set();
        }
        get computed_bounds() {
            return this._computed_bounds;
        }
        get is_reversed() {
            return this.start > this.end;
        }
        get is_valid() {
            return isFinite(this.min) && isFinite(this.max);
        }
        get span() {
            return Math.abs(this.end - this.start);
        }
    }
    exports.Range = Range;
    _a = Range;
    Range.__name__ = "Range";
    (() => {
        _a.define(({ Number, Nullable }) => ({
            bounds: [Bounds, null, {
                    on_update(bounds, obj) {
                        const [lower, upper] = bounds == "auto" || bounds == null ? [null, null] : bounds;
                        obj._computed_bounds = [lower !== null && lower !== void 0 ? lower : -Infinity, upper !== null && upper !== void 0 ? upper : Infinity];
                    },
                }],
            min_interval: [Nullable(Number), null],
            max_interval: [Nullable(Number), null],
        }));
    })();
},
/* models/ranges/range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const numerical_range_1 = require(89) /* ./numerical_range */;
    class Range1d extends numerical_range_1.NumericalRange {
        constructor(attrs) {
            super(attrs);
        }
        _set_auto_bounds() {
            if (this.bounds == "auto") {
                const min = Math.min(this._reset_start, this._reset_end);
                const max = Math.max(this._reset_start, this._reset_end);
                this._computed_bounds = [min, max];
            }
        }
        initialize() {
            super.initialize();
            this._set_auto_bounds();
        }
        get min() {
            return Math.min(this.start, this.end);
        }
        get max() {
            return Math.max(this.start, this.end);
        }
        reset() {
            this._set_auto_bounds();
            const { _reset_start, _reset_end } = this;
            if (this.start != _reset_start || this.end != _reset_end)
                this.setv({ start: _reset_start, end: _reset_end });
            else
                this.change.emit();
        }
        map(fn) {
            return new _a({ start: fn(this.start), end: fn(this.end) });
        }
        widen(v) {
            let { start, end } = this;
            if (this.is_reversed) {
                start += v;
                end -= v;
            }
            else {
                start -= v;
                end += v;
            }
            return new _a({ start, end });
        }
    }
    exports.Range1d = Range1d;
    _a = Range1d;
    Range1d.__name__ = "Range1d";
    (() => {
        _a.define(({ Number, Nullable }) => ({
            reset_start: [Nullable(Number), null, {
                    on_update(reset_start, self) {
                        self._reset_start = reset_start !== null && reset_start !== void 0 ? reset_start : self.start;
                    },
                }],
            reset_end: [Nullable(Number), null, {
                    on_update(reset_end, self) {
                        self._reset_end = reset_end !== null && reset_end !== void 0 ? reset_end : self.end;
                    },
                }],
        }));
        _a.override({
            start: 0,
            end: 1,
        });
    })();
},
/* models/ranges/numerical_range.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const range_1 = require(87) /* ./range */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(11) /* ../../core/util/math */;
    class NumericalRange extends range_1.Range {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.NumericalRange = NumericalRange;
    _a = NumericalRange;
    NumericalRange.__name__ = "NumericalRange";
    (() => {
        _a.define(({ Number }) => ({
            start: [Number, p.unset, {
                    convert(value, obj) {
                        const [lower, upper] = obj.computed_bounds;
                        return (0, math_1.clamp)(value, lower, upper);
                    },
                }],
            end: [Number, p.unset, {
                    convert(value, obj) {
                        const [lower, upper] = obj.computed_bounds;
                        return (0, math_1.clamp)(value, lower, upper);
                    },
                }],
        }));
    })();
},
/* models/scales/linear_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_scale_1 = require(91) /* ./continuous_scale */;
    class LinearScale extends continuous_scale_1.ContinuousScale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const [factor, offset] = this._linear_compute_state();
            return (x) => factor * x + offset;
        }
        get s_invert() {
            const [factor, offset] = this._linear_compute_state();
            return (sx) => (sx - offset) / factor;
        }
        /*protected*/ _linear_compute_state() {
            //
            //  (t1 - t0)       (t1 - t0)
            //  --------- * x - --------- * s0 + t0
            //  (s1 - s0)       (s1 - s0)
            //
            // [  factor  ]     [    offset    ]
            //
            const source_start = this.source_range.start;
            const source_end = this.source_range.end;
            const target_start = this.target_range.start;
            const target_end = this.target_range.end;
            const factor = (target_end - target_start) / (source_end - source_start);
            const offset = -(factor * source_start) + target_start;
            return [factor, offset];
        }
    }
    exports.LinearScale = LinearScale;
    LinearScale.__name__ = "LinearScale";
},
/* models/scales/continuous_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(85) /* ./scale */;
    class ContinuousScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContinuousScale = ContinuousScale;
    ContinuousScale.__name__ = "ContinuousScale";
},
/* models/scales/log_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_scale_1 = require(91) /* ./continuous_scale */;
    class LogScale extends continuous_scale_1.ContinuousScale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            return (x) => {
                if (inter_factor == 0)
                    return 0;
                else {
                    const _x = (Math.log(x) - inter_offset) / inter_factor;
                    return isFinite(_x) ? _x * factor + offset : NaN;
                }
            };
        }
        get s_invert() {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            return (xprime) => {
                const value = (xprime - offset) / factor;
                return Math.exp(inter_factor * value + inter_offset);
            };
        }
        _get_safe_factor(orig_start, orig_end) {
            let start = orig_start < 0 ? 0 : orig_start;
            let end = orig_end < 0 ? 0 : orig_end;
            if (start == end) {
                if (start == 0)
                    [start, end] = [1, 10];
                else {
                    const log_val = Math.log10(start);
                    start = 10 ** Math.floor(log_val);
                    if (Math.ceil(log_val) != Math.floor(log_val))
                        end = 10 ** Math.ceil(log_val);
                    else
                        end = 10 ** (Math.ceil(log_val) + 1);
                }
            }
            return [start, end];
        }
        /*protected*/ _compute_state() {
            const source_start = this.source_range.start;
            const source_end = this.source_range.end;
            const target_start = this.target_range.start;
            const target_end = this.target_range.end;
            const screen_range = target_end - target_start;
            const [start, end] = this._get_safe_factor(source_start, source_end);
            let inter_factor;
            let inter_offset;
            if (start == 0) {
                inter_factor = Math.log(end);
                inter_offset = 0;
            }
            else {
                inter_factor = Math.log(end / start);
                inter_offset = Math.log(start);
            }
            const factor = screen_range;
            const offset = target_start;
            return [factor, offset, inter_factor, inter_offset];
        }
    }
    exports.LogScale = LogScale;
    LogScale.__name__ = "LogScale";
},
/* models/scales/categorical_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(85) /* ./scale */;
    const linear_scale_1 = require(90) /* ./linear_scale */;
    const { _linear_compute_state } = linear_scale_1.LinearScale.prototype;
    class CategoricalScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const [factor, offset] = _linear_compute_state.call(this);
            const range = this.source_range;
            return (x) => factor * range.synthetic(x) + offset;
        }
        get s_invert() {
            const [factor, offset] = _linear_compute_state.call(this);
            return (sx) => (sx - offset) / factor;
        }
    }
    exports.CategoricalScale = CategoricalScale;
    CategoricalScale.__name__ = "CategoricalScale";
},
/* models/scales/composite_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const scale_1 = require(85) /* ../scales/scale */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class CompositeScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const source_compute = this.source_scale.s_compute;
            const target_compute = this.target_scale.s_compute;
            return (x) => target_compute(source_compute(x));
        }
        get s_invert() {
            const source_invert = this.source_scale.s_invert;
            const target_invert = this.target_scale.s_invert;
            return (sx) => source_invert(target_invert(sx));
        }
        compute(x) {
            return this.s_compute(x);
        }
        v_compute(xs) {
            const { s_compute } = this;
            return (0, arrayable_1.map)(xs, s_compute); // XXX
        }
        invert(sx) {
            return this.s_invert(sx);
        }
        v_invert(sxs) {
            const { s_invert } = this;
            return (0, arrayable_1.map)(sxs, s_invert); // XXX
        }
    }
    exports.CompositeScale = CompositeScale;
    _a = CompositeScale;
    CompositeScale.__name__ = "CompositeScale";
    (() => {
        _a.define(({ Ref }) => ({
            source_scale: [Ref(scale_1.Scale)],
            target_scale: [Ref(scale_1.Scale)],
        }));
    })();
},
/* models/ranges/data_range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_range_1 = require(96) /* ./data_range */;
    const enums_1 = require(20) /* ../../core/enums */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const logging_1 = require(19) /* ../../core/logging */;
    const bbox = tslib_1.__importStar(require(57) /* ../../core/util/bbox */);
    const util_1 = require(97) /* ../util */;
    exports.auto_ranged = Symbol("auto_ranged");
    function is_auto_ranged(r) {
        return exports.auto_ranged in r;
    }
    exports.is_auto_ranged = is_auto_ranged;
    class DataRange1d extends data_range_1.DataRange {
        constructor(attrs) {
            super(attrs);
            this.have_updated_interactively = false;
        }
        initialize() {
            super.initialize();
            this._initial_start = isNaN(this.start) ? null : this.start;
            this._initial_end = isNaN(this.end) ? null : 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();
        }
        get min() {
            return Math.min(this.start, this.end);
        }
        get max() {
            return Math.max(this.start, this.end);
        }
        computed_renderers() {
            // TODO (bev) check that renderers actually configured with this range
            const { renderers } = this;
            const all_renderers = (0, iterator_1.flat_map)(this.plots, (plot) => plot.auto_ranged_renderers.map((r) => r.model));
            return (0, util_1.compute_renderers)(renderers.length == 0 ? "auto" : renderers, [...all_renderers]);
        }
        /*protected*/ _compute_plot_bounds(renderers, bounds) {
            let result = bbox.empty();
            for (const r of renderers) {
                const rect = bounds.get(r);
                if (rect != null && (r.visible || !this.only_visible)) {
                    result = bbox.union(result, rect);
                }
            }
            return result;
        }
        adjust_bounds_for_aspect(bounds, ratio) {
            const result = bbox.empty();
            let width = bounds.x1 - bounds.x0;
            if (width <= 0) {
                width = 1.0;
            }
            let height = bounds.y1 - bounds.y0;
            if (height <= 0) {
                height = 1.0;
            }
            const xcenter = 0.5 * (bounds.x1 + bounds.x0);
            const 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*/ _compute_min_max(plot_bounds, dimension) {
            let overall = bbox.empty();
            for (const [plot, rect] of plot_bounds) {
                if (plot.model.visible)
                    overall = bbox.union(overall, rect);
            }
            let min, max;
            if (dimension == 0)
                [min, max] = [overall.x0, overall.x1];
            else
                [min, max] = [overall.y0, overall.y1];
            return [min, max];
        }
        /*protected*/ _compute_range(min, max) {
            const range_padding = this.range_padding; // XXX: ? 0
            let 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}`);
                }
                let center, span;
                if (max == min) {
                    span = this.default_span + 0.001;
                    center = Math.log10(min);
                }
                else {
                    let log_min, log_max;
                    if (this.range_padding_units == "percent") {
                        log_min = Math.log10(min);
                        log_max = Math.log10(max);
                        span = (log_max - log_min) * (1 + range_padding);
                    }
                    else {
                        log_min = Math.log10(min - range_padding);
                        log_max = Math.log10(max + range_padding);
                        span = log_max - log_min;
                    }
                    center = (log_min + log_max) / 2.0;
                }
                start = 10 ** (center - span / 2.0);
                end = 10 ** (center + span / 2.0);
            }
            else {
                let span;
                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;
                }
                const center = (max + min) / 2.0;
                start = center - span / 2.0;
                end = center + span / 2.0;
            }
            let follow_sign = +1;
            if (this.flipped) {
                [start, end] = [end, start];
                follow_sign = -1;
            }
            const 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];
        }
        update(bounds, dimension, plot, ratio) {
            if (this.have_updated_interactively)
                return;
            const renderers = this.computed_renderers();
            // update the raw data bounds for all renderers we care about
            let 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
            const [min, max] = this._compute_min_max(this._plot_bounds.entries(), dimension);
            // derive start, end from bounds and data range config
            let [start, end] = this._compute_range(min, max);
            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;
            }
            let needs_emit = false;
            if (this.bounds == "auto") {
                this._computed_bounds = [start, end];
                needs_emit = true;
            }
            // only trigger updates when there are changes
            const [_start, _end] = [this.start, this.end];
            if (start != _start || end != _end) {
                const 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();
            }
        }
        reset() {
            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();
        }
    }
    exports.DataRange1d = DataRange1d;
    _a = DataRange1d;
    DataRange1d.__name__ = "DataRange1d";
    (() => {
        _a.define(({ Boolean, Number, Nullable }) => ({
            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(({ Enum }) => ({
            scale_hint: [Enum("log", "auto"), "auto"],
        }));
    })();
},
/* models/ranges/data_range.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const numerical_range_1 = require(89) /* ./numerical_range */;
    class DataRange extends numerical_range_1.NumericalRange {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DataRange = DataRange;
    _a = DataRange;
    DataRange.__name__ = "DataRange";
    (() => {
        _a.define(({ Array, AnyRef, Or, Auto }) => ({
            renderers: [Or(Array(AnyRef()), Auto), []],
        }));
        _a.override({
            start: NaN,
            end: NaN,
        });
    })();
},
/* models/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function compute_renderers(renderers, all_renderers) {
        return renderers == "auto" ? all_renderers : renderers !== null && renderers !== void 0 ? renderers : [];
    }
    exports.compute_renderers = compute_renderers;
},
/* models/ranges/factor_range.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const range_1 = require(87) /* ./range */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const kinds_1 = require(21) /* ../../core/kinds */;
    const types_1 = require(24) /* ../../core/types */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_2 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../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 = 0) {
        const mapping = new Map();
        for (let i = 0; i < factors.length; i++) {
            const 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 = 0) {
        var _b;
        const mapping = new Map();
        const tops = new Map();
        for (const [f0, f1] of factors) {
            const top = (_b = tops.get(f0)) !== null && _b !== void 0 ? _b : [];
            tops.set(f0, [...top, f1]);
        }
        let suboffset = offset;
        let total_subpad = 0;
        for (const [f0, top] of tops) {
            const n = top.length;
            const [submap, subpad] = map_one_level(top, factor_pad, suboffset);
            total_subpad += subpad;
            const subtot = (0, array_1.sum)(top.map((f1) => submap.get(f1).value));
            mapping.set(f0, { value: subtot / n, mapping: submap });
            suboffset += n + outer_pad + subpad;
        }
        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 = 0) {
        var _b;
        const mapping = new Map();
        const tops = new Map();
        for (const [f0, f1, f2] of factors) {
            const top = (_b = tops.get(f0)) !== null && _b !== void 0 ? _b : [];
            tops.set(f0, [...top, [f1, f2]]);
        }
        let suboffset = offset;
        let total_subpad = 0;
        for (const [f0, top] of tops) {
            const n = top.length;
            const [submap, subpad] = map_two_levels(top, inner_pad, factor_pad, suboffset);
            total_subpad += subpad;
            const subtot = (0, array_1.sum)(top.map(([f1]) => submap.get(f1).value));
            mapping.set(f0, { value: subtot / n, mapping: submap });
            suboffset += n + outer_pad + subpad;
        }
        return [mapping, (tops.size - 1) * outer_pad + total_subpad];
    }
    exports.map_three_levels = map_three_levels;
    class FactorRange extends range_1.Range {
        constructor(attrs) {
            super(attrs);
            this.invalidate_synthetic = new signaling_1.Signal0(this, "invalidate_synthetic");
        }
        get min() {
            return this.start;
        }
        get max() {
            return this.end;
        }
        initialize() {
            super.initialize();
            this._init();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.properties.factors.change, () => this.reset());
            this.connect(this.properties.factor_padding.change, () => this.reset());
            this.connect(this.properties.group_padding.change, () => this.reset());
            this.connect(this.properties.subgroup_padding.change, () => this.reset());
            this.connect(this.properties.range_padding.change, () => this.reset());
            this.connect(this.properties.range_padding_units.change, () => this.reset());
        }
        reset() {
            this._init();
            this.invalidate_synthetic.emit();
        }
        _lookup(x) {
            switch (x.length) {
                case 1: {
                    const [f0] = x;
                    const mapping = this._mapping;
                    const y0 = mapping.get(f0);
                    return y0 != null ? y0.value : NaN;
                }
                case 2: {
                    const [f0, f1] = x;
                    const mapping = this._mapping;
                    const y0 = mapping.get(f0);
                    if (y0 != null) {
                        const y1 = y0.mapping.get(f1);
                        if (y1 != null)
                            return y1.value;
                    }
                    return NaN;
                }
                case 3: {
                    const [f0, f1, f2] = x;
                    const mapping = this._mapping;
                    const y0 = mapping.get(f0);
                    if (y0 != null) {
                        const y1 = y0.mapping.get(f1);
                        if (y1 != null) {
                            const y2 = y1.mapping.get(f2);
                            if (y2 != null)
                                return y2.value;
                        }
                    }
                    return NaN;
                }
            }
        }
        // convert a string factor into a synthetic coordinate
        synthetic(x) {
            if ((0, types_2.isNumber)(x))
                return x;
            if ((0, types_2.isString)(x))
                return this._lookup([x]);
            let offset = 0;
            const 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
        v_synthetic(xs) {
            const n = xs.length;
            const array = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++) {
                array[i] = this.synthetic(xs[i]);
            }
            return array;
        }
        _init() {
            const { levels, mapping, tops, mids, inside_padding } = (() => {
                if ((0, array_1.every)(this.factors, types_2.isString)) {
                    const factors = this.factors;
                    const [mapping, inside_padding] = map_one_level(factors, this.factor_padding);
                    const tops = null;
                    const mids = null;
                    return { levels: 1, mapping, tops, mids, inside_padding };
                }
                else if ((0, array_1.every)(this.factors, (x) => (0, types_2.isArray)(x) && x.length == 2 && (0, types_2.isString)(x[0]) && (0, types_2.isString)(x[1]))) {
                    const factors = this.factors;
                    const [mapping, inside_padding] = map_two_levels(factors, this.group_padding, this.factor_padding);
                    const tops = [...mapping.keys()];
                    const mids = null;
                    return { levels: 2, mapping, tops, mids, inside_padding };
                }
                else if ((0, array_1.every)(this.factors, (x) => (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]))) {
                    const factors = this.factors;
                    const [mapping, inside_padding] = map_three_levels(factors, this.group_padding, this.subgroup_padding, this.factor_padding);
                    const tops = [...mapping.keys()];
                    const mids = [];
                    for (const [f0, L2] of mapping) {
                        for (const f1 of L2.mapping.keys()) {
                            mids.push([f0, f1]);
                        }
                    }
                    return { levels: 3, mapping, tops, mids, inside_padding };
                }
                else
                    (0, assert_1.unreachable)();
            })();
            this._mapping = mapping;
            this.tops = tops;
            this.mids = mids;
            let start = 0;
            let end = this.factors.length + inside_padding;
            if (this.range_padding_units == "percent") {
                const 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, end, levels }, { silent: true });
            if (this.bounds == "auto") {
                this._computed_bounds = [start, end];
            }
        }
    }
    exports.FactorRange = FactorRange;
    _a = FactorRange;
    FactorRange.__name__ = "FactorRange";
    (() => {
        _a.define(({ Number }) => ({
            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, p.unset, { readonly: true }],
            end: [Number, p.unset, { readonly: true }],
        }));
        _a.internal(({ Number, String, Array, Tuple, Nullable }) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(100) /* ./data_annotation */;
    const arrow_head_1 = require(141) /* ./arrow_head */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const enums_1 = require(20) /* ../../core/enums */;
    const types_1 = require(24) /* ../../core/types */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const types_2 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(11) /* ../../core/util/math */;
    class ArrowView extends data_annotation_1.DataAnnotationView {
        *children() {
            yield* super.children();
            const { start, end } = this;
            if (start != null)
                yield start;
            if (end != null)
                yield end;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { start, end } = this.model;
            if (start != null)
                this.start = await (0, build_views_1.build_view)(start, { parent: this });
            if (end != null)
                this.end = await (0, build_views_1.build_view)(end, { parent: this });
        }
        set_data(source) {
            var _b, _c;
            super.set_data(source);
            const indices = types_2.Indices.all_set(this._x_start.length);
            (_b = this.start) === null || _b === void 0 ? void 0 : _b.set_data(source, indices);
            (_c = this.end) === null || _c === void 0 ? void 0 : _c.set_data(source, indices);
        }
        remove() {
            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.remove();
        }
        map_data() {
            const { frame } = this.plot_view;
            const [sx_start, sy_start] = (() => {
                switch (this.model.start_units) {
                    case "canvas": {
                        return [
                            new types_1.ScreenArray(this._x_start),
                            new types_1.ScreenArray(this._y_start),
                        ];
                    }
                    case "screen": {
                        return [
                            frame.bbox.xview.v_compute(this._x_start),
                            frame.bbox.yview.v_compute(this._y_start),
                        ];
                    }
                    case "data": {
                        return [
                            this.coordinates.x_scale.v_compute(this._x_start),
                            this.coordinates.y_scale.v_compute(this._y_start),
                        ];
                    }
                }
            })();
            const [sx_end, sy_end] = (() => {
                switch (this.model.end_units) {
                    case "canvas": {
                        return [
                            new types_1.ScreenArray(this._x_end),
                            new types_1.ScreenArray(this._y_end),
                        ];
                    }
                    case "screen": {
                        return [
                            frame.bbox.xview.v_compute(this._x_end),
                            frame.bbox.yview.v_compute(this._y_end),
                        ];
                    }
                    case "data": {
                        return [
                            this.coordinates.x_scale.v_compute(this._x_end),
                            this.coordinates.y_scale.v_compute(this._y_end),
                        ];
                    }
                }
            })();
            this._sx_start = sx_start;
            this._sy_start = sy_start;
            this._sx_end = sx_end;
            this._sy_end = sy_end;
            const n = sx_start.length;
            const angles = this._angles = new types_1.ScreenArray(n);
            for (let 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]]);
            }
        }
        paint(ctx) {
            const { start, end } = this;
            const { _sx_start, _sy_start, _sx_end, _sy_end, _angles } = this;
            const { x, y, width, height } = this.plot_view.frame.bbox;
            for (let 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)
                    continue;
                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();
                }
                ctx.beginPath();
                ctx.moveTo(_sx_start[i], _sy_start[i]);
                ctx.lineTo(_sx_end[i], _sy_end[i]);
                this.visuals.line.apply(ctx, i);
                ctx.restore();
            }
        }
    }
    exports.ArrowView = ArrowView;
    ArrowView.__name__ = "ArrowView";
    class Arrow extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Arrow = Arrow;
    _a = Arrow;
    Arrow.__name__ = "Arrow";
    (() => {
        _a.prototype.default_view = ArrowView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(({ Ref, Nullable }) => ({
            x_start: [p.XCoordinateSpec, { field: "x_start" }],
            y_start: [p.YCoordinateSpec, { field: "y_start" }],
            start_units: [enums_1.CoordinateUnits, "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.CoordinateUnits, "data"],
            end: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.OpenHead()],
        }));
    })();
},
/* models/annotations/data_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const columnar_data_source_1 = require(101) /* ../sources/columnar_data_source */;
    const column_data_source_1 = require(106) /* ../sources/column_data_source */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class DataAnnotationView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._initial_set_data = false;
        }
        connect_signals() {
            super.connect_signals();
            const update = () => {
                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);
        }
        _rerender() {
            this.request_render();
        }
        set_data(source) {
            const self = this;
            for (const prop of this.model) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                    continue;
                if (prop instanceof p.BaseCoordinateSpec) {
                    const array = prop.array(source);
                    self[`_${prop.attr}`] = array;
                }
                else {
                    const uniform = prop.uniform(source);
                    self[`${prop.attr}`] = uniform;
                }
            }
            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);
            }
            for (const visual of this.visuals) {
                visual.update();
            }
        }
        _render() {
            if (!this._initial_set_data) {
                this.set_data(this.model.source);
                this._initial_set_data = true;
            }
            this.map_data();
            this.paint(this.layer.ctx);
        }
    }
    exports.DataAnnotationView = DataAnnotationView;
    DataAnnotationView.__name__ = "DataAnnotationView";
    class DataAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DataAnnotation = DataAnnotation;
    _a = DataAnnotation;
    DataAnnotation.__name__ = "DataAnnotation";
    (() => {
        _a.define(({ Ref }) => ({
            source: [Ref(columnar_data_source_1.ColumnarDataSource), () => new column_data_source_1.ColumnDataSource()],
        }));
    })();
},
/* models/sources/columnar_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const logging_1 = require(19) /* ../../core/logging */;
    const selection_manager_1 = require(102) /* ../../core/selection_manager */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const array_1 = require(10) /* ../../core/util/array */;
    const ndarray_1 = require(30) /* ../../core/util/ndarray */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const interaction_policy_1 = require(104) /* ../selections/interaction_policy */;
    const selection_1 = require(103) /* ../selections/selection */;
    const data_source_1 = require(105) /* ./data_source */;
    class ColumnarDataSource extends data_source_1.DataSource {
        get_array(key) {
            let 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;
        }
        constructor(attrs) {
            super(attrs);
            this.selection_manager = new selection_manager_1.SelectionManager(this);
        }
        initialize() {
            super.initialize();
            this._select = new signaling_1.Signal0(this, "select");
            this.inspect = new signaling_1.Signal(this, "inspect");
        }
        get_column(name) {
            return name in this.data ? this.data[name] : null;
        }
        columns() {
            // return the column names in this data source
            return (0, object_1.keys)(this.data);
        }
        get_length(soft = true) {
            const lengths = (0, array_1.uniq)((0, object_1.values)(this.data).map((v) => (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: {
                    const msg = "data source has columns of inconsistent lengths";
                    if (soft) {
                        logging_1.logger.warn(msg);
                        return lengths.sort()[0];
                    }
                    else
                        throw new Error(msg);
                }
            }
        }
        get length() {
            var _b;
            return (_b = this.get_length()) !== null && _b !== void 0 ? _b : 0;
        }
        clear() {
            const empty = {};
            for (const col of this.columns()) {
                empty[col] = new this.data[col].constructor(0);
            }
            this.data = empty;
        }
        stream(new_data, rollover, { sync } = {}) {
            this.stream_to(this.properties.data, new_data, rollover, { sync });
        }
        patch(patches, { sync } = {}) {
            this.patch_to(this.properties.data, patches, { sync });
        }
    }
    exports.ColumnarDataSource = ColumnarDataSource;
    _a = ColumnarDataSource;
    ColumnarDataSource.__name__ = "ColumnarDataSource";
    (() => {
        _a.define(({ Ref }) => ({
            selection_policy: [Ref(interaction_policy_1.SelectionPolicy), () => new interaction_policy_1.UnionRenderers()],
        }));
        _a.internal(({ AnyRef }) => ({
            inspected: [AnyRef(), () => new selection_1.Selection()],
        }));
    })();
},
/* core/selection_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selection_1 = require(103) /* ../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";
    }
    class SelectionManager {
        constructor(source) {
            this.inspectors = new Map();
            this.source = source;
        }
        select(renderer_views, geometry, final, mode = "replace") {
            // divide renderers into glyph_renderers or graph_renderers
            const glyph_renderer_views = [];
            const graph_renderer_views = [];
            for (const r of renderer_views) {
                if (is_GlyphRendererView(r))
                    glyph_renderer_views.push(r);
                else if (is_GraphRendererView(r))
                    graph_renderer_views.push(r);
            }
            let did_hit = false;
            // graph renderer case
            for (const r of graph_renderer_views) {
                const 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);
            }
            // glyph renderers
            if (glyph_renderer_views.length > 0) {
                const 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;
        }
        inspect(renderer_view, geometry) {
            let did_hit = false;
            if (is_GlyphRendererView(renderer_view)) {
                const hit_test_result = renderer_view.hit_test(geometry);
                if (hit_test_result != null) {
                    did_hit = !hit_test_result.is_empty();
                    const 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 }]);
                }
            }
            else if (is_GraphRendererView(renderer_view)) {
                const hit_test_result = renderer_view.model.inspection_policy.hit_test(geometry, renderer_view);
                did_hit = renderer_view.model.inspection_policy.do_inspection(hit_test_result, geometry, renderer_view, false, "replace");
            }
            return did_hit;
        }
        clear(rview) {
            this.source.selected.clear();
            if (rview != null)
                this.get_or_create_inspector(rview.model).clear();
        }
        get_or_create_inspector(renderer) {
            let selection = this.inspectors.get(renderer);
            if (selection == null) {
                selection = new selection_1.Selection();
                this.inspectors.set(renderer, selection);
            }
            return selection;
        }
    }
    exports.SelectionManager = SelectionManager;
    SelectionManager.__name__ = "SelectionManager";
},
/* models/selections/selection.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    exports.OpaqueIndices = (0, kinds_1.Arrayable)(kinds_1.Int);
    class Selection extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get_view() {
            return this.view;
        }
        get selected_glyph() {
            return this.selected_glyphs.length > 0 ? this.selected_glyphs[0] : null;
        }
        add_to_selected_glyphs(glyph) {
            this.selected_glyphs.push(glyph);
        }
        update(selection, _final = true, 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;
                }
            }
        }
        clear() {
            this.indices = [];
            this.line_indices = [];
            this.multiline_indices = {};
            this.image_indices = [];
            this.view = null;
            this.selected_glyphs = [];
        }
        map(mapper) {
            return new _a(Object.assign(Object.assign({}, this.attributes), { indices: (0, arrayable_1.map)(this.indices, mapper),
                // NOTE: line_indices don't support subset indexing
                multiline_indices: (0, object_1.to_object)((0, object_1.entries)(this.multiline_indices).map(([index, line_indices]) => [mapper(Number(index)), line_indices])), image_indices: this.image_indices.map((ndx) => (Object.assign(Object.assign({}, ndx), { index: mapper(ndx.index) }))) }));
        }
        is_empty() {
            return this.indices.length == 0 && this.line_indices.length == 0 && this.image_indices.length == 0;
        }
        update_through_union(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);
        }
        update_through_intersection(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);
        }
        update_through_subtraction(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);
        }
    }
    exports.Selection = Selection;
    _a = Selection;
    Selection.__name__ = "Selection";
    (() => {
        _a.define(({ Int, Array, Dict, Struct }) => ({
            indices: [exports.OpaqueIndices, []],
            line_indices: [exports.OpaqueIndices, []],
            multiline_indices: [Dict(exports.OpaqueIndices), {}],
            image_indices: [Array(Struct({ index: Int, i: Int, j: Int, flat_index: Int })), []],
        }));
        _a.internal(({ Array, AnyRef, Nullable }) => ({
            selected_glyphs: [Array(AnyRef()), []],
            view: [Nullable(AnyRef()), null],
        }));
    })();
},
/* models/selections/interaction_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class SelectionPolicy extends model_1.Model {
        do_selection(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();
            }
        }
    }
    exports.SelectionPolicy = SelectionPolicy;
    SelectionPolicy.__name__ = "SelectionPolicy";
    class IntersectRenderers extends SelectionPolicy {
        hit_test(geometry, renderer_views) {
            const hit_test_result_renderers = [];
            for (const r of renderer_views) {
                const result = r.hit_test(geometry);
                if (result != null)
                    hit_test_result_renderers.push(result);
            }
            if (hit_test_result_renderers.length > 0) {
                const hit_test_result = hit_test_result_renderers[0];
                for (const hit_test_result_other of hit_test_result_renderers) {
                    hit_test_result.update_through_intersection(hit_test_result_other);
                }
                return hit_test_result;
            }
            else {
                return null;
            }
        }
    }
    exports.IntersectRenderers = IntersectRenderers;
    IntersectRenderers.__name__ = "IntersectRenderers";
    class UnionRenderers extends SelectionPolicy {
        hit_test(geometry, renderer_views) {
            const hit_test_result_renderers = [];
            for (const r of renderer_views) {
                const result = r.hit_test(geometry);
                if (result != null)
                    hit_test_result_renderers.push(result);
            }
            if (hit_test_result_renderers.length > 0) {
                const hit_test_result = hit_test_result_renderers[0];
                for (const hit_test_result_other of hit_test_result_renderers) {
                    hit_test_result.update_through_union(hit_test_result_other);
                }
                return hit_test_result;
            }
            else {
                return null;
            }
        }
    }
    exports.UnionRenderers = UnionRenderers;
    UnionRenderers.__name__ = "UnionRenderers";
},
/* models/sources/data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const selection_1 = require(103) /* ../selections/selection */;
    class DataSource extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DataSource = DataSource;
    _a = DataSource;
    DataSource.__name__ = "DataSource";
    (() => {
        _a.define(({ Ref }) => ({
            selected: [Ref(selection_1.Selection), () => new selection_1.Selection(), { readonly: true }],
        }));
    })();
},
/* models/sources/column_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const columnar_data_source_1 = require(101) /* ./columnar_data_source */;
    class ColumnDataSource extends columnar_data_source_1.ColumnarDataSource {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ColumnDataSource = ColumnDataSource;
    _a = ColumnDataSource;
    ColumnDataSource.__name__ = "ColumnDataSource";
    (() => {
        _a.define(({ Any, Dict, Arrayable }) => ({
            data: [Dict(Arrayable(Any)), {}],
        }));
    })();
},
/* core/util/projections.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const core_1 = tslib_1.__importDefault(require(108) /* proj4/lib/core */);
    const Proj_1 = tslib_1.__importDefault(require(109) /* proj4/lib/Proj */);
    const types_1 = require(24) /* ../types */;
    const mercator = new Proj_1.default("GOOGLE");
    const wgs84 = new Proj_1.default("WGS84");
    const _wgs84_mercator = (0, core_1.default)(wgs84, mercator);
    exports.wgs84_mercator = {
        compute(x, y) {
            if (isFinite(x) && isFinite(y))
                return _wgs84_mercator.forward([x, y]);
            else
                return [NaN, NaN];
        },
        invert(merc_x, merc_y) {
            if (isFinite(merc_x) && isFinite(merc_y))
                return _wgs84_mercator.inverse([merc_x, merc_y]);
            else
                return [NaN, NaN];
        },
    };
    const mercator_bounds = {
        lon: [-20026376.39, 20026376.39],
        lat: [-20048966.10, 20048966.10],
    };
    const latlon_bounds = {
        lon: [-180, 180],
        lat: [-85.06, 85.06],
    };
    const { min, max } = Math;
    function clip_mercator(low, high, dimension) {
        const [vmin, vmax] = mercator_bounds[dimension];
        return [max(low, vmin), min(high, vmax)];
    }
    exports.clip_mercator = clip_mercator;
    function in_bounds(value, dimension) {
        const [min, max] = latlon_bounds[dimension];
        return min < value && value < max;
    }
    exports.in_bounds = in_bounds;
    (function (inplace) {
        function project_xy(x, y, merc_x, merc_y) {
            const 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 (let i = 0; i < n; i++) {
                const xi = x[i];
                const yi = y[i];
                const [merc_xi, merc_yi] = exports.wgs84_mercator.compute(xi, yi);
                merc_x[i] = merc_xi;
                merc_y[i] = merc_yi;
            }
        }
        inplace.project_xy = project_xy;
        function project_xsys(xs, ys, merc_xs, merc_ys) {
            const 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 (let 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) {
        const n = min(x.length, y.length);
        const ArrayType = (0, types_1.infer_type)(x, y);
        const merc_x = new ArrayType(n);
        const 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) {
        const n = min(xs.length, ys.length);
        const merc_xs = new Array(n);
        const merc_ys = new Array(n);
        for (let i = 0; i < n; i++) {
            const [merc_x, merc_y] = project_xy(xs[i], ys[i]);
            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();
    const tslib_1 = require(1) /* tslib */;
    const Proj_1 = tslib_1.__importDefault(require(109) /* ./Proj */);
    const transform_1 = tslib_1.__importDefault(require(135) /* ./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();
    const tslib_1 = require(1) /* tslib */;
    const parseCode_1 = tslib_1.__importDefault(require(110) /* ./parseCode */);
    const extend_1 = tslib_1.__importDefault(require(121) /* ./extend */);
    const projections_1 = tslib_1.__importDefault(require(122) /* ./projections */);
    const deriveConstants_1 = require(130) /* ./deriveConstants */;
    const Datum_1 = tslib_1.__importDefault(require(132) /* ./constants/Datum */);
    const datum_1 = tslib_1.__importDefault(require(133) /* ./datum */);
    const match_1 = tslib_1.__importDefault(require(117) /* ./match */);
    const nadgrid_1 = require(134) /* ./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 calculated 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();
    const tslib_1 = require(1) /* tslib */;
    const defs_1 = tslib_1.__importDefault(require(111) /* ./defs */);
    const wkt_parser_1 = tslib_1.__importDefault(require(118) /* wkt-parser */);
    const projString_1 = tslib_1.__importDefault(require(113) /* ./projString */);
    const match_1 = tslib_1.__importDefault(require(117) /* ./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();
    const tslib_1 = require(1) /* tslib */;
    const global_1 = tslib_1.__importDefault(require(112) /* ./global */);
    const projString_1 = tslib_1.__importDefault(require(113) /* ./projString */);
    const wkt_parser_1 = tslib_1.__importDefault(require(118) /* 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();
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(114) /* ./constants/values */;
    const PrimeMeridian_1 = tslib_1.__importDefault(require(115) /* ./constants/PrimeMeridian */);
    const units_1 = tslib_1.__importDefault(require(116) /* ./constants/units */);
    const match_1 = tslib_1.__importDefault(require(117) /* ./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();
    const tslib_1 = require(1) /* tslib */;
    var D2R = 0.01745329251994329577;
    const parser_1 = tslib_1.__importDefault(require(119) /* ./parser */);
    const process_1 = require(120) /* ./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;
        }
        else if (!wkt.lat_ts && wkt.lat0 && wkt.projName === 'Polar_Stereographic') {
            wkt.lat_ts = wkt.lat0;
            wkt.lat0 = d2r(wkt.lat0 > 0 ? 90 : -90);
        }
    }
    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();
    const tslib_1 = require(1) /* tslib */;
    const merc_1 = tslib_1.__importDefault(require(123) /* ./projections/merc */);
    const longlat_1 = tslib_1.__importDefault(require(129) /* ./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();
    const tslib_1 = require(1) /* tslib */;
    const msfnz_1 = tslib_1.__importDefault(require(124) /* ../common/msfnz */);
    const adjust_lon_1 = tslib_1.__importDefault(require(125) /* ../common/adjust_lon */);
    const tsfnz_1 = tslib_1.__importDefault(require(127) /* ../common/tsfnz */);
    const phi2z_1 = tslib_1.__importDefault(require(128) /* ../common/phi2z */);
    const values_1 = require(114) /* ../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();
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(114) /* ../constants/values */;
    const sign_1 = tslib_1.__importDefault(require(126) /* ./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();
    const values_1 = require(114) /* ../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();
    const values_1 = require(114) /* ../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();
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(114) /* ./constants/values */;
    const Ellipsoid_1 = tslib_1.__importStar(require(131) /* ./constants/Ellipsoid */);
    const match_1 = tslib_1.__importDefault(require(117) /* ./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.clrk80ign = {
        a: 6378249.2,
        b: 6356515,
        rf: 293.4660213,
        ellipseName: "Clarke 1880 (IGN)"
    };
    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();
    const values_1 = require(114) /* ./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();
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(114) /* ./constants/values */;
    const datum_transform_1 = tslib_1.__importDefault(require(136) /* ./datum_transform */);
    const adjust_axis_1 = tslib_1.__importDefault(require(138) /* ./adjust_axis */);
    const Proj_1 = tslib_1.__importDefault(require(109) /* ./Proj */);
    const toPoint_1 = tslib_1.__importDefault(require(139) /* ./common/toPoint */);
    const checkSanity_1 = tslib_1.__importDefault(require(140) /* ./checkSanity */);
    function checkNotWGS(source, dest) {
        return ((source.datum.datum_type === values_1.PJD_3PARAM || source.datum.datum_type === values_1.PJD_7PARAM || source.datum.datum_type === values_1.PJD_GRIDSHIFT) && dest.datumCode !== 'WGS84') ||
            ((dest.datum.datum_type === values_1.PJD_3PARAM || dest.datum.datum_type === values_1.PJD_7PARAM || dest.datum.datum_type === values_1.PJD_GRIDSHIFT) && source.datumCode !== 'WGS84');
    }
    function transform(source, dest, point, enforceAxis) {
        var wgs84;
        if (Array.isArray(point)) {
            point = (0, toPoint_1.default)(point);
        }
        else {
            // Clone the point object so inputs don't get modified
            point = {
                x: point.x,
                y: point.y,
                z: point.z,
                m: point.m
            };
        }
        var hasZ = point.z !== undefined;
        (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);
        }
        if (!hasZ) {
            delete point.z;
        }
        return point;
    }
    exports.default = transform;
},
/* proj4/lib/datum_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(114) /* ./constants/values */;
    const datumUtils_1 = require(137) /* ./datumUtils */;
    const adjust_lon_1 = tslib_1.__importDefault(require(125) /* ./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();
    const values_1 = require(114) /* ./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) {
    var _a, _b, _c, _d, _e;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const marking_1 = require(142) /* ../graphics/marking */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class ArrowHeadView extends marking_1.MarkingView {
    }
    exports.ArrowHeadView = ArrowHeadView;
    ArrowHeadView.__name__ = "ArrowHeadView";
    class ArrowHead extends marking_1.Marking {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ArrowHead = ArrowHead;
    _a = ArrowHead;
    ArrowHead.__name__ = "ArrowHead";
    (() => {
        _a.define(() => ({
            size: [p.NumberSpec, 25],
        }));
    })();
    class OpenHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const 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);
        }
        render(ctx, i) {
            const 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);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.OpenHeadView = OpenHeadView;
    OpenHeadView.__name__ = "OpenHeadView";
    class OpenHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.OpenHead = OpenHead;
    _b = OpenHead;
    OpenHead.__name__ = "OpenHead";
    (() => {
        _b.prototype.default_view = OpenHeadView;
        _b.mixins(property_mixins_1.LineVector);
    })();
    class NormalHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const 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);
        }
        render(ctx, i) {
            const 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();
            this.visuals.fill.apply(ctx, i);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.NormalHeadView = NormalHeadView;
    NormalHeadView.__name__ = "NormalHeadView";
    class NormalHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.NormalHead = NormalHead;
    _c = NormalHead;
    NormalHead.__name__ = "NormalHead";
    (() => {
        _c.prototype.default_view = NormalHeadView;
        _c.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector]);
        _c.override({
            fill_color: "black",
        });
    })();
    class VeeHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const 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);
        }
        render(ctx, i) {
            const 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();
            this.visuals.fill.apply(ctx, i);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.VeeHeadView = VeeHeadView;
    VeeHeadView.__name__ = "VeeHeadView";
    class VeeHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VeeHead = VeeHead;
    _d = VeeHead;
    VeeHead.__name__ = "VeeHead";
    (() => {
        _d.prototype.default_view = VeeHeadView;
        _d.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector]);
        _d.override({
            fill_color: "black",
        });
    })();
    class TeeHeadView extends ArrowHeadView {
        render(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, 0);
            ctx.lineTo(-0.5 * size_i, 0);
            this.visuals.line.apply(ctx, i);
        }
        clip(_ctx, _i) { }
    }
    exports.TeeHeadView = TeeHeadView;
    TeeHeadView.__name__ = "TeeHeadView";
    class TeeHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TeeHead = TeeHead;
    _e = TeeHead;
    TeeHead.__name__ = "TeeHead";
    (() => {
        _e.prototype.default_view = TeeHeadView;
        _e.mixins(property_mixins_1.LineVector);
    })();
},
/* models/graphics/marking.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(50) /* ../../model */;
    const view_1 = require(54) /* ../../core/view */;
    const visuals = tslib_1.__importStar(require(75) /* ../../core/visuals */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class MarkingView extends view_1.View {
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        request_render() {
            this.parent.request_render();
        }
        get canvas() {
            return this.parent.canvas;
        }
        set_data(source, indices) {
            const self = this;
            for (const prop of this.model) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                    continue;
                const uniform = prop.uniform(source).select(indices);
                self[`${prop.attr}`] = uniform;
            }
        }
    }
    exports.MarkingView = MarkingView;
    MarkingView.__name__ = "MarkingView";
    class Marking extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Marking = Marking;
    _a = Marking;
    Marking.__name__ = "Marking";
    (() => {
        _a.define(({}) => ({}));
    })();
},
/* models/annotations/base_color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const title_1 = require(144) /* ./title */;
    const cartesian_frame_1 = require(159) /* ../canvas/cartesian_frame */;
    const axes_1 = require(160) /* ../axes */;
    const ticker_1 = require(163) /* ../tickers/ticker */;
    const tickers_1 = require(194) /* ../tickers */;
    const tick_formatter_1 = require(164) /* ../formatters/tick_formatter */;
    const formatters_1 = require(224) /* ../formatters */;
    const labeling_1 = require(165) /* ../policies/labeling */;
    const scales_1 = require(228) /* ../scales */;
    const ranges_1 = require(230) /* ../ranges */;
    const base_text_1 = require(149) /* ../text/base_text */;
    const enums_1 = require(20) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const layout_1 = require(231) /* ../../core/layout */;
    const alignments_1 = require(232) /* ../../core/layout/alignments */;
    const border_1 = require(234) /* ../../core/layout/border */;
    const side_panel_1 = require(146) /* ../../core/layout/side_panel */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const types_1 = require(8) /* ../../core/util/types */;
    const object_1 = require(9) /* ../../core/util/object */;
    const MINOR_DIM = 25;
    const MAJOR_DIM_MIN_SCALAR = 0.3;
    const MAJOR_DIM_MAX_SCALAR = 0.8;
    class BaseColorBarView extends annotation_1.AnnotationView {
        get orientation() {
            return this._orientation;
        }
        *children() {
            yield* super.children();
            yield this._axis_view;
            yield this._title_view;
        }
        initialize() {
            super.initialize();
            const { ticker, formatter } = this.model;
            this._ticker = ticker != "auto" ? ticker : this._create_ticker();
            this._formatter = formatter != "auto" ? formatter : this._create_formatter();
            this._major_range = this._create_major_range();
            this._major_scale = this._create_major_scale();
            this._minor_range = new ranges_1.Range1d({ start: 0, end: 1 });
            this._minor_scale = new scales_1.LinearScale();
            // configure some frame, update when the layout is know
            this._frame = new cartesian_frame_1.CartesianFrame(this._major_scale, this._minor_scale, this._major_range, this._minor_range);
            this._axis = this._create_axis();
            this._apply_axis_properties();
            this._title = new title_1.Title();
            this._apply_title_properties();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const self = this;
            const 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() {
                    // force re-layout; not ideal but ColorBar's layout doesn't fully
                    // participate in has_size_changed to detect if layout is needed
                    self.layout.dirty = true;
                    self.parent.request_layout();
                },
                request_paint() {
                    self.parent.request_paint(self);
                },
                request_render() {
                    self.request_paint();
                },
                notify_finished_after_paint() {
                    self.parent.notify_finished_after_paint();
                },
            };
            this._axis_view = await (0, build_views_1.build_view)(this._axis, { parent });
            this._title_view = await (0, build_views_1.build_view)(this._title, { parent });
        }
        remove() {
            this._title_view.remove();
            this._axis_view.remove();
            super.remove();
        }
        _apply_axis_properties() {
            const attrs = Object.assign(Object.assign(Object.assign({ ticker: this._ticker, formatter: this._formatter, major_label_standoff: this.model.label_standoff, axis_line_color: null, 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_overrides: this.model.major_label_overrides, major_label_policy: this.model.major_label_policy }, mixins.attrs_of(this.model, "major_label_", mixins.Text, true)), mixins.attrs_of(this.model, "major_tick_", mixins.Line, true)), mixins.attrs_of(this.model, "minor_tick_", mixins.Line, true));
            this._axis.setv(attrs);
        }
        _apply_title_properties() {
            var _b;
            const attrs = Object.assign({ text: (_b = this.model.title) !== null && _b !== void 0 ? _b : "", standoff: this.model.title_standoff }, mixins.attrs_of(this.model, "title_", mixins.Text, false));
            this._title.setv(attrs);
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => {
                this._apply_title_properties();
                this._apply_axis_properties();
                // TODO?: this.plot_view.invalidate_layout()
            });
            this.connect(this._ticker.change, () => this.request_render());
            this.connect(this._formatter.change, () => this.request_render());
        }
        _update_frame() {
            const [x_scale, y_scale, x_range, y_range] = (() => {
                if (this.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];
            })();
            this._frame.in_x_scale = x_scale;
            this._frame.in_y_scale = y_scale;
            this._frame.x_range = x_range;
            this._frame.y_range = y_range;
            this._frame.configure_scales();
        }
        update_layout() {
            const { location, width: w, height: h, padding, margin } = this.model;
            const [valign, halign] = (() => {
                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"
            })();
            const orientation = this._orientation = (() => {
                const { orientation } = this.model;
                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;
            })();
            this._update_frame();
            const center_panel = new alignments_1.NodeLayout();
            const top_panel = new alignments_1.VStack();
            const bottom_panel = new alignments_1.VStack();
            const left_panel = new alignments_1.HStack();
            const 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.on_resize((bbox) => this._frame.set_geometry(bbox));
            const 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;
            const padding_box = { left: padding, right: padding, top: padding, bottom: padding };
            const margin_box = (() => {
                if (this.panel == null) {
                    if ((0, types_1.isString)(location))
                        return { left: margin, right: margin, top: margin, bottom: margin };
                    else {
                        const [left, bottom] = location;
                        return { left, right: margin, top: margin, 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 = (outer, inner) => {
                            const origin = outer;
                            if (orientation == "horizontal") {
                                const { top, width, height } = outer;
                                if (halign == "end") {
                                    const { right } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ right, top, width, height });
                                }
                                else if (halign == "center") {
                                    const { hcenter } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ hcenter: Math.round(hcenter), top, width, height });
                                }
                            }
                            else {
                                const { left, width, height } = outer;
                                if (valign == "end") {
                                    const { bottom } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ left, bottom, width, height });
                                }
                                else if (valign == "center") {
                                    const { vcenter } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ left, vcenter: Math.round(vcenter), width, height });
                                }
                            }
                            if (inner != null) {
                                const dh = outer.left - origin.left;
                                const dv = outer.top - origin.top;
                                const { left, top, width, height } = inner;
                                inner = new bbox_1.BBox({ left: left + dh, top: top + dv, width, height });
                            }
                            return [outer, inner];
                        };
                        return undefined;
                    }
                    else {
                        const [left, bottom] = location;
                        layout.fixup_geometry = (outer, inner) => {
                            const origin = outer;
                            const grid = this.layout.bbox;
                            const { width, height } = outer;
                            outer = new bbox_1.BBox({ left: grid.left + left, bottom: grid.bottom - bottom, width, height });
                            if (inner != null) {
                                const dh = outer.left - origin.left;
                                const dv = outer.top - origin.top;
                                const { left, top, width, height } = inner;
                                inner = new bbox_1.BBox({ left: left + dh, top: top + dv, width, height });
                            }
                            return [outer, inner];
                        };
                        return { left, right: 0, top: 0, bottom };
                    }
                }
            })();
            layout.padding = padding_box;
            let major_policy;
            let major_size;
            let min_major_size;
            let 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";
                    const major_size_factor = this._get_major_size_factor();
                    if (major_size_factor != null)
                        major_size = major_size_factor * 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") {
                const width = w == "auto" ? undefined : w;
                const 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, valign, margin: margin_box,
                });
                layout.center_panel.set_sizing({ width_policy: w == "auto" ? "fit" : "fixed", height_policy: "fixed", width, height });
            }
            else {
                const width = w == "auto" ? MINOR_DIM : w;
                const 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, valign, margin: margin_box,
                });
                layout.center_panel.set_sizing({ width_policy: "fixed", height_policy: h == "auto" ? "fit" : "fixed", width, 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" });
            const { _title_view } = this;
            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);
            }
            const { panel } = this;
            const side = (() => {
                if (panel != null && orientation == panel.orientation)
                    return panel.side;
                else
                    return orientation == "horizontal" ? "below" : "right";
            })();
            const stack = (() => {
                switch (side) {
                    case "above":
                        return top_panel;
                    case "below":
                        return bottom_panel;
                    case "left":
                        return left_panel;
                    case "right":
                        return right_panel;
                }
            })();
            const { _axis_view } = this;
            _axis_view.panel = new side_panel_1.Panel(side);
            _axis_view.update_layout();
            if (_axis_view.layout != null)
                stack.children.push(_axis_view.layout);
            if (this.panel != null) {
                const outer = new layout_1.Grid([{ 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;
            }
            const { visible } = this.model;
            this.layout.sizing.visible = visible;
        }
        _create_axis() {
            return new axes_1.LinearAxis();
        }
        _create_formatter() {
            return new formatters_1.BasicTickFormatter();
        }
        _create_major_range() {
            return new ranges_1.Range1d({ start: 0, end: 1 });
        }
        _create_major_scale() {
            return new scales_1.LinearScale();
        }
        _create_ticker() {
            return new tickers_1.BasicTicker();
        }
        _get_major_size_factor() {
            return null;
        }
        _render() {
            const { ctx } = this.layer;
            ctx.save();
            this._paint_bbox(ctx, this._inner_layout.bbox);
            this._paint_colors(ctx, this._inner_layout.center_panel.bbox);
            this._title_view.render();
            this._axis_view.render();
            ctx.restore();
        }
        _paint_bbox(ctx, bbox) {
            const { x, y } = bbox;
            let { width, height } = bbox;
            // 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();
        }
        serializable_state() {
            const _b = super.serializable_state(), { children = [] } = _b, state = tslib_1.__rest(_b, ["children"]);
            children.push(this._title_view.serializable_state());
            children.push(this._axis_view.serializable_state());
            return Object.assign(Object.assign({}, state), { children });
        }
    }
    exports.BaseColorBarView = BaseColorBarView;
    BaseColorBarView.__name__ = "BaseColorBarView";
    class BaseColorBar extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BaseColorBar = BaseColorBar;
    _a = BaseColorBar;
    BaseColorBar.__name__ = "BaseColorBar";
    (() => {
        _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(({ Alpha, Number, String, Tuple, Map, Or, Ref, Auto, Nullable }) => ({
            location: [Or(enums_1.Anchor, Tuple(Number, Number)), "top_right"],
            orientation: [Or(enums_1.Orientation, Auto), "auto"],
            title: [Nullable(Or(String, Ref(base_text_1.BaseText))), 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: [Map(Or(String, Number), Or(String, Ref(base_text_1.BaseText))), new globalThis.Map(), {
                    convert(v) {
                        return (0, types_1.isPlainObject)(v) ? new object_1.Dict(v) : v;
                    },
                }],
            major_label_policy: [Ref(labeling_1.LabelingPolicy), () => new labeling_1.NoOverlap()],
            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) {
    var _a;
    __esModule();
    const text_annotation_1 = require(145) /* ./text_annotation */;
    const enums_1 = require(20) /* ../../core/enums */;
    class TitleView extends text_annotation_1.TextAnnotationView {
        _get_position() {
            const hmargin = this.model.offset;
            const vmargin = this.model.standoff / 2;
            const { align, vertical_align } = this.model;
            let sx, sy;
            const { bbox } = this.layout;
            switch (this.panel.side) {
                case "above":
                case "below": {
                    switch (vertical_align) {
                        case "top":
                            sy = bbox.top + vmargin;
                            break;
                        case "middle":
                            sy = bbox.vcenter;
                            break;
                        case "bottom":
                            sy = bbox.bottom - vmargin;
                            break;
                    }
                    switch (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 (vertical_align) {
                        case "top":
                            sx = bbox.left + vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.right - vmargin;
                            break;
                    }
                    switch (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 (vertical_align) {
                        case "top":
                            sx = bbox.right - vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.left + vmargin;
                            break;
                    }
                    switch (align) {
                        case "left":
                            sy = bbox.top + hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.bottom - hmargin;
                            break;
                    }
                    break;
                }
            }
            const x_anchor = align;
            const y_anchor = vertical_align == "middle" ? "center" : vertical_align;
            return { sx, sy, x_anchor, y_anchor };
        }
        _render() {
            const position = this._get_position();
            const angle = this.panel.get_label_angle_heuristic("parallel");
            this._paint(this.layer.ctx, position, angle);
        }
        _get_size() {
            if (!this.displayed)
                return { width: 0, height: 0 };
            const graphics = this._text_view.graphics();
            graphics.visuals = this.visuals.text.values();
            const { width, height } = graphics._size();
            // 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, height: height == 0 ? 0 : 2 + height + this.model.standoff };
        }
    }
    exports.TitleView = TitleView;
    TitleView.__name__ = "TitleView";
    class Title extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Title = Title;
    _a = Title;
    Title.__name__ = "Title";
    (() => {
        _a.prototype.default_view = TitleView;
        _a.define(({ Number }) => ({
            vertical_align: [enums_1.VerticalAlign, "bottom"],
            align: [enums_1.TextAlign, "left"],
            offset: [Number, 0],
            standoff: [Number, 10],
        }));
        _a.override({
            text_font_size: "13px",
            text_font_style: "bold",
            text_line_height: 1.0,
        });
    })();
},
/* models/annotations/text_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const side_panel_1 = require(146) /* ../../core/layout/side_panel */;
    const base_text_1 = require(149) /* ../text/base_text */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const types_1 = require(8) /* ../../core/util/types */;
    const utils_1 = require(150) /* ../text/utils */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    class TextAnnotationView extends annotation_1.AnnotationView {
        *children() {
            yield* super.children();
            yield this._text_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._init_text();
        }
        async _init_text() {
            const { text } = this.model;
            const _text = (0, types_1.isString)(text) ? (0, utils_1.parse_delimited_string)(text) : text;
            this._text_view = await (0, build_views_1.build_view)(_text, { parent: this });
        }
        update_layout() {
            const { panel } = this;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), true);
            else
                this.layout = undefined;
        }
        connect_signals() {
            super.connect_signals();
            const { text } = this.model.properties;
            this.on_change(text, async () => {
                this._text_view.remove();
                await this._init_text();
            });
            this.connect(this.model.change, () => this.request_render());
        }
        remove() {
            this._text_view.remove();
            super.remove();
        }
        has_finished() {
            if (!super.has_finished())
                return false;
            if (!this._text_view.has_finished())
                return false;
            return true;
        }
        get displayed() {
            return super.displayed && this._text_view.model.text != "" && this.visuals.text.doit;
        }
        _paint(ctx, position, angle) {
            const graphics = this._text_view.graphics();
            graphics.angle = angle;
            graphics.position = position;
            graphics.align = "auto";
            graphics.visuals = this.visuals.text.values();
            const { background_fill, border_line } = this.visuals;
            if (background_fill.doit || border_line.doit) {
                const { p0, p1, p2, p3 } = graphics.rect();
                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);
        }
    }
    exports.TextAnnotationView = TextAnnotationView;
    TextAnnotationView.__name__ = "TextAnnotationView";
    class TextAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TextAnnotation = TextAnnotation;
    _a = TextAnnotation;
    TextAnnotation.__name__ = "TextAnnotation";
    (() => {
        _a.mixins([
            mixins.Text,
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
        ]);
        _a.define(({ String, Or, Ref }) => ({
            text: [Or(String, Ref(base_text_1.BaseText)), ""],
        }));
        _a.override({
            background_fill_color: null,
            border_line_color: null,
        });
    })();
},
/* core/layout/side_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(147) /* ./types */;
    const layoutable_1 = require(148) /* ./layoutable */;
    const types_2 = require(8) /* ../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
    const pi2 = Math.PI / 2;
    const _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,
        },
    };
    const _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",
        },
    };
    const _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",
        },
    };
    const _align_lookup_negative = {
        above: "right",
        below: "left",
        left: "right",
        right: "left",
    };
    const _align_lookup_positive = {
        above: "left",
        below: "right",
        left: "right",
        right: "left",
    };
    class Panel {
        constructor(side, face) {
            this.side = side;
            this.face = (() => {
                if (face != null && face != "auto") {
                    return face;
                }
                else {
                    switch (this.side) {
                        case "left":
                        case "above":
                            return "front";
                        case "right":
                        case "below":
                            return "back";
                    }
                }
            })();
            this.dimension = this.side == "above" || this.side == "below" ? 0 : 1;
            this.orientation = this.dimension == 0 ? "horizontal" : "vertical";
            this.is_horizontal = this.dimension == 0;
            this.is_vertical = this.dimension == 1;
            this.normals = (() => {
                const sign = this.face == "front" ? -1 : 1;
                switch (this.side) {
                    case "left": return [sign, 0];
                    case "right": return [sign, 0];
                    case "above": return [0, sign];
                    case "below": return [0, sign];
                }
            })();
        }
        get face_adjusted_side() {
            const { side, face } = this;
            switch (side) {
                case "left":
                case "right":
                    return face == "front" ? "left" : "right";
                case "above":
                case "below":
                    return face == "front" ? "above" : "below";
            }
        }
        get_label_text_heuristics(orient) {
            const side = this.face_adjusted_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],
                };
            }
        }
        get_label_angle_heuristic(orient) {
            if ((0, types_2.isString)(orient)) {
                const side = this.face_adjusted_side;
                return _angle_lookup[side][orient];
            }
            else
                return -orient;
        }
    }
    exports.Panel = Panel;
    Panel.__name__ = "Panel";
    class SideLayout extends layoutable_1.ContentLayoutable {
        constructor(panel, get_size, rotate = false) {
            super();
            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" });
        }
        _content_size() {
            const { width, height } = this.get_size();
            if (!this.rotate || this.panel.is_horizontal)
                return new types_1.Sizeable({ width, height });
            else
                return new types_1.Sizeable({ width: height, height: width });
        }
        has_size_changed() {
            const { width, height } = this._content_size();
            if (this.panel.is_horizontal)
                return this.bbox.height != height;
            else
                return this.bbox.width != width;
        }
    }
    exports.SideLayout = SideLayout;
    SideLayout.__name__ = "SideLayout";
},
/* core/layout/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const kinds_1 = require(21) /* ../kinds */;
    const { min, max } = Math;
    class Sizeable {
        constructor(size = {}) {
            this.width = size.width != null ? size.width : 0;
            this.height = size.height != null ? size.height : 0;
        }
        bounded_to({ width, height }) {
            return new Sizeable({
                width: this.width == Infinity && width != null ? width : this.width,
                height: this.height == Infinity && height != null ? height : this.height,
            });
        }
        expanded_to({ width, height }) {
            return new Sizeable({
                width: width != Infinity ? max(this.width, width) : this.width,
                height: height != Infinity ? max(this.height, height) : this.height,
            });
        }
        expand_to({ width, height }) {
            this.width = max(this.width, width);
            this.height = max(this.height, height);
        }
        narrowed_to({ width, height }) {
            return new Sizeable({
                width: min(this.width, width),
                height: min(this.height, height),
            });
        }
        narrow_to({ width, height }) {
            this.width = min(this.width, width);
            this.height = min(this.height, height);
        }
        grow_by({ left, right, top, bottom }) {
            const width = this.width + left + right;
            const height = this.height + top + bottom;
            return new Sizeable({ width, height });
        }
        shrink_by({ left, right, top, bottom }) {
            const width = max(this.width - left - right, 0);
            const height = max(this.height - top - bottom, 0);
            return new Sizeable({ width, height });
        }
        map(w_fn, h_fn) {
            return new Sizeable({
                width: w_fn(this.width),
                height: (h_fn != null ? h_fn : w_fn)(this.height),
            });
        }
    }
    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();
    const types_1 = require(147) /* ./types */;
    const bbox_1 = require(57) /* ../util/bbox */;
    const types_2 = require(8) /* ../util/types */;
    const assert_1 = require(12) /* ../util/assert */;
    const { abs, min, max, round } = Math;
    class Layoutable {
        constructor() {
            this.absolute = false;
            this.position = { left: 0, top: 0 };
            this._bbox = new bbox_1.BBox();
            this._inner_bbox = new bbox_1.BBox();
            this._sizing = null;
            this._dirty = false;
            this._handlers = [];
        }
        *[Symbol.iterator]() { }
        get bbox() {
            return this._bbox;
        }
        get inner_bbox() {
            return this._inner_bbox;
        }
        get sizing() {
            (0, assert_1.assert)(this._sizing != null);
            return this._sizing;
        }
        set dirty(dirty) {
            this._dirty = dirty;
        }
        get dirty() {
            return this._dirty;
        }
        get visible() {
            return this.sizing.visible;
        }
        set visible(visible) {
            if (this.sizing.visible != visible) {
                this.sizing.visible = visible;
                this._dirty = true;
            }
        }
        set_sizing(sizing = {}) {
            var _a, _b, _c, _d, _e, _f;
            const width_policy = (_a = sizing.width_policy) !== null && _a !== void 0 ? _a : "fit";
            const width = sizing.width;
            const min_width = sizing.min_width;
            const max_width = sizing.max_width;
            const height_policy = (_b = sizing.height_policy) !== null && _b !== void 0 ? _b : "fit";
            const height = sizing.height;
            const min_height = sizing.min_height;
            const max_height = sizing.max_height;
            const aspect = sizing.aspect;
            const margin = (_c = sizing.margin) !== null && _c !== void 0 ? _c : { top: 0, right: 0, bottom: 0, left: 0 };
            const visible = (_d = sizing.visible) !== null && _d !== void 0 ? _d : true;
            const halign = (_e = sizing.halign) !== null && _e !== void 0 ? _e : "start";
            const valign = (_f = sizing.valign) !== null && _f !== void 0 ? _f : "start";
            this._sizing = {
                width_policy, min_width, width, max_width,
                height_policy, min_height, height, max_height,
                aspect,
                margin,
                visible,
                halign,
                valign,
                size: { width, height },
            };
            this._init();
        }
        _init() { }
        _set_geometry(outer, inner) {
            this._bbox = outer;
            this._inner_bbox = inner;
        }
        set_geometry(outer, inner) {
            const { fixup_geometry } = this;
            if (fixup_geometry != null) {
                [outer, inner] = fixup_geometry(outer, inner);
            }
            this._set_geometry(outer, inner !== null && inner !== void 0 ? inner : outer);
            for (const handler of this._handlers) {
                handler(this._bbox, this._inner_bbox);
            }
        }
        on_resize(handler) {
            this._handlers.push(handler);
        }
        is_width_expanding() {
            return this.sizing.width_policy == "max";
        }
        is_height_expanding() {
            return this.sizing.height_policy == "max";
        }
        apply_aspect(viewport, { width, height }) {
            const { aspect } = this.sizing;
            if (aspect != null) {
                const { width_policy, height_policy } = this.sizing;
                const gt = (width, height) => {
                    const 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) {
                        const w_width = width;
                        const w_height = round(width / aspect);
                        const h_width = round(height * aspect);
                        const h_height = height;
                        const w_diff = abs(viewport.width - w_width) + abs(viewport.height - w_height);
                        const h_diff = abs(viewport.width - h_width) + 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, height };
        }
        measure(viewport_size) {
            if (this._sizing == null) {
                this.set_sizing();
            }
            if (!this.sizing.visible)
                return { width: 0, height: 0 };
            const exact_width = (width) => {
                return this.sizing.width_policy == "fixed" && this.sizing.width != null ? this.sizing.width : width;
            };
            const exact_height = (height) => {
                return this.sizing.height_policy == "fixed" && this.sizing.height != null ? this.sizing.height : height;
            };
            const viewport = new types_1.Sizeable(viewport_size)
                .shrink_by(this.sizing.margin)
                .map(exact_width, exact_height);
            const computed = this._measure(viewport);
            const clipped = this.clip_size(computed, viewport);
            const width = exact_width(clipped.width);
            const height = exact_height(clipped.height);
            const size = this.apply_aspect(viewport, { width, height });
            return Object.assign(Object.assign({}, computed), size);
        }
        compute(viewport = {}) {
            const 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,
            });
            const { width, height } = size_hint;
            const { left, top } = this.position;
            const outer = new bbox_1.BBox({ left, top, width, height });
            let inner = undefined;
            if (size_hint.inner != null) {
                const { left, top, right, bottom } = size_hint.inner;
                inner = new bbox_1.BBox({ left, top, right: width - right, bottom: height - bottom });
            }
            this.set_geometry(outer, inner);
        }
        get xview() {
            return this.bbox.xview;
        }
        get yview() {
            return this.bbox.yview;
        }
        clip_size(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 = round(min_size.percent * vsize);
                if (max_size == null)
                    max_size = Infinity;
                else if (!(0, types_2.isNumber)(max_size))
                    max_size = 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),
            };
        }
        has_size_changed() {
            const { _dirty } = this;
            this._dirty = false;
            return _dirty;
        }
    }
    exports.Layoutable = Layoutable;
    Layoutable.__name__ = "Layoutable";
    class ContentLayoutable extends Layoutable {
        _measure(viewport) {
            const content_size = this._content_size();
            const bounds = viewport
                .bounded_to(this.sizing.size)
                .bounded_to(content_size);
            const width = (() => {
                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 max(content_size.width, bounds.width);
                }
            })();
            const height = (() => {
                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 max(content_size.height, bounds.height);
                }
            })();
            return { width, height };
        }
    }
    exports.ContentLayoutable = ContentLayoutable;
    ContentLayoutable.__name__ = "ContentLayoutable";
    class TextLayout extends ContentLayoutable {
        constructor(text) {
            super();
            this.text = text;
        }
        _content_size() {
            return new types_1.Sizeable(this.text.size());
        }
    }
    exports.TextLayout = TextLayout;
    TextLayout.__name__ = "TextLayout";
    class FixedLayout extends ContentLayoutable {
        constructor(size = {}) {
            super();
            this.size = size;
        }
        _content_size() {
            return new types_1.Sizeable(this.size);
        }
    }
    exports.FixedLayout = FixedLayout;
    FixedLayout.__name__ = "FixedLayout";
},
/* models/text/base_text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const view_1 = require(54) /* ../../core/view */;
    class BaseTextView extends view_1.View {
    }
    exports.BaseTextView = BaseTextView;
    BaseTextView.__name__ = "BaseTextView";
    class BaseText extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BaseText = BaseText;
    _a = BaseText;
    BaseText.__name__ = "BaseText";
    (() => {
        _a.define(({ String }) => ({
            text: [String],
        }));
    })();
},
/* models/text/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const math_text_1 = require(151) /* ./math_text */;
    const plain_text_1 = require(158) /* ./plain_text */;
    const array_1 = require(10) /* ../../core/util/array */;
    const delimiters = [
        { start: "$$", end: "$$", inline: false },
        { start: "\\\[", end: "\\\]", inline: false },
        { start: "\\\(", end: "\\\)", inline: true },
    ];
    function add_backslash(m) {
        return m.split("").map(s => `\\${s}`).join("");
    }
    function parse_delimited_string(text) {
        const matches = [];
        for (const delim of delimiters) {
            const start = add_backslash(delim.start);
            const end = add_backslash(delim.end);
            const re = new RegExp(`${start}([^]*?)${end}`, "gm");
            for (const match of text.matchAll(re)) {
                const { index } = match;
                if (index != null) {
                    const [outer, inner] = match;
                    matches.push({ index, outer, inner, delim });
                }
            }
        }
        if (matches.length > 0) {
            if (matches.length == 1) {
                const [match] = matches;
                const start = match.index;
                const end = match.outer.length;
                if (start == 0 && end == text.length) {
                    const tex_string = match.inner;
                    return new math_text_1.TeX({ text: tex_string, inline: match.delim.inline });
                }
            }
            let tex_string = "";
            let end = 0;
            for (const match of (0, array_1.sort_by)(matches, (match) => match.index)) {
                const start = match.index;
                if (end <= start) {
                    tex_string += start != 0 ? `\\text{${text.slice(end, start)}}${match.inner}` : `${match.inner}`;
                    end = start + match.outer.length;
                }
            }
            tex_string += end < text.length ? `\\text{${text.slice(end)}}` : "";
            return new math_text_1.TeX({ text: tex_string, inline: false });
        }
        else {
            return new plain_text_1.PlainText({ text });
        }
    }
    exports.parse_delimited_string = parse_delimited_string;
},
/* models/text/math_text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c;
    __esModule();
    const types_1 = require(8) /* ../../core/util/types */;
    const image_1 = require(152) /* ../../core/util/image */;
    const color_1 = require(22) /* ../../core/util/color */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    const text_1 = require(154) /* ../../core/util/text */;
    const string_1 = require(40) /* ../../core/util/string */;
    const affine_1 = require(155) /* ../../core/util/affine */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const base_text_1 = require(149) /* ./base_text */;
    const providers_1 = require(156) /* ./providers */;
    /**
     * Helper class for rendering MathText into Canvas
     */
    class MathTextView extends base_text_1.BaseTextView {
        constructor() {
            super(...arguments);
            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 :host's font-size (13px)
            this.font_size_scale = 1.0;
            this.svg_image = null;
        }
        graphics() {
            return this;
        }
        // Same for infer_text_height
        infer_text_height() {
            return "ascent_descent";
        }
        set base_font_size(v) {
            if (v != null)
                this._base_font_size = v;
        }
        get base_font_size() {
            return this._base_font_size;
        }
        _rect() {
            const { width, height } = this._size();
            const { x, y } = this._computed_position();
            const bbox = new bbox_1.BBox({ x, y, width, height });
            return bbox.rect;
        }
        set position(p) {
            this._position = p;
        }
        get position() {
            return this._position;
        }
        get text() {
            return this.model.text;
        }
        get provider() {
            return providers_1.default_provider;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            if (this.provider.status == "not_started")
                await this.provider.fetch();
        }
        connect_signals() {
            super.connect_signals();
            this.on_change(this.model.properties.text, () => this.load_image());
        }
        set visuals(v) {
            const color = v.color;
            const alpha = v.alpha;
            const style = v.font_style;
            let size = v.font_size;
            const face = v.font;
            const { font_size_scale, _base_font_size } = this;
            const res = (0, text_1.parse_css_font_size)(size);
            if (res != null) {
                let { value, unit } = res;
                value *= font_size_scale;
                if (unit == "em" && _base_font_size != 0) {
                    value *= _base_font_size;
                    unit = "px";
                }
                size = `${value}${unit}`;
            }
            const font = `${style} ${size} ${face}`;
            this.font = font;
            this.color = (0, color_1.color2css)(color, alpha);
            const align = v.align;
            //this._visual_align = align
            this._x_anchor = align;
            const baseline = v.baseline;
            this._y_anchor = (() => {
                switch (baseline) {
                    case "top": return "top";
                    case "middle": return "center";
                    case "bottom": return "bottom";
                    default: return "baseline";
                }
            })();
        }
        /**
         * Calculates position of element after considering
         * anchor and dimensions
         */
        _computed_position() {
            const { width, height } = this._size();
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const metrics = (0, text_1.font_metrics)(this.font);
            const x = sx - (() => {
                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;
                    }
                }
            })();
            const y = sy - (() => {
                if ((0, types_1.isNumber)(y_anchor))
                    return y_anchor * height;
                else {
                    switch (y_anchor) {
                        case "top":
                            if (metrics.height > height)
                                return (height - (-this.valign - metrics.descent) - metrics.height);
                            else
                                return 0;
                        case "center": return 0.5 * height;
                        case "bottom":
                            if (metrics.height > height)
                                return (height + metrics.descent + this.valign);
                            else
                                return height;
                        case "baseline": return 0.5 * height;
                    }
                }
            })();
            return { x, y };
        }
        /**
         * Uses the width, height and given angle to calculate the size
        */
        size() {
            const { width, height } = this._size();
            const { angle } = this;
            if (angle == null || angle == 0)
                return { width, height };
            else {
                const c = Math.cos(Math.abs(angle));
                const s = Math.sin(Math.abs(angle));
                return {
                    width: Math.abs(width * c + height * s),
                    height: Math.abs(width * s + height * c),
                };
            }
        }
        get_image_dimensions() {
            var _d;
            const fmetrics = (0, text_1.font_metrics)(this.font);
            // XXX: perhaps use getComputedStyle()?
            const svg_styles = (_d = this.svg_element.getAttribute("style")) === null || _d === void 0 ? void 0 : _d.split(";");
            if (svg_styles != null) {
                const rules_map = new Map();
                svg_styles.forEach(property => {
                    const [rule, value] = property.split(":");
                    if (rule.trim() != "") {
                        rules_map.set(rule.trim(), value.trim());
                    }
                });
                const v_align = (0, text_1.parse_css_length)(rules_map.get("vertical-align"));
                if ((v_align === null || v_align === void 0 ? void 0 : v_align.unit) == "ex") {
                    this.valign = v_align.value * fmetrics.x_height;
                }
                else if ((v_align === null || v_align === void 0 ? void 0 : v_align.unit) == "px") {
                    this.valign = v_align.value;
                }
            }
            const ex = (() => {
                const width = this.svg_element.getAttribute("width");
                const height = this.svg_element.getAttribute("height");
                return {
                    width: width != null && width.endsWith("ex") ? parseFloat(width) : 1,
                    height: height != null && height.endsWith("ex") ? parseFloat(height) : 1,
                };
            })();
            return {
                width: fmetrics.x_height * ex.width,
                height: fmetrics.x_height * ex.height,
            };
        }
        get truncated_text() {
            return this.model.text.length > 6
                ? `${this.model.text.substring(0, 6)}...`
                : this.model.text;
        }
        _size() {
            var _d, _e;
            if (this.svg_image == null) {
                if (this.provider.status == "failed" || this.provider.status == "not_started") {
                    return {
                        width: (0, graphics_1.text_width)(this.truncated_text, this.font),
                        height: (0, text_1.font_metrics)(this.font).height,
                    };
                }
                else {
                    return { width: this._base_font_size, height: this._base_font_size };
                }
            }
            const fmetrics = (0, text_1.font_metrics)(this.font);
            let { width, height } = this.get_image_dimensions();
            height = Math.max(height, fmetrics.height);
            const w_scale = ((_d = this.width) === null || _d === void 0 ? void 0 : _d.unit) == "%" ? this.width.value : 1;
            const h_scale = ((_e = this.height) === null || _e === void 0 ? void 0 : _e.unit) == "%" ? this.height.value : 1;
            return { width: width * w_scale, height: height * h_scale };
        }
        bbox() {
            const { p0, p1, p2, p3 } = this.rect();
            const left = Math.min(p0.x, p1.x, p2.x, p3.x);
            const top = Math.min(p0.y, p1.y, p2.y, p3.y);
            const right = Math.max(p0.x, p1.x, p2.x, p3.x);
            const bottom = Math.max(p0.y, p1.y, p2.y, p3.y);
            return new bbox_1.BBox({ left, right, top, bottom });
        }
        rect() {
            const rect = this._rect();
            const { angle } = this;
            if (angle == null || angle == 0)
                return rect;
            else {
                const { sx, sy } = this.position;
                const tr = new affine_1.AffineTransform();
                tr.translate(sx, sy);
                tr.rotate(angle);
                tr.translate(-sx, -sy);
                return tr.apply_rect(rect);
            }
        }
        paint_rect(ctx) {
            const { p0, p1, p2, p3 } = this.rect();
            ctx.save();
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            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();
        }
        paint_bbox(ctx) {
            const { x, y, width, height } = this.bbox();
            ctx.save();
            ctx.strokeStyle = "blue";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            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();
        }
        async load_image() {
            if (this.provider.MathJax == null)
                return null;
            const mathjax_element = this._process_text();
            if (mathjax_element == null) {
                this._has_finished = true;
                return null;
            }
            const svg_element = mathjax_element.children[0];
            this.svg_element = svg_element;
            svg_element.setAttribute("font", this.font);
            svg_element.setAttribute("stroke", this.color);
            const svg = svg_element.outerHTML;
            const src = `data:image/svg+xml;utf-8,${encodeURIComponent(svg)}`;
            this.svg_image = await (0, image_1.load_image)(src);
            this.parent.request_layout();
            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.
        */
        paint(ctx) {
            if (this.svg_image == null) {
                if (this.provider.status == "not_started" || this.provider.status == "loading")
                    this.provider.ready.connect(() => this.load_image());
                if (this.provider.status == "loaded")
                    this.load_image();
            }
            ctx.save();
            const { sx, sy } = this.position;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            if (this.svg_image != null) {
                const { width, height } = this.get_image_dimensions();
                ctx.drawImage(this.svg_image, x, y, width, height);
            }
            else if (this.provider.status == "failed" || this.provider.status == "not_started") {
                ctx.fillStyle = this.color;
                ctx.font = this.font;
                ctx.textAlign = "left";
                ctx.textBaseline = "alphabetic";
                ctx.fillText(this.truncated_text, x, y + (0, text_1.font_metrics)(this.font).ascent);
            }
            ctx.restore();
            if (!this._has_finished && (this.provider.status == "failed" || this.svg_image != null)) {
                this._has_finished = true;
                this.parent.notify_finished_after_paint();
            }
        }
    }
    exports.MathTextView = MathTextView;
    MathTextView.__name__ = "MathTextView";
    class MathText extends base_text_1.BaseText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MathText = MathText;
    MathText.__name__ = "MathText";
    class AsciiView extends MathTextView {
        // TODO: Color ascii
        get styled_text() {
            return this.text;
        }
        _process_text() {
            return undefined; // TODO: this.provider.MathJax?.ascii2svg(text)
        }
        _size() {
            return {
                width: (0, graphics_1.text_width)(this.text, this.font),
                height: (0, text_1.font_metrics)(this.font).height,
            };
        }
        paint(ctx) {
            ctx.save();
            const { sx, sy } = this.position;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            ctx.fillStyle = this.color;
            ctx.font = this.font;
            ctx.textAlign = "left";
            ctx.textBaseline = "alphabetic";
            ctx.fillText(this.text, x, y + (0, text_1.font_metrics)(this.font).ascent);
            ctx.restore();
            this._has_finished = true;
            this.parent.notify_finished_after_paint();
        }
    }
    exports.AsciiView = AsciiView;
    AsciiView.__name__ = "AsciiView";
    class Ascii extends MathText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ascii = Ascii;
    _a = Ascii;
    Ascii.__name__ = "Ascii";
    (() => {
        _a.prototype.default_view = AsciiView;
    })();
    class MathMLView extends MathTextView {
        get styled_text() {
            let styled = this.text.trim();
            let matchs = styled.match(/<math(.*?[^?])?>/s);
            if (matchs == null)
                return this.text.trim();
            styled = (0, string_1.insert_text_on_position)(styled, styled.indexOf(matchs[0]) + matchs[0].length, `<mstyle displaystyle="true" mathcolor="${(0, color_1.color2hexrgb)(this.color)}" ${this.font.includes("bold") ? 'mathvariant="bold"' : ""}>`);
            matchs = styled.match(/<\/[^>]*?math.*?>/s);
            if (matchs == null)
                return this.text.trim();
            return (0, string_1.insert_text_on_position)(styled, styled.indexOf(matchs[0]), "</mstyle>");
        }
        _process_text() {
            var _d;
            const fmetrics = (0, text_1.font_metrics)(this.font);
            return (_d = this.provider.MathJax) === null || _d === void 0 ? void 0 : _d.mathml2svg(this.styled_text, {
                em: this.base_font_size,
                ex: fmetrics.x_height,
            });
        }
    }
    exports.MathMLView = MathMLView;
    MathMLView.__name__ = "MathMLView";
    class MathML extends MathText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MathML = MathML;
    _b = MathML;
    MathML.__name__ = "MathML";
    (() => {
        _b.prototype.default_view = MathMLView;
    })();
    class TeXView extends MathTextView {
        get styled_text() {
            const [r, g, b] = (0, color_1.color2rgba)(this.color);
            return `\\color[RGB]{${r}, ${g}, ${b}} ${this.font.includes("bold") ? `\\pmb{${this.text}}` : this.text}`;
        }
        _process_text() {
            var _d;
            // TODO: allow plot/document level configuration of macros
            const fmetrics = (0, text_1.font_metrics)(this.font);
            return (_d = this.provider.MathJax) === null || _d === void 0 ? void 0 : _d.tex2svg(this.styled_text, {
                display: !this.model.inline,
                em: this.base_font_size,
                ex: fmetrics.x_height,
            }, this.model.macros);
        }
    }
    exports.TeXView = TeXView;
    TeXView.__name__ = "TeXView";
    class TeX extends MathText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TeX = TeX;
    _c = TeX;
    TeX.__name__ = "TeX";
    (() => {
        _c.prototype.default_view = TeXView;
        _c.define(({ Boolean, Number, String, Dict, Tuple, Or }) => ({
            macros: [Dict(Or(String, Tuple(String, Number))), {}],
            inline: [Boolean, false],
        }));
    })();
},
/* core/util/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const logging_1 = require(19) /* ../logging */;
    async function load_image(url, options) {
        return new ImageLoader(url, options).promise;
    }
    exports.load_image = load_image;
    class ImageLoader {
        constructor(src, config = {}) {
            this.image = new Image();
            this._finished = false;
            const { attempts = 1, timeout = 1 } = config;
            const url = (() => {
                if (src instanceof ArrayBuffer) {
                    const blob = new Blob([src], { type: "image/png" }); // TODO mime
                    return URL.createObjectURL(blob); // TODO revoke
                }
                else {
                    return src;
                }
            })();
            this.promise = new Promise((resolve, _reject) => {
                this.image.crossOrigin = "anonymous";
                let retries = 0;
                this.image.onerror = () => {
                    if (++retries == attempts) {
                        const 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(() => this.image.src = url, timeout);
                };
                this.image.onload = () => {
                    this._finished = true;
                    if (config.loaded != null)
                        config.loaded(this.image);
                    resolve(this.image);
                };
                this.image.src = url;
            });
        }
        get finished() {
            return this._finished;
        }
    }
    exports.ImageLoader = ImageLoader;
    ImageLoader.__name__ = "ImageLoader";
},
/* core/graphics.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const bbox_1 = require(57) /* ./util/bbox */;
    const text_1 = require(154) /* ./util/text */;
    const array_1 = require(10) /* ./util/array */;
    const types_1 = require(8) /* ./util/types */;
    const affine_1 = require(155) /* ./util/affine */;
    const color_1 = require(22) /* ./util/color */;
    exports.text_width = (() => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        let current_font = "";
        return (text, font) => {
            if (font != current_font) {
                current_font = font;
                ctx.font = font;
            }
            return ctx.measureText(text).width;
        };
    })();
    class GraphicsBox {
        constructor() {
            this._position = { sx: 0, sy: 0 };
            this.font_size_scale = 1.0;
            this.align = "left";
            this._base_font_size = 13; // the same as :host's font-size (13px)
            this._x_anchor = "left";
            this._y_anchor = "center";
        }
        set base_font_size(v) {
            if (v != null)
                this._base_font_size = v;
        }
        get base_font_size() {
            return this._base_font_size;
        }
        set position(p) {
            this._position = p;
        }
        get position() {
            return this._position;
        }
        infer_text_height() {
            return "ascent_descent";
        }
        bbox() {
            const { p0, p1, p2, p3 } = this.rect();
            const left = Math.min(p0.x, p1.x, p2.x, p3.x);
            const top = Math.min(p0.y, p1.y, p2.y, p3.y);
            const right = Math.max(p0.x, p1.x, p2.x, p3.x);
            const bottom = Math.max(p0.y, p1.y, p2.y, p3.y);
            return new bbox_1.BBox({ left, right, top, bottom });
        }
        size() {
            const { width, height } = this._size();
            const { angle } = this;
            if (angle == null || angle == 0)
                return { width, height };
            else {
                const c = Math.cos(Math.abs(angle));
                const s = Math.sin(Math.abs(angle));
                return {
                    width: Math.abs(width * c + height * s),
                    height: Math.abs(width * s + height * c),
                };
            }
        }
        rect() {
            const rect = this._rect();
            const { angle } = this;
            if (angle == null || angle == 0)
                return rect;
            else {
                const { sx, sy } = this.position;
                const tr = new affine_1.AffineTransform();
                tr.translate(sx, sy);
                tr.rotate(angle);
                tr.translate(-sx, -sy);
                return tr.apply_rect(rect);
            }
        }
        paint_rect(ctx) {
            const { p0, p1, p2, p3 } = this.rect();
            ctx.save();
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            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();
        }
        paint_bbox(ctx) {
            const { x, y, width, height } = this.bbox();
            ctx.save();
            ctx.strokeStyle = "blue";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            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();
        }
    }
    exports.GraphicsBox = GraphicsBox;
    GraphicsBox.__name__ = "GraphicsBox";
    class TextBox extends GraphicsBox {
        set visuals(v) {
            const color = v.color;
            const alpha = v.alpha;
            const outline_color = v.outline_color;
            const style = v.font_style;
            let size = v.font_size;
            const face = v.font;
            const { font_size_scale, base_font_size } = this;
            const res = (0, text_1.parse_css_font_size)(size);
            if (res != null) {
                let { value, unit } = res;
                value *= font_size_scale;
                if (unit == "em" && base_font_size != 0) {
                    value *= base_font_size;
                    unit = "px";
                }
                size = `${value}${unit}`;
            }
            const font = `${style} ${size} ${face}`;
            this.font = font;
            this.color = (0, color_1.color2css)(color, alpha);
            this.outline_color = (0, color_1.color2css)(outline_color, alpha);
            this.line_height = v.line_height;
            const align = v.align;
            this._visual_align = align;
            this._x_anchor = align;
            const baseline = v.baseline;
            this._y_anchor = (() => {
                switch (baseline) {
                    case "top": return "top";
                    case "middle": return "center";
                    case "bottom": return "bottom";
                    default: return "baseline";
                }
            })();
        }
        constructor({ text }) {
            super();
            //padding: Padding
            this._visual_align = "left";
            this.text = text;
        }
        infer_text_height() {
            if (this.text.includes("\n"))
                return "ascent_descent";
            else {
                function is_math_like(text) {
                    for (const c of new Set(text)) {
                        if ("0" <= c && c <= "9")
                            continue;
                        switch (c) {
                            case ",":
                            case ".":
                            case "+":
                            case "-":
                            case "\u2212":
                            case "e":
                                continue;
                            default:
                                return false;
                        }
                    }
                    return true;
                }
                if (is_math_like(this.text))
                    return "cap";
                else
                    return "ascent_descent";
            }
        }
        _text_line(fmetrics) {
            var _a;
            const metric = (_a = this.text_height_metric) !== null && _a !== void 0 ? _a : this.infer_text_height();
            const ascent = (() => {
                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;
                }
            })();
            const descent = (() => {
                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, descent };
        }
        get nlines() {
            const lines = this.text.split("\n");
            return lines.length;
        }
        _size() {
            var _a, _b;
            const { font } = this;
            const fmetrics = (0, text_1.font_metrics)(font);
            const line_spacing = (this.line_height - 1) * fmetrics.height; // TODO: max(trailing(L[n-1]), leading(L[n]))
            const empty = this.text == "";
            const lines = this.text.split("\n");
            const nlines = lines.length;
            const widths = lines.map((line) => (0, exports.text_width)(line, font));
            const text_line = this._text_line(fmetrics);
            const 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)
            */
            const w_scale = ((_a = this.width) === null || _a === void 0 ? void 0 : _a.unit) == "%" ? this.width.value : 1;
            const h_scale = ((_b = this.height) === null || _b === void 0 ? void 0 : _b.unit) == "%" ? this.height.value : 1;
            const width = (0, array_1.max)(widths) * w_scale;
            const height = empty ? 0 : (text_height + line_spacing * (nlines - 1)) * h_scale;
            return { width, height, metrics: fmetrics };
        }
        _computed_position(size, metrics, nlines) {
            const { width, height } = size;
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const x = sx - (() => {
                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;
                    }
                }
            })();
            const y = sy - (() => {
                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) {
                                const 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, y };
        }
        _rect() {
            const { width, height, metrics } = this._size();
            const nlines = this.text.split("\n").length;
            const { x, y } = this._computed_position({ width, height }, metrics, nlines);
            const bbox = new bbox_1.BBox({ x, y, width, height });
            return bbox.rect;
        }
        paint(ctx) {
            var _a, _b;
            const { font } = this;
            const fmetrics = (0, text_1.font_metrics)(font);
            const line_spacing = (this.line_height - 1) * fmetrics.height; // TODO: see above
            const lines = this.text.split("\n");
            const nlines = lines.length;
            const widths = lines.map((line) => (0, exports.text_width)(line, font));
            const text_line = this._text_line(fmetrics);
            const 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 w_scale = ((_a = this.width) === null || _a === void 0 ? void 0 : _a.unit) == "%" ? this.width.value : 1;
            const h_scale = ((_b = this.height) === null || _b === void 0 ? void 0 : _b.unit) == "%" ? this.height.value : 1;
            const width = (0, array_1.max)(widths) * w_scale;
            const height = (text_height + line_spacing * (nlines - 1)) * h_scale;
            ctx.save();
            ctx.fillStyle = this.color;
            ctx.strokeStyle = this.outline_color;
            ctx.font = this.font;
            ctx.textAlign = "left";
            ctx.textBaseline = "alphabetic";
            const { sx, sy } = this.position;
            const { align } = this;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            let { x, y } = this._computed_position({ width, height }, fmetrics, nlines);
            if (align == "justify") {
                for (let i = 0; i < nlines; i++) {
                    let xij = x;
                    const line = lines[i];
                    const words = line.split(" ");
                    const nwords = words.length;
                    const word_widths = words.map((word) => (0, exports.text_width)(word, font));
                    const word_spacing = (width - (0, array_1.sum)(word_widths)) / (nwords - 1);
                    for (let j = 0; j < nwords; j++) {
                        ctx.fillText(words[j], xij, y);
                        ctx.strokeText(words[j], xij, y);
                        xij += word_widths[j] + word_spacing;
                    }
                    y += /*heights[i]*/ text_line.height + line_spacing;
                }
            }
            else {
                for (let i = 0; i < nlines; i++) {
                    const xi = x + (() => {
                        switch (align == "auto" ? this._visual_align : align) {
                            case "left": return 0;
                            case "center": return 0.5 * (width - widths[i]);
                            case "right": return width - widths[i];
                        }
                    })();
                    const linei = lines[i];
                    const yi = y + /*ascents[i]*/ text_line.ascent;
                    ctx.fillText(linei, xi, yi);
                    ctx.strokeText(linei, xi, yi);
                    y += /*heights[i]*/ text_line.height + line_spacing;
                }
            }
            ctx.restore();
        }
    }
    exports.TextBox = TextBox;
    TextBox.__name__ = "TextBox";
    class BaseExpo extends GraphicsBox {
        constructor(base, expo) {
            super();
            this.base = base;
            this.expo = expo;
        }
        get children() {
            return [this.base, this.expo];
        }
        set base_font_size(v) {
            super.base_font_size = v;
            this.base.base_font_size = v;
            this.expo.base_font_size = v;
        }
        set position(p) {
            this._position = p;
            const bs = this.base.size();
            const es = this.expo.size();
            const shift = this._shift_scale() * bs.height;
            const 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",
            };
        }
        get position() {
            return this._position;
        }
        set visuals(v) {
            this.expo.font_size_scale = 0.7;
            this.base.visuals = v;
            this.expo.visuals = v;
        }
        _shift_scale() {
            if (this.base instanceof TextBox && this.base.nlines == 1) {
                const { x_height, cap_height } = (0, text_1.font_metrics)(this.base.font);
                return x_height / cap_height;
            }
            else {
                return 2 / 3;
            }
        }
        infer_text_height() {
            return this.base.infer_text_height();
        }
        _rect() {
            const bb = this.base.bbox();
            const eb = this.expo.bbox();
            const bbox = bb.union(eb);
            const { x, y } = this._computed_position();
            return bbox.translate(x, y).rect;
        }
        _size() {
            const bs = this.base.size();
            const es = this.expo.size();
            return {
                width: bs.width + es.width,
                height: Math.max(bs.height, this._shift_scale() * bs.height + es.height),
            };
        }
        paint(ctx) {
            ctx.save();
            const { angle } = this;
            if (angle != null && angle != 0) {
                const { sx, sy } = this.position;
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            ctx.translate(x, y);
            this.base.paint(ctx);
            this.expo.paint(ctx);
            ctx.restore();
        }
        // paint_rect ...
        paint_bbox(ctx) {
            super.paint_bbox(ctx);
            const { x, y } = this._computed_position();
            ctx.save();
            ctx.translate(x, y);
            for (const child of this.children) {
                child.paint_bbox(ctx);
            }
            ctx.restore();
        }
        _computed_position() {
            const { width, height } = this._size();
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const x = sx - (() => {
                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;
                    }
                }
            })();
            const y = sy - (() => {
                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, y };
        }
    }
    exports.BaseExpo = BaseExpo;
    BaseExpo.__name__ = "BaseExpo";
    class GraphicsBoxes {
        constructor(items) {
            this.items = items;
        }
        set base_font_size(v) {
            for (const item of this.items) {
                item.base_font_size = v;
            }
        }
        get length() {
            return this.items.length;
        }
        set visuals(v) {
            for (const item of this.items) {
                item.visuals = v;
            }
            const metric_map = { x: 0, cap: 1, ascent: 2, x_descent: 3, cap_descent: 4, ascent_descent: 5 };
            const common = (0, array_1.max_by)(this.items.map((item) => item.infer_text_height()), (metric) => metric_map[metric]);
            for (const item of this.items) {
                item.text_height_metric = common;
            }
        }
        set angle(a) {
            for (const item of this.items) {
                item.angle = a;
            }
        }
        max_size() {
            let width = 0;
            let height = 0;
            for (const item of this.items) {
                const size = item.size();
                width = Math.max(width, size.width);
                height = Math.max(height, size.height);
            }
            return { width, height };
        }
    }
    exports.GraphicsBoxes = GraphicsBoxes;
    GraphicsBoxes.__name__ = "GraphicsBoxes";
},
/* core/util/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const assert_1 = require(12) /* ./assert */;
    const types_1 = require(8) /* ./types */;
    const has_OffscreenCanvas = (() => {
        try {
            return typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(0, 0).getContext("2d") != null;
        }
        catch (_a) {
            return false;
        }
    })();
    const _offscreen_canvas = (() => {
        if (has_OffscreenCanvas)
            return (w, h) => new OffscreenCanvas(w, h);
        else {
            return (w, h) => {
                const canvas = document.createElement("canvas");
                canvas.width = w;
                canvas.height = h;
                return canvas;
            };
        }
    })();
    const _native_font_metrics = (() => {
        const canvas = _offscreen_canvas(0, 0);
        // XXX: explicit type required due to insuffient quality of stdlib's type declarations
        const ctx = canvas.getContext("2d");
        (0, assert_1.assert)(ctx != null, "can't obtain 2d context");
        return (font) => {
            ctx.font = font;
            const cap_metrics = ctx.measureText("M");
            const x_metrics = ctx.measureText("x");
            const metrics = ctx.measureText("ÅŚg|");
            const font_ascent = metrics.fontBoundingBoxAscent;
            const font_descent = metrics.fontBoundingBoxDescent;
            if ((0, types_1.is_defined)(font_ascent) && (0, types_1.is_defined)(font_descent)) {
                return {
                    height: font_ascent + font_descent,
                    ascent: font_ascent,
                    descent: font_descent,
                    cap_height: cap_metrics.actualBoundingBoxAscent,
                    x_height: x_metrics.actualBoundingBoxAscent,
                };
            }
            const text_ascent = metrics.actualBoundingBoxAscent;
            const text_descent = metrics.actualBoundingBoxDescent;
            if ((0, types_1.is_defined)(text_ascent) && (0, types_1.is_defined)(text_descent)) {
                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)();
        };
    })();
    const _internal_font_metrics = (() => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        let cwidth = -1;
        let cheight = -1;
        return (font, scale = 1) => {
            ctx.font = font;
            const { width: _em } = ctx.measureText("M");
            const em = _em * scale;
            const width = Math.ceil(em);
            const height = Math.ceil(2.0 * em);
            const 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);
            const measure_ascent = (data) => {
                let k = 0;
                for (let i = 0; i <= baseline; i++) {
                    for (let j = 0; j < width; j++, k += 4)
                        if (data[k] != 255)
                            return baseline - i;
                }
                return 0;
            };
            const measure_descent = (data) => {
                let k = data.length - 4;
                for (let i = height; i >= baseline; i--) {
                    for (let j = 0; j < width; j++, k -= 4)
                        if (data[k] != 255)
                            return i - baseline;
                }
                return 0;
            };
            ctx.font = font;
            ctx.fillStyle = "#000";
            for (const c of "xa") {
                ctx.fillText(c, 0, baseline / scale);
            }
            const { data: data0 } = ctx.getImageData(0, 0, width, height);
            const x_height = measure_ascent(data0) / scale;
            for (const c of "ASQ") {
                ctx.fillText(c, 0, baseline / scale);
            }
            const { data: data1 } = ctx.getImageData(0, 0, width, height);
            const cap_height = measure_ascent(data1) / scale;
            for (const c of "ÅŚgy") {
                ctx.fillText(c, 0, baseline / scale);
            }
            const { data: data2 } = ctx.getImageData(0, 0, width, height);
            const ascent = measure_ascent(data2) / scale;
            const descent = measure_descent(data2) / scale;
            ctx.restore();
            return { height: ascent + descent, ascent, cap_height, x_height, descent };
        };
    })();
    const _font_metrics = (() => {
        try {
            _native_font_metrics("normal 10px sans-serif");
            return _native_font_metrics;
        }
        catch (_a) {
            return _internal_font_metrics;
        }
    })();
    const _metrics_cache = new Map();
    function font_metrics(font) {
        let metrics = _metrics_cache.get(font);
        if (metrics == null) {
            const loaded = document.fonts.check(font);
            metrics = { font: _font_metrics(font) };
            if (loaded) {
                _metrics_cache.set(font, metrics);
            }
        }
        return metrics.font;
    }
    exports.font_metrics = font_metrics;
    function parse_css_font_size(size) {
        const match = size.match(/^\s*(\d+(\.\d+)?)(\w+)\s*$/);
        if (match != null) {
            const [, value, , unit] = match;
            const number = Number(value);
            if (isFinite(number))
                return { value: number, unit };
        }
        return null;
    }
    exports.parse_css_font_size = parse_css_font_size;
    function parse_css_length(size) {
        const match = size.match(/^\s*(-?\d+(\.\d+)?)(\w+)\s*$/);
        if (match != null) {
            const [, value, , unit] = match;
            const number = Number(value);
            if (isFinite(number))
                return { value: number, unit };
        }
        return null;
    }
    exports.parse_css_length = parse_css_length;
},
/* core/util/affine.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(26) /* ./eq */;
    const { sin, cos } = Math;
    class AffineTransform {
        constructor(a = 1, b = 0, c = 0, d = 1, e = 0, f = 0) {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.e = e;
            this.f = f;
        }
        toString() {
            const { a, b, c, d, e, f } = this;
            return `matrix(${a}, ${b}, ${c}, ${d}, ${e}, ${f})`;
        }
        static from_DOMMatrix(matrix) {
            const { a, b, c, d, e, f } = matrix;
            return new AffineTransform(a, b, c, d, e, f);
        }
        to_DOMMatrix() {
            const { a, b, c, d, e, f } = this;
            return new DOMMatrix([a, b, c, d, e, f]);
        }
        clone() {
            const { a, b, c, d, e, f } = this;
            return new AffineTransform(a, b, c, d, e, f);
        }
        [eq_1.equals](that, cmp) {
            return (cmp.eq(this.a, that.a) &&
                cmp.eq(this.b, that.b) &&
                cmp.eq(this.c, that.c) &&
                cmp.eq(this.d, that.d) &&
                cmp.eq(this.e, that.e) &&
                cmp.eq(this.f, that.f));
        }
        reset() {
            this.a = 1;
            this.b = 0;
            this.c = 0;
            this.d = 1;
            this.e = 0;
            this.f = 0;
        }
        get is_identity() {
            const { a, b, c, d, e, f } = this;
            return a == 1 && b == 0 && c == 0 && d == 1 && e == 0 && f == 0;
        }
        apply_point(p) {
            const [x, y] = this.apply(p.x, p.y);
            return { x, y };
        }
        apply_rect(rect) {
            const p0 = this.apply_point(rect.p0);
            const p1 = this.apply_point(rect.p1);
            const p2 = this.apply_point(rect.p2);
            const p3 = this.apply_point(rect.p3);
            return { p0, p1, p2, p3 };
        }
        apply(x, y) {
            const { a, b, c, d, e, f } = this;
            return [
                a * x + c * y + e,
                b * x + d * y + f,
            ];
        }
        iv_apply(xs, ys) {
            const { a, b, c, d, e, f } = this;
            const n = xs.length;
            for (let i = 0; i < n; i++) {
                const x = xs[i];
                const y = ys[i];
                xs[i] = a * x + c * y + e;
                ys[i] = b * x + d * y + f;
            }
        }
        transform(A, B, C, D, E, F) {
            const { a, b, c, d, e, f } = this;
            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;
        }
        translate(tx, ty) {
            return this.transform(1, 0, 0, 1, tx, ty);
        }
        scale(cx, cy) {
            return this.transform(cx, 0, 0, cy, 0, 0);
        }
        skew(sx, sy) {
            return this.transform(1, sy, sx, 1, 0, 0);
        }
        rotate(angle) {
            if (angle == 0)
                return this;
            const s = sin(angle);
            const c = cos(angle);
            return this.transform(c, s, -s, c, 0, 0);
        }
        rotate_ccw(angle) {
            return this.rotate(-angle);
        }
        rotate_around(x, y, angle) {
            this.translate(x, y);
            this.rotate(angle);
            this.translate(-x, -y);
            return this;
        }
        translate_x(tx) {
            return this.translate(tx, 0);
        }
        translate_y(ty) {
            return this.translate(0, ty);
        }
        flip() {
            return this.scale(-1, -1);
        }
        flip_x() {
            return this.scale(1, -1);
        }
        flip_y() {
            return this.scale(-1, 1);
        }
        inverse() {
            return AffineTransform.from_DOMMatrix(this.to_DOMMatrix().inverse());
        }
    }
    exports.AffineTransform = AffineTransform;
    AffineTransform.__name__ = "AffineTransform";
    function rotate_around(point, center, angle) {
        if (angle == 0) {
            return point;
        }
        else {
            const tr = new AffineTransform();
            tr.rotate_around(center.x, center.y, angle);
            const [x, y] = tr.apply(point.x, point.y);
            return { x, y };
        }
    }
    exports.rotate_around = rotate_around;
},
/* models/text/providers.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (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))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    __esModule();
    const signaling_1 = require(15) /* ../../core/signaling */;
    const modules_1 = require(157) /* ../../core/util/modules */;
    class MathJaxProvider {
        constructor() {
            this.ready = new signaling_1.Signal0(this, "ready");
            this.status = "not_started";
        }
    }
    exports.MathJaxProvider = MathJaxProvider;
    MathJaxProvider.__name__ = "MathJaxProvider";
    class NoProvider extends MathJaxProvider {
        get MathJax() {
            return null;
        }
        async fetch() {
            this.status = "failed";
        }
    }
    exports.NoProvider = NoProvider;
    NoProvider.__name__ = "NoProvider";
    class CDNProvider extends MathJaxProvider {
        get MathJax() {
            return typeof MathJax !== "undefined" ? MathJax : null;
        }
        async fetch() {
            const script = document.createElement("script");
            script.src = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js";
            script.onload = () => {
                this.status = "loaded";
                this.ready.emit();
            };
            script.onerror = () => {
                this.status = "failed";
            };
            this.status = "loading";
            document.head.appendChild(script);
        }
    }
    exports.CDNProvider = CDNProvider;
    CDNProvider.__name__ = "CDNProvider";
    class BundleProvider extends MathJaxProvider {
        get MathJax() {
            return this._mathjax;
        }
        async fetch() {
            this.status = "loading";
            try {
                const mathjax = await (0, modules_1.load_module)(Promise.resolve().then(() => __importStar(require(677) /* ./mathjax */)));
                this._mathjax = mathjax;
                this.status = "loaded";
                this.ready.emit();
            }
            catch (error) {
                this.status = "failed";
            }
        }
    }
    exports.BundleProvider = BundleProvider;
    BundleProvider.__name__ = "BundleProvider";
    exports.default_provider = new BundleProvider();
},
/* core/util/modules.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function is_ModuleError(error) {
        return error instanceof Error && "code" in error;
    }
    /** T is of import("some/module/path") type */
    async function load_module(module) {
        try {
            return await module;
        }
        catch (e) {
            // XXX: this exposes the underyling module system and hinders
            // interoperability with other module systems and bundlers
            if (is_ModuleError(e) && e.code === "MODULE_NOT_FOUND")
                return null;
            else
                throw e;
        }
    }
    exports.load_module = load_module;
},
/* models/text/plain_text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const base_text_1 = require(149) /* ./base_text */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    class PlainTextView extends base_text_1.BaseTextView {
        initialize() {
            super.initialize();
            this._has_finished = true;
        }
        graphics() {
            return new graphics_1.TextBox({ text: this.model.text });
        }
    }
    exports.PlainTextView = PlainTextView;
    PlainTextView.__name__ = "PlainTextView";
    class PlainText extends base_text_1.BaseText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.PlainText = PlainText;
    _a = PlainText;
    PlainText.__name__ = "PlainText";
    (() => {
        _a.prototype.default_view = PlainTextView;
    })();
},
/* models/canvas/cartesian_frame.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const categorical_scale_1 = require(93) /* ../scales/categorical_scale */;
    const log_scale_1 = require(92) /* ../scales/log_scale */;
    const range1d_1 = require(88) /* ../ranges/range1d */;
    const data_range1d_1 = require(95) /* ../ranges/data_range1d */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const object_1 = require(9) /* ../../core/util/object */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    class CartesianFrame {
        get bbox() {
            return this._bbox;
        }
        constructor(in_x_scale, in_y_scale, x_range, y_range, extra_x_ranges = {}, extra_y_ranges = {}, extra_x_scales = {}, extra_y_scales = {}) {
            this._bbox = new bbox_1.BBox();
            this.change = new signaling_1.Signal0(this, "change");
            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;
            (0, assert_1.assert)(in_x_scale.properties.source_range.is_unset && in_x_scale.properties.target_range.is_unset);
            (0, assert_1.assert)(in_y_scale.properties.source_range.is_unset && in_y_scale.properties.target_range.is_unset);
            this._configure_scales();
        }
        _get_ranges(range, extra_ranges) {
            return new Map((0, object_1.entries)(Object.assign(Object.assign({}, extra_ranges), { default: range })));
        }
        /*protected*/ _get_scales(scale, extra_scales, ranges, frame_range) {
            var _a;
            const in_scales = new Map((0, object_1.entries)(Object.assign(Object.assign({}, extra_scales), { default: scale })));
            const scales = new Map();
            for (const [name, range] of ranges) {
                const factor_range = range instanceof factor_range_1.FactorRange;
                const 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";
                const base_scale = (_a = in_scales.get(name)) !== null && _a !== void 0 ? _a : scale;
                const derived_scale = base_scale.clone();
                derived_scale.setv({ source_range: range, target_range: frame_range });
                scales.set(name, derived_scale);
            }
            return scales;
        }
        _configure_frame_ranges() {
            // data to/from screen space transform (left-bottom <-> left-top origin)
            const { bbox } = this;
            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 });
        }
        _configure_scales() {
            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);
        }
        configure_scales() {
            this._configure_scales();
            this.change.emit();
        }
        _update_scales() {
            this._configure_frame_ranges();
            for (const [, scale] of this._x_scales) {
                scale.target_range = this._x_target;
            }
            for (const [, scale] of this._y_scales) {
                scale.target_range = this._y_target;
            }
        }
        set_geometry(bbox) {
            this._bbox = bbox;
            this._update_scales();
        }
        get x_target() {
            return this._x_target;
        }
        get y_target() {
            return this._y_target;
        }
        get x_ranges() {
            return this._x_ranges;
        }
        get y_ranges() {
            return this._y_ranges;
        }
        get ranges() {
            return new Set([...this.x_ranges.values(), ...this.y_ranges.values()]);
        }
        get x_scales() {
            return this._x_scales;
        }
        get y_scales() {
            return this._y_scales;
        }
        get scales() {
            return new Set([...this.x_scales.values(), ...this.y_scales.values()]);
        }
        get x_scale() {
            return this._x_scales.get("default");
        }
        get y_scale() {
            return this._y_scales.get("default");
        }
    }
    exports.CartesianFrame = CartesianFrame;
    CartesianFrame.__name__ = "CartesianFrame";
},
/* models/axes/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var axis_1 = require(161) /* ./axis */;
    __esExport("Axis", axis_1.Axis);
    var categorical_axis_1 = require(166) /* ./categorical_axis */;
    __esExport("CategoricalAxis", categorical_axis_1.CategoricalAxis);
    var continuous_axis_1 = require(169) /* ./continuous_axis */;
    __esExport("ContinuousAxis", continuous_axis_1.ContinuousAxis);
    var datetime_axis_1 = require(170) /* ./datetime_axis */;
    __esExport("DatetimeAxis", datetime_axis_1.DatetimeAxis);
    var linear_axis_1 = require(186) /* ./linear_axis */;
    __esExport("LinearAxis", linear_axis_1.LinearAxis);
    var log_axis_1 = require(188) /* ./log_axis */;
    __esExport("LogAxis", log_axis_1.LogAxis);
    var mercator_axis_1 = require(191) /* ./mercator_axis */;
    __esExport("MercatorAxis", mercator_axis_1.MercatorAxis);
},
/* models/axes/axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const guide_renderer_1 = require(162) /* ../renderers/guide_renderer */;
    const ticker_1 = require(163) /* ../tickers/ticker */;
    const tick_formatter_1 = require(164) /* ../formatters/tick_formatter */;
    const labeling_1 = require(165) /* ../policies/labeling */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const types_1 = require(24) /* ../../core/types */;
    const side_panel_1 = require(146) /* ../../core/layout/side_panel */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_2 = require(8) /* ../../core/util/types */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    const base_text_1 = require(149) /* ../text/base_text */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const types_3 = require(8) /* ../../core/util/types */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const utils_1 = require(150) /* ../text/utils */;
    const { abs } = Math;
    class AxisView extends guide_renderer_1.GuideRendererView {
        constructor() {
            super(...arguments);
            /*private*/ this._axis_label_view = null;
            /*private*/ this._major_label_views = new Map();
        }
        get panel() {
            return this._panel;
        }
        set panel(panel) {
            this._panel = new side_panel_1.Panel(panel.side, this.model.face);
        }
        get bbox() {
            // TODO Fixed axes should not participate in layout at all.
            if (this.layout != null && this.model.fixed_location == null) {
                return this.layout.bbox;
            }
            else if (this.is_renderable) {
                const { extents } = this;
                const depth = Math.round(extents.tick + extents.tick_label + extents.axis_label);
                let { sx0, sy0, sx1, sy1 } = this.rule_scoords;
                const { dimension, face } = this;
                if (dimension == 0) {
                    if (face == "front")
                        sy0 -= depth;
                    else
                        sy1 += depth;
                }
                else {
                    if (face == "front")
                        sx0 -= depth;
                    else
                        sx1 += depth;
                }
                return bbox_1.BBox.from_lrtb({ left: sx0, top: sy0, right: sx1, bottom: sy1 });
            }
            else {
                return new bbox_1.BBox();
            }
        }
        *children() {
            yield* super.children();
            if (this._axis_label_view != null)
                yield this._axis_label_view;
            yield* this._major_label_views.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._init_axis_label();
            await this._init_major_labels();
        }
        async _init_axis_label() {
            const { axis_label } = this.model;
            if (axis_label != null) {
                const _axis_label = (0, types_3.isString)(axis_label) ? (0, utils_1.parse_delimited_string)(axis_label) : axis_label;
                this._axis_label_view = await (0, build_views_1.build_view)(_axis_label, { parent: this });
            }
            else
                this._axis_label_view = null;
        }
        async _init_major_labels() {
            for (const [label, label_text] of this.model.major_label_overrides) {
                const _label_text = (0, types_3.isString)(label_text) ? (0, utils_1.parse_delimited_string)(label_text) : label_text;
                this._major_label_views.set(label, await (0, build_views_1.build_view)(_label_text, { parent: this }));
            }
        }
        update_layout() {
            this.layout = new side_panel_1.SideLayout(this.panel, () => this.get_size(), true);
            this.layout.on_resize(() => this._coordinates = undefined);
        }
        get_size() {
            const { visible, fixed_location } = this.model;
            if (visible && fixed_location == null && this.is_renderable) {
                const { extents } = this;
                const height = Math.round(extents.tick + extents.tick_label + extents.axis_label);
                return { width: 0, height };
            }
            else
                return { width: 0, height: 0 };
        }
        get is_renderable() {
            const [range, cross_range] = this.ranges;
            return range.is_valid && cross_range.is_valid && range.span > 0 && cross_range.span > 0;
        }
        _render() {
            var _b;
            if (!this.is_renderable)
                return;
            const { tick_coords, extents } = this;
            const ctx = this.layer.ctx;
            ctx.save();
            this._draw_background(ctx, extents);
            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();
        }
        connect_signals() {
            super.connect_signals();
            const { axis_label, major_label_overrides } = this.model.properties;
            this.on_change(axis_label, async () => {
                var _b;
                (_b = this._axis_label_view) === null || _b === void 0 ? void 0 : _b.remove();
                await this._init_axis_label();
            });
            this.on_change(major_label_overrides, async () => {
                for (const label_view of this._major_label_views.values()) {
                    label_view.remove();
                }
                await this._init_major_labels();
            });
            this.connect(this.model.change, () => this.plot_view.request_layout());
        }
        get needs_clip() {
            return this.model.fixed_location != null;
        }
        // drawing sub functions -----------------------------------------------------
        _draw_background(ctx, _extents) {
            if (!this.visuals.background_fill.doit)
                return;
            ctx.beginPath();
            const { x, y, width, height } = this.bbox;
            ctx.rect(x, y, width, height);
            this.visuals.background_fill.apply(ctx);
        }
        _draw_rule(ctx, _extents) {
            if (!this.visuals.axis_line.doit)
                return;
            const { sx0, sy0, sx1, sy1 } = this.rule_scoords;
            ctx.beginPath();
            ctx.moveTo(sx0, sy0);
            ctx.lineTo(sx1, sy1);
            this.visuals.axis_line.apply(ctx);
        }
        _draw_major_ticks(ctx, _extents, tick_coords) {
            const tin = this.model.major_tick_in;
            const tout = this.model.major_tick_out;
            const visuals = this.visuals.major_tick_line;
            this._draw_ticks(ctx, tick_coords.major, tin, tout, visuals);
        }
        _draw_minor_ticks(ctx, _extents, tick_coords) {
            const tin = this.model.minor_tick_in;
            const tout = this.model.minor_tick_out;
            const visuals = this.visuals.minor_tick_line;
            this._draw_ticks(ctx, tick_coords.minor, tin, tout, visuals);
        }
        _draw_major_labels(ctx, extents, tick_coords) {
            const coords = tick_coords.major;
            const labels = this.compute_labels(coords[this.dimension]);
            const orient = this.model.major_label_orientation;
            const standoff = extents.tick + this.model.major_label_standoff;
            const visuals = this.visuals.major_label_text;
            this._draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals);
        }
        _axis_label_extent() {
            if (this._axis_label_view == null)
                return 0;
            const axis_label_graphics = this._axis_label_view.graphics();
            const padding = 3;
            const orient = this.model.axis_label_orientation;
            axis_label_graphics.visuals = this.visuals.axis_label_text.values();
            axis_label_graphics.angle = this.panel.get_label_angle_heuristic(orient);
            axis_label_graphics.base_font_size = this.plot_view.base_font_size;
            const size = axis_label_graphics.size();
            const extent = this.dimension == 0 ? size.height : size.width;
            const standoff = this.model.axis_label_standoff;
            return extent > 0 ? standoff + extent + padding : 0;
        }
        _draw_axis_label(ctx, extents, _tick_coords) {
            if (this._axis_label_view == null)
                return;
            const [sx, sy /* TODO, x_anchor, y_anchor*/] = (() => {
                const { bbox } = this;
                const { side, face } = this.panel;
                const [range] = this.ranges;
                const { axis_label_align } = this.model;
                switch (side) {
                    case "above":
                    case "below": {
                        const [sx, x_anchor] = (() => {
                            switch (axis_label_align) {
                                case "start": return !range.is_reversed ? [bbox.left, "left"] : [bbox.right, "right"];
                                case "center": return [bbox.hcenter, "center"];
                                case "end": return !range.is_reversed ? [bbox.right, "right"] : [bbox.left, "left"];
                            }
                        })();
                        const [sy, y_anchor] = face == "front" ? [bbox.bottom, "bottom"] : [bbox.top, "top"];
                        return [sx, sy, x_anchor, y_anchor];
                    }
                    case "left":
                    case "right": {
                        const [sy, y_anchor] = (() => {
                            switch (axis_label_align) {
                                case "start": return !range.is_reversed ? [bbox.bottom, "bottom"] : [bbox.top, "top"];
                                case "center": return [bbox.vcenter, "center"];
                                case "end": return !range.is_reversed ? [bbox.top, "top"] : [bbox.bottom, "bottom"];
                            }
                        })();
                        const [sx, x_anchor] = face == "front" ? [bbox.right, "right"] : [bbox.left, "left"];
                        return [sx, sy, x_anchor, y_anchor];
                    }
                }
            })();
            const [nx, ny] = this.normals;
            const orient = this.model.axis_label_orientation;
            const standoff = extents.tick + extents.tick_label + this.model.axis_label_standoff;
            const { vertical_align, align } = this.panel.get_label_text_heuristics(orient);
            const position = {
                sx: sx + nx * standoff,
                sy: sy + ny * standoff,
                x_anchor: align,
                y_anchor: vertical_align,
            };
            const 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(orient);
            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);
        }
        _draw_ticks(ctx, coords, tin, tout, visuals) {
            if (!visuals.doit)
                return;
            const [sxs, sys] = this.scoords(coords);
            const [nx, ny] = this.normals;
            const [xoff, yoff] = this.offsets;
            const [nxin, nyin] = [nx * (xoff - tin), ny * (yoff - tin)];
            const [nxout, nyout] = [nx * (xoff + tout), ny * (yoff + tout)];
            visuals.set_value(ctx);
            ctx.beginPath();
            for (let i = 0; i < sxs.length; i++) {
                const sx0 = Math.round(sxs[i] + nxout);
                const sy0 = Math.round(sys[i] + nyout);
                const sx1 = Math.round(sxs[i] + nxin);
                const sy1 = Math.round(sys[i] + nyin);
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
            }
            ctx.stroke();
        }
        _draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals) {
            if (!visuals.doit || labels.length == 0)
                return;
            const [sxs, sys] = this.scoords(coords);
            const [xoff, yoff] = this.offsets;
            const [nx, ny] = this.normals;
            const nxd = nx * (xoff + standoff);
            const nyd = ny * (yoff + standoff);
            const { vertical_align, align } = this.panel.get_label_text_heuristics(orient);
            const 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 (let i = 0; i < labels.length; i++) {
                const 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;
            }
            const n = labels.length;
            const indices = types_1.Indices.all_set(n);
            const { items } = labels;
            const bboxes = items.map((l) => l.bbox());
            const dist = (() => {
                const [range] = this.ranges;
                if (!range.is_reversed)
                    return this.dimension == 0 ? (i, j) => bboxes[j].left - bboxes[i].right
                        : (i, j) => bboxes[i].top - bboxes[j].bottom;
                else
                    return this.dimension == 0 ? (i, j) => bboxes[i].left - bboxes[j].right
                        : (i, j) => bboxes[j].top - bboxes[i].bottom;
            })();
            const { major_label_policy } = this.model;
            const selected = major_label_policy.filter(indices, bboxes, dist);
            const ids = [...selected.ones()];
            if (ids.length != 0) {
                const cbox = this.canvas.bbox;
                const correct_x = (k) => {
                    const bbox = bboxes[k];
                    if (bbox.left < 0) {
                        const offset = -bbox.left;
                        const { position } = items[k];
                        items[k].position = Object.assign(Object.assign({}, position), { sx: position.sx + offset });
                    }
                    else if (bbox.right > cbox.width) {
                        const offset = bbox.right - cbox.width;
                        const { position } = items[k];
                        items[k].position = Object.assign(Object.assign({}, position), { sx: position.sx - offset });
                    }
                };
                const correct_y = (k) => {
                    const bbox = bboxes[k];
                    if (bbox.top < 0) {
                        const offset = -bbox.top;
                        const { position } = items[k];
                        items[k].position = Object.assign(Object.assign({}, position), { sy: position.sy + offset });
                    }
                    else if (bbox.bottom > cbox.height) {
                        const offset = bbox.bottom - cbox.height;
                        const { position } = items[k];
                        items[k].position = Object.assign(Object.assign({}, position), { sy: position.sy - offset });
                    }
                };
                const i = ids[0];
                const j = ids[ids.length - 1];
                if (this.dimension == 0) {
                    correct_x(i);
                    correct_x(j);
                }
                else {
                    correct_y(i);
                    correct_y(j);
                }
            }
            for (const i of selected) {
                const label = items[i];
                label.paint(ctx);
            }
        }
        // extents sub functions -----------------------------------------------------
        /*protected*/ _tick_extent() {
            const { major, minor } = this.tick_coords;
            const i = this.dimension;
            return Math.max(major[i].length == 0 ? 0 : this.model.major_tick_out, minor[i].length == 0 ? 0 : this.model.minor_tick_out);
        }
        _tick_label_extents() {
            const coords = this.tick_coords.major;
            const labels = this.compute_labels(coords[this.dimension]);
            const orient = this.model.major_label_orientation;
            const standoff = this.model.major_label_standoff;
            const visuals = this.visuals.major_label_text;
            return [this._oriented_labels_extent(labels, orient, standoff, visuals)];
        }
        get extents() {
            const tick_labels = this._tick_label_extents();
            return {
                tick: this._tick_extent(),
                tick_labels,
                tick_label: (0, array_1.sum)(tick_labels),
                axis_label: this._axis_label_extent(),
            };
        }
        _oriented_labels_extent(labels, orient, standoff, visuals) {
            if (labels.length == 0 || !visuals.doit)
                return 0;
            const 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;
            const size = labels.max_size();
            const extent = this.dimension == 0 ? size.height : size.width;
            const padding = 3;
            return extent > 0 ? standoff + extent + padding : 0;
        }
        // {{{ TODO: state
        get normals() {
            return this.panel.normals;
        }
        get dimension() {
            return this.panel.dimension;
        }
        compute_labels(ticks) {
            const labels = this.model.formatter.format_graphics(ticks, this);
            const { _major_label_views } = this;
            const visited = new Set();
            for (let i = 0; i < ticks.length; i++) {
                const override = _major_label_views.get(ticks[i]);
                if (override != null) {
                    visited.add(override);
                    labels[i] = override.graphics();
                }
            }
            // XXX: make sure unused overrides don't prevent document idle
            for (const label_view of this._major_label_views.values()) {
                if (!visited.has(label_view)) {
                    label_view._has_finished = true;
                }
            }
            return new graphics_1.GraphicsBoxes(labels);
        }
        scoords(coords) {
            /**
             * Compute screen coordinates with respect to the bbox.
             */
            const [x, y] = coords;
            const [sxs, sys] = this.coordinates.map_to_screen(x, y);
            if (this.model.fixed_location != null) {
                return [[...sxs], [...sys]];
            }
            else {
                const { bbox } = this;
                const { face } = this.panel;
                if (this.panel.is_vertical) {
                    const sx = face == "front" ? bbox.right : bbox.left;
                    return [(0, array_1.repeat)(sx, sxs.length), [...sys]];
                }
                else {
                    const sy = face == "front" ? bbox.bottom : bbox.top;
                    return [[...sxs], (0, array_1.repeat)(sy, sys.length)];
                }
            }
        }
        // TODO Remove this.
        get offsets() {
            return [0, 0];
        }
        get ranges() {
            const i = this.dimension;
            const j = 1 - i;
            const { ranges } = this.coordinates;
            return [ranges[i], ranges[j]];
        }
        get computed_bounds() {
            const [range] = this.ranges;
            const user_bounds = this.model.bounds;
            const range_bounds = [range.min, range.max];
            if (user_bounds == "auto")
                return [range.min, range.max];
            else {
                let start;
                let end;
                const [user_start, user_end] = user_bounds;
                const [range_start, range_end] = range_bounds;
                const { min, max } = Math;
                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];
            }
        }
        get rule_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const xs = new Array(2);
            const ys = new Array(2);
            const 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;
        }
        get rule_scoords() {
            const [[sx0, sx1], [sy0, sy1]] = this.scoords(this.rule_coords);
            return {
                sx0: Math.round(sx0),
                sy0: Math.round(sy0),
                sx1: Math.round(sx1),
                sy1: Math.round(sy1),
            };
        }
        get tick_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const ticks = this.model.ticker.get_ticks(start, end, range, this.loc);
            const majors = ticks.major;
            const minors = ticks.minor;
            const xs = [];
            const ys = [];
            const coords = [xs, ys];
            const minor_xs = [];
            const minor_ys = [];
            const minor_coords = [minor_xs, minor_ys];
            const [range_min, range_max] = [range.min, range.max];
            for (let 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 (let 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,
            };
        }
        get loc() {
            const { fixed_location } = this.model;
            if (fixed_location != null) {
                if ((0, types_2.isNumber)(fixed_location))
                    return fixed_location;
                const [, cross_range] = this.ranges;
                if (cross_range instanceof factor_range_1.FactorRange)
                    return cross_range.synthetic(fixed_location);
                (0, assert_1.unreachable)();
            }
            const [, cross_range] = this.ranges;
            switch (this.panel.side) {
                case "left":
                case "below":
                    return cross_range.start;
                case "right":
                case "above":
                    return cross_range.end;
            }
        }
        get face() {
            return this.panel.face;
        }
        // }}}
        serializable_state() {
            return Object.assign(Object.assign({}, super.serializable_state()), { bbox: this.bbox });
        }
        remove() {
            var _b;
            (_b = this._axis_label_view) === null || _b === void 0 ? void 0 : _b.remove();
            for (const label_view of this._major_label_views.values()) {
                label_view.remove();
            }
            super.remove();
        }
        has_finished() {
            if (!super.has_finished())
                return false;
            if (this._axis_label_view != null) {
                if (!this._axis_label_view.has_finished())
                    return false;
            }
            for (const label_view of this._major_label_views.values()) {
                if (!label_view.has_finished())
                    return false;
            }
            return true;
        }
    }
    exports.AxisView = AxisView;
    AxisView.__name__ = "AxisView";
    class Axis extends guide_renderer_1.GuideRenderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Axis = Axis;
    _a = Axis;
    Axis.__name__ = "Axis";
    (() => {
        _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],
            ["background_", mixins.Fill],
        ]);
        _a.define(({ Any, Int, Number, String, Ref, Map, Tuple, Or, Nullable, Auto, Enum }) => ({
            dimension: [Or(Enum(0, 1), Auto), "auto"],
            face: [Or(enums_1.Face, Auto), "auto"],
            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],
            axis_label_orientation: [Or(enums_1.LabelOrientation, Number), "parallel"],
            axis_label_align: [enums_1.Align, "center"],
            major_label_standoff: [Int, 5],
            major_label_orientation: [Or(enums_1.LabelOrientation, Number), "horizontal"],
            major_label_overrides: [Map(Or(String, Number), Or(String, Ref(base_text_1.BaseText))), new globalThis.Map(), {
                    convert(v) {
                        return (0, types_2.isPlainObject)(v) ? new object_1.Dict(v) : v;
                    },
                }],
            major_label_policy: [Ref(labeling_1.LabelingPolicy), () => 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",
            background_fill_color: null,
        });
    })();
},
/* models/renderers/guide_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const renderer_1 = require(74) /* ./renderer */;
    class GuideRendererView extends renderer_1.RendererView {
    }
    exports.GuideRendererView = GuideRendererView;
    GuideRendererView.__name__ = "GuideRendererView";
    class GuideRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GuideRenderer = GuideRenderer;
    _a = GuideRenderer;
    GuideRenderer.__name__ = "GuideRenderer";
    (() => {
        _a.override({
            level: "guide",
        });
    })();
},
/* models/tickers/ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class Ticker extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ticker = Ticker;
    Ticker.__name__ = "Ticker";
},
/* models/formatters/tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    class TickFormatter extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        format_graphics(ticks, opts) {
            return this.doFormat(ticks, opts).map((text) => new graphics_1.TextBox({ text }));
        }
        compute(tick, opts) {
            return this.doFormat([tick], opts !== null && opts !== void 0 ? opts : { loc: 0 })[0];
        }
        v_compute(tick, opts) {
            return this.doFormat(tick, opts !== null && opts !== void 0 ? opts : { loc: 0 });
        }
    }
    exports.TickFormatter = TickFormatter;
    TickFormatter.__name__ = "TickFormatter";
},
/* models/policies/labeling.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    const types_1 = require(8) /* ../../core/util/types */;
    const types_2 = require(24) /* ../../core/types */;
    class LabelingPolicy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LabelingPolicy = LabelingPolicy;
    LabelingPolicy.__name__ = "LabelingPolicy";
    class AllLabels extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        filter(indices, _bboxes, _distance) {
            return indices;
        }
    }
    exports.AllLabels = AllLabels;
    AllLabels.__name__ = "AllLabels";
    class NoOverlap extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        filter(indices, _bboxes, distance) {
            const { min_distance } = this;
            let k = null;
            for (const i of indices) {
                if (k != null && distance(k, i) < min_distance)
                    indices.unset(i);
                else
                    k = i;
            }
            return indices;
        }
    }
    exports.NoOverlap = NoOverlap;
    _a = NoOverlap;
    NoOverlap.__name__ = "NoOverlap";
    (() => {
        _a.define(({ Number }) => ({
            min_distance: [Number, 5],
        }));
    })();
    class CustomLabelingPolicy extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new types_2.GeneratorFunction("indices", "bboxes", "distance", ...this.names, code);
        }
        filter(indices, bboxes, distance) {
            var _c, _d;
            const obj = Object.create(null);
            const generator = this.func.call(obj, indices, bboxes, distance, ...this.values);
            let result = generator.next();
            if (((_c = result.done) !== null && _c !== void 0 ? _c : false) && result.value !== undefined) {
                const { value } = result;
                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 {
                const array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!((_d = result.done) !== null && _d !== void 0 ? _d : false));
                return types_2.Indices.from_indices(indices.size, array);
            }
        }
    }
    exports.CustomLabelingPolicy = CustomLabelingPolicy;
    _b = CustomLabelingPolicy;
    CustomLabelingPolicy.__name__ = "CustomLabelingPolicy";
    (() => {
        _b.define(({ Unknown, String, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [String, ""],
        }));
    })();
},
/* models/axes/categorical_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const axis_1 = require(161) /* ./axis */;
    const categorical_ticker_1 = require(167) /* ../tickers/categorical_ticker */;
    const categorical_tick_formatter_1 = require(168) /* ../formatters/categorical_tick_formatter */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    const types_1 = require(8) /* ../../core/util/types */;
    class CategoricalAxisView extends axis_1.AxisView {
        _paint(ctx, extents, tick_coords) {
            this._draw_group_separators(ctx, extents, tick_coords);
        }
        _draw_group_separators(ctx, _extents, _tick_coords) {
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            if (range.tops == null || range.tops.length < 2 || !this.visuals.separator_line.doit)
                return;
            const dim = this.dimension;
            const alt = 1 - dim;
            const coords = [[], []];
            let ind = 0;
            for (let i = 0; i < range.tops.length - 1; i++) {
                let first, last;
                for (let j = ind; j < range.factors.length; j++) {
                    if (range.factors[j][0] == range.tops[i + 1]) {
                        [first, last] = [range.factors[j - 1], range.factors[j]];
                        ind = j;
                        break;
                    }
                }
                const pt = (range.synthetic(first) + range.synthetic(last)) / 2;
                if (pt > start && pt < end) {
                    coords[dim].push(pt);
                    coords[alt].push(this.loc);
                }
            }
            const tex = this.extents.tick_label;
            this._draw_ticks(ctx, coords, -3, tex - 6, this.visuals.separator_line);
        }
        _draw_major_labels(ctx, extents, _tick_coords) {
            const info = this._get_factor_info();
            let standoff = extents.tick + this.model.major_label_standoff;
            for (let i = 0; i < info.length; i++) {
                const [labels, coords, orient, visuals] = info[i];
                this._draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals);
                standoff += extents.tick_labels[i];
            }
        }
        _tick_label_extents() {
            const info = this._get_factor_info();
            const extents = [];
            for (const [labels, , orient, visuals] of info) {
                const extent = this._oriented_labels_extent(labels, orient, this.model.major_label_standoff, visuals);
                extents.push(extent);
            }
            return extents;
        }
        _get_factor_info() {
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const loc = this.loc;
            const ticks = this.model.ticker.get_ticks(start, end, range, loc);
            const coords = this.tick_coords;
            const info = [];
            const map = (labels) => {
                return new graphics_1.GraphicsBoxes(labels.map((label) => (0, types_1.isString)(label) ? new graphics_1.TextBox({ text: label }) : label));
            };
            const format = (ticks) => {
                return map(this.model.formatter.doFormat(ticks, this));
            };
            if (range.levels == 1) {
                const major = ticks.major;
                const labels = format(major);
                info.push([labels, coords.major, this.model.major_label_orientation, this.visuals.major_label_text]);
            }
            else if (range.levels == 2) {
                const major = ticks.major.map((x) => x[1]);
                const 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) {
                const major = ticks.major.map((x) => x[2]);
                const labels = format(major);
                const mid_labels = ticks.mids.map((x) => 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;
        }
        get tick_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const ticks = this.model.ticker.get_ticks(start, end, range, this.loc);
            const coords = {
                major: [[], []],
                mids: [[], []],
                tops: [[], []],
                minor: [[], []],
            };
            coords.major[i] = ticks.major;
            coords.major[j] = ticks.major.map(() => this.loc);
            if (range.levels == 3) {
                coords.mids[i] = ticks.mids;
                coords.mids[j] = ticks.mids.map(() => this.loc);
            }
            if (range.levels > 1) {
                coords.tops[i] = ticks.tops;
                coords.tops[j] = ticks.tops.map(() => this.loc);
            }
            return coords;
        }
    }
    exports.CategoricalAxisView = CategoricalAxisView;
    CategoricalAxisView.__name__ = "CategoricalAxisView";
    class CategoricalAxis extends axis_1.Axis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CategoricalAxis = CategoricalAxis;
    _a = CategoricalAxis;
    CategoricalAxis.__name__ = "CategoricalAxis";
    (() => {
        _a.prototype.default_view = CategoricalAxisView;
        _a.mixins([
            ["separator_", mixins.Line],
            ["group_", mixins.Text],
            ["subgroup_", mixins.Text],
        ]);
        _a.define(({ Number, Or }) => ({
            group_label_orientation: [Or(enums_1.LabelOrientation, Number), "parallel"],
            subgroup_label_orientation: [Or(enums_1.LabelOrientation, Number), "parallel"],
        }));
        _a.override({
            ticker: () => new categorical_ticker_1.CategoricalTicker(),
            formatter: () => 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();
    const ticker_1 = require(163) /* ./ticker */;
    class CategoricalTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks(start, end, range, _cross_loc) {
            var _a, _b;
            const majors = this._collect(range.factors, range, start, end);
            const tops = this._collect((_a = range.tops) !== null && _a !== void 0 ? _a : [], range, start, end);
            const mids = this._collect((_b = range.mids) !== null && _b !== void 0 ? _b : [], range, start, end);
            return {
                major: majors,
                minor: [],
                tops,
                mids,
            };
        }
        _collect(factors, range, start, end) {
            const result = [];
            for (const factor of factors) {
                const coord = range.synthetic(factor);
                if (coord > start && coord < end)
                    result.push(factor);
            }
            return result;
        }
    }
    exports.CategoricalTicker = CategoricalTicker;
    CategoricalTicker.__name__ = "CategoricalTicker";
},
/* models/formatters/categorical_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(164) /* ./tick_formatter */;
    const array_1 = require(10) /* ../../core/util/array */;
    class CategoricalTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, _opts) {
            return (0, array_1.copy)(ticks);
        }
    }
    exports.CategoricalTickFormatter = CategoricalTickFormatter;
    CategoricalTickFormatter.__name__ = "CategoricalTickFormatter";
},
/* models/axes/continuous_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const axis_1 = require(161) /* ./axis */;
    class ContinuousAxisView extends axis_1.AxisView {
    }
    exports.ContinuousAxisView = ContinuousAxisView;
    ContinuousAxisView.__name__ = "ContinuousAxisView";
    class ContinuousAxis extends axis_1.Axis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContinuousAxis = ContinuousAxis;
    ContinuousAxis.__name__ = "ContinuousAxis";
},
/* models/axes/datetime_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_axis_1 = require(169) /* ./continuous_axis */;
    const datetime_tick_formatter_1 = require(171) /* ../formatters/datetime_tick_formatter */;
    const datetime_ticker_1 = require(177) /* ../tickers/datetime_ticker */;
    class DatetimeAxisView extends continuous_axis_1.ContinuousAxisView {
    }
    exports.DatetimeAxisView = DatetimeAxisView;
    DatetimeAxisView.__name__ = "DatetimeAxisView";
    class DatetimeAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DatetimeAxis = DatetimeAxis;
    _a = DatetimeAxis;
    DatetimeAxis.__name__ = "DatetimeAxis";
    (() => {
        _a.prototype.default_view = DatetimeAxisView;
        _a.override({
            ticker: () => new datetime_ticker_1.DatetimeTicker(),
            formatter: () => new datetime_tick_formatter_1.DatetimeTickFormatter(),
        });
    })();
},
/* models/formatters/datetime_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const enums_1 = require(20) /* ../../core/enums */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const templating_1 = require(172) /* ../../core/util/templating */;
    const types_1 = require(8) /* ../../core/util/types */;
    const tick_formatter_1 = require(164) /* ./tick_formatter */;
    const util_1 = require(176) /* ../tickers/util */;
    const timezone_1 = tslib_1.__importDefault(require(175) /* timezone */);
    // Labels of time units, from finest to coarsest.
    exports.resolution_order = [
        "microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days", "months", "years",
    ];
    // This dictionary maps the name of a time resolution (in @resolution_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.
    exports.tm_index_for_resolution = new Map();
    for (const fmt of exports.resolution_order) {
        exports.tm_index_for_resolution.set(fmt, 0);
    }
    exports.tm_index_for_resolution.set("seconds", 5);
    exports.tm_index_for_resolution.set("minsec", 4);
    exports.tm_index_for_resolution.set("minutes", 4);
    exports.tm_index_for_resolution.set("hourmin", 3);
    exports.tm_index_for_resolution.set("hours", 3);
    function _get_resolution(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.
        const adjusted_ms = resolution_secs * 1.1 * 1000;
        const span_ms = span_secs * 1000;
        if (adjusted_ms < util_1.ONE_MILLI)
            return "microseconds";
        if (adjusted_ms < util_1.ONE_SECOND)
            return "milliseconds";
        if (adjusted_ms < util_1.ONE_MINUTE)
            return span_ms >= util_1.ONE_MINUTE ? "minsec" : "seconds";
        if (adjusted_ms < util_1.ONE_HOUR)
            return span_ms >= util_1.ONE_HOUR ? "hourmin" : "minutes";
        if (adjusted_ms < util_1.ONE_DAY)
            return "hours";
        if (adjusted_ms < util_1.ONE_MONTH)
            return "days";
        if (adjusted_ms < util_1.ONE_YEAR)
            return "months";
        return "years";
    }
    exports._get_resolution = _get_resolution;
    function _mktime(t) {
        return (0, timezone_1.default)(t, "%Y %m %d %H %M %S").split(/\s+/).map(e => parseInt(e, 10));
    }
    exports._mktime = _mktime;
    function _strftime(t, format) {
        // 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.
        const microsecond_replacement_string = (0, templating_1.sprintf)("$1%06d", _us(t));
        format = format.replace(/((^|[^%])(%%)*)%f/, microsecond_replacement_string);
        // 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.
        if (format.indexOf("%") == -1) {
            return format;
        }
        return (0, timezone_1.default)(t, format);
    }
    exports._strftime = _strftime;
    function _us(t) {
        // From double-precision unix (millisecond) timestamp, get microseconds 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.
        // Note: for negative timestamps (pre epoch) the microsecond scale needs to be
        // inverted as we are counting backwards.
        let us = Math.round(((t / 1000) % 1) * 1000000);
        if (t < 0.0) {
            us = (1000000 + us) % 1000000;
        }
        return us;
    }
    exports._us = _us;
    class DatetimeTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, _opts, _resolution) {
            if (ticks.length == 0)
                return [];
            const span = Math.abs(ticks[ticks.length - 1] - ticks[0]) / 1000.0;
            const r = span / (ticks.length - 1);
            const resolution = (0, types_1.is_undefined)(_resolution) ? _get_resolution(r, span) : _resolution;
            const labels = [];
            for (const [tick, i] of (0, iterator_1.enumerate)(ticks)) {
                const base_label = this._compute_label(tick, resolution);
                const full_label = this._add_context(tick, base_label, i, ticks.length, resolution);
                labels.push(full_label);
            }
            return labels;
        }
        _compute_label(t, resolution) {
            const s0 = _strftime(t, this[resolution]);
            const tm = _mktime(t);
            const resolution_index = exports.resolution_order.indexOf(resolution);
            let s = s0;
            let hybrid_handled = false;
            let next_index = resolution_index;
            let next_resolution;
            // 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 but it works.
            while (tm[exports.tm_index_for_resolution.get(exports.resolution_order[next_index])] == 0) {
                next_index += 1;
                if (next_index == exports.resolution_order.length)
                    break;
                // 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).
                if ((resolution == "minsec" || resolution == "hourmin") && !hybrid_handled) {
                    if ((resolution == "minsec" && tm[4] == 0 && tm[5] != 0) || (resolution == "hourmin" && tm[3] == 0 && tm[4] != 0)) {
                        next_resolution = exports.resolution_order[resolution_index - 1];
                        s = _strftime(t, this[next_resolution]);
                        break;
                    }
                    else {
                        hybrid_handled = true;
                    }
                }
                next_resolution = exports.resolution_order[next_index];
                s = _strftime(t, this[next_resolution]);
            }
            if (this.strip_leading_zeros) {
                const 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.
                    return `0${ss}`;
                }
                return ss;
            }
            return s;
        }
        _add_context(tick, label, i, N, resolution) {
            const loc = this.context_location;
            const which = this.context_which;
            if (this.context == null)
                return label;
            if ((which == "start" && i == 0) ||
                (which == "end" && i == N - 1) ||
                (which == "center" && i == Math.floor(N / 2)) ||
                (which == "all")) {
                const context = (0, types_1.isString)(this.context) ?
                    _strftime(tick, this.context) : this.context.doFormat([tick], { loc: 0 }, resolution)[0];
                if (context == "")
                    return label;
                switch (loc) {
                    case "above": return `${context}\n${label}`;
                    case "below": return `${label}\n${context}`;
                    case "left": return `${context} ${label}`;
                    case "right": return `${label} ${context}`;
                }
            }
            return label;
        }
    }
    exports.DatetimeTickFormatter = DatetimeTickFormatter;
    _a = DatetimeTickFormatter;
    DatetimeTickFormatter.__name__ = "DatetimeTickFormatter";
    (() => {
        _a.define(({ Boolean, Nullable, Or, Ref, String }) => ({
            microseconds: [String, "%fus"],
            milliseconds: [String, "%3Nms"],
            seconds: [String, "%Ss"],
            minsec: [String, ":%M:%S"],
            minutes: [String, ":%M"],
            hourmin: [String, "%H:%M"],
            hours: [String, "%Hh"],
            days: [String, "%m/%d"],
            months: [String, "%m/%Y"],
            years: [String, "%Y"],
            strip_leading_zeros: [Boolean, true],
            context: [Nullable(Or(String, Ref(_a))), null],
            context_which: [enums_1.ContextWhich, "start"],
            context_location: [enums_1.Location, "below"],
        }));
    })();
},
/* core/util/templating.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const Numbro = tslib_1.__importStar(require(173) /* @bokeh/numbro */);
    const sprintf_js_1 = require(174) /* sprintf-js */;
    const timezone_1 = tslib_1.__importDefault(require(175) /* timezone */);
    const kinds_1 = require(21) /* ../kinds */;
    const ndarray_1 = require(30) /* ./ndarray */;
    const types_1 = require(8) /* ./types */;
    exports.FormatterType = (0, kinds_1.Enum)("numeral", "printf", "datetime");
    exports.DEFAULT_FORMATTERS = {
        numeral: (value, format, _special_vars) => Numbro.format(value, format),
        datetime: (value, format, _special_vars) => (0, timezone_1.default)(value, format),
        printf: (value, format, _special_vars) => sprintf(format, value),
    };
    function sprintf(format, ...args) {
        return (0, sprintf_js_1.sprintf)(format, ...args);
    }
    exports.sprintf = sprintf;
    function basic_formatter(value, _format, _special_vars) {
        if ((0, types_1.isNumber)(value)) {
            const format = (() => {
                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) {
            const formatter = formatters[raw_spec];
            if ((0, types_1.isString)(formatter)) {
                if (formatter in exports.DEFAULT_FORMATTERS)
                    return exports.DEFAULT_FORMATTERS[formatter];
                else
                    throw new Error(`Unknown tooltip field formatter type '${formatter}'`);
            }
            return function (value, format, special_vars) {
                return formatter.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, ind) {
        const column = data_source.get_column(name);
        // missing column
        if (column == null)
            return null;
        // null index (e.g for patch)
        if (ind == null)
            return null;
        // typical (non-image) index
        if ((0, types_1.isNumber)(ind))
            return column[ind];
        // image index
        const data = column[ind.index];
        if ((0, types_1.isTypedArray)(data) || (0, types_1.isArray)(data)) {
            // inspect array of arrays
            if ((0, types_1.isArray)(data[0])) {
                const row = data[ind.j];
                return row[ind.i];
            }
            else if ((0, ndarray_1.is_NDArray)(data) && data.dimension == 3) {
                // For 3d array return whole of 3rd axis
                return data.slice(ind.flat_index * data.shape[2], (ind.flat_index + 1) * data.shape[2]);
            }
            else
                return data[ind.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] == "$") {
            const name = raw_name.substring(1);
            return _get_special_value(name, special_vars);
        }
        else {
            const 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) {
        let str;
        let 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, (_match) => `@{${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, (_match, spec, format) => {
            const value = get_value(spec, data_source, i, special_vars);
            // missing value, return ???
            if (value == null)
                return encode != null ? encode("???") : "???";
            // 'safe' format, return the value as-is
            if (format == "safe") {
                has_html = true;
                return `${value}`;
            }
            // format and escape everything else
            const formatter = get_formatter(spec, format, formatters);
            const result = `${formatter(value, format, special_vars)}`;
            return encode != null ? encode(result) : result;
        });
        if (!has_html)
            return str;
        else {
            const parser = new DOMParser();
            const document = parser.parseFromString(str, "text/html");
            return [...document.body.childNodes];
        }
    }
    exports.replace_placeholders = replace_placeholders;
    function process_placeholders(text, fn) {
        //
        // (?:\$\w+) - special vars: $x
        // (?:@\w+) - simple names: @foo
        // (?:@{(?:[^{}]+)})) - full names: @{one two}
        //
        // (?:{([^{}]+)})? - (optional) format for all of the above: @foo{fmt}
        //
        const regex = /((?:\$\w+)|(?:@\w+)|(?:@{(?:[^{}]+)}))(?:{([^{}]+)})?/g;
        return text.replace(regex, (_match, spec, format) => {
            const type = spec[0];
            const name = spec.substring(1).replace(/[{}]/g, "").trim();
            return fn(type, name, format);
        });
    }
    exports.process_placeholders = process_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
},
/* 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); };
    });
},
/* 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) {
        const 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) {
        const 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/datetime_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const array_1 = require(10) /* ../../core/util/array */;
    const adaptive_ticker_1 = require(178) /* ./adaptive_ticker */;
    const composite_ticker_1 = require(180) /* ./composite_ticker */;
    const days_ticker_1 = require(181) /* ./days_ticker */;
    const months_ticker_1 = require(183) /* ./months_ticker */;
    const years_ticker_1 = require(184) /* ./years_ticker */;
    const util_1 = require(176) /* ./util */;
    class DatetimeTicker extends composite_ticker_1.CompositeTicker {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DatetimeTicker = DatetimeTicker;
    _a = DatetimeTicker;
    DatetimeTicker.__name__ = "DatetimeTicker";
    (() => {
        _a.override({
            num_minor_ticks: 0,
            tickers: () => [
                // 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/adaptive_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    const math_1 = require(11) /* ../../core/util/math */;
    class AdaptiveTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_min_interval() {
            return this.min_interval;
        }
        get_max_interval() {
            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.
        get extended_mantissas() {
            const prefix_mantissa = (0, array_1.nth)(this.mantissas, -1) / this.base;
            const suffix_mantissa = (0, array_1.nth)(this.mantissas, 0) * this.base;
            return [prefix_mantissa, ...this.mantissas, suffix_mantissa];
        }
        get base_factor() {
            return this.get_min_interval() == 0.0 ? 1.0 : this.get_min_interval();
        }
        get_interval(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            const ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
            const interval_exponent = Math.floor((0, math_1.log)(ideal_interval / this.base_factor, this.base));
            const ideal_magnitude = 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]
            const candidate_mantissas = this.extended_mantissas;
            const errors = candidate_mantissas.map((mantissa) => {
                return Math.abs(desired_n_ticks - (data_range / (mantissa * ideal_magnitude)));
            });
            const best_mantissa = candidate_mantissas[(0, array_1.argmin)(errors)];
            const interval = best_mantissa * ideal_magnitude;
            return (0, math_1.clamp)(interval, this.get_min_interval(), this.get_max_interval());
        }
    }
    exports.AdaptiveTicker = AdaptiveTicker;
    _a = AdaptiveTicker;
    AdaptiveTicker.__name__ = "AdaptiveTicker";
    (() => {
        _a.define(({ Number, Array, Nullable }) => ({
            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) {
    var _a;
    __esModule();
    const ticker_1 = require(163) /* ./ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    class ContinuousTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks(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).
        get_ticks_no_defaults(data_low, data_high, _cross_loc, desired_n_ticks) {
            const interval = this.get_interval(data_low, data_high, desired_n_ticks);
            const start_factor = Math.floor(data_low / interval);
            const end_factor = Math.ceil(data_high / interval);
            let factors;
            if (!isFinite(start_factor) || !isFinite(end_factor))
                factors = [];
            else
                factors = (0, array_1.range)(start_factor, end_factor + 1);
            const ticks = factors
                .map((factor) => factor * interval)
                .filter((tick) => data_low <= tick && tick <= data_high);
            const num_minor_ticks = this.num_minor_ticks;
            const minor_ticks = [];
            if (num_minor_ticks > 0 && ticks.length > 0) {
                const minor_interval = interval / num_minor_ticks;
                const minor_offsets = (0, array_1.range)(0, num_minor_ticks).map((i) => i * minor_interval);
                for (const x of minor_offsets.slice(1)) {
                    const mt = ticks[0] - x;
                    if (data_low <= mt && mt <= data_high) {
                        minor_ticks.push(mt);
                    }
                }
                for (const tick of ticks) {
                    for (const x of minor_offsets) {
                        const mt = tick + x;
                        if (data_low <= mt && mt <= data_high) {
                            minor_ticks.push(mt);
                        }
                    }
                }
            }
            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.)
        get_ideal_interval(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            return data_range / desired_n_ticks;
        }
    }
    exports.ContinuousTicker = ContinuousTicker;
    _a = ContinuousTicker;
    ContinuousTicker.__name__ = "ContinuousTicker";
    (() => {
        _a.define(({ Int }) => ({
            num_minor_ticks: [Int, 5],
            desired_num_ticks: [Int, 6],
        }));
    })();
},
/* models/tickers/composite_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    class CompositeTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        // 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 min_intervals() {
            return this.tickers.map((ticker) => ticker.get_min_interval());
        }
        get max_intervals() {
            return this.tickers.map((ticker) => ticker.get_max_interval());
        }
        get_min_interval() {
            return this.min_intervals[0];
        }
        get_max_interval() {
            return this.max_intervals[0];
        }
        get_best_ticker(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            const ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
            const ticker_ndxs = [
                (0, array_1.sorted_index)(this.min_intervals, ideal_interval) - 1,
                (0, array_1.sorted_index)(this.max_intervals, ideal_interval),
            ];
            const intervals = [
                this.min_intervals[ticker_ndxs[0]],
                this.max_intervals[ticker_ndxs[1]],
            ];
            const errors = intervals.map((interval) => {
                return Math.abs(desired_n_ticks - (data_range / interval));
            });
            let best_ticker;
            if ((0, array_1.is_empty)(errors.filter((e) => !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 {
                const best_index = (0, array_1.argmin)(errors);
                const best_ticker_ndx = ticker_ndxs[best_index];
                best_ticker = this.tickers[best_ticker_ndx];
            }
            return best_ticker;
        }
        get_interval(data_low, data_high, desired_n_ticks) {
            const 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);
        }
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks) {
            const 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);
        }
    }
    exports.CompositeTicker = CompositeTicker;
    _a = CompositeTicker;
    CompositeTicker.__name__ = "CompositeTicker";
    (() => {
        _a.define(({ Array, Ref }) => ({
            tickers: [Array(Ref(continuous_ticker_1.ContinuousTicker)), []],
        }));
    })();
},
/* models/tickers/days_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const single_interval_ticker_1 = require(182) /* ./single_interval_ticker */;
    const util_1 = require(176) /* ./util */;
    const array_1 = require(10) /* ../../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) {
        const start_date = (0, util_1.last_month_no_later_than)(new Date(start_time));
        const 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);
        const dates = [];
        const 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;
    }
    class DaysTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            const 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;
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, _desired_n_ticks) {
            const month_dates = date_range_by_month(data_low, data_high);
            const days = this.days;
            const days_of_month = (month_date, interval) => {
                const current_month = month_date.getUTCMonth();
                const dates = [];
                for (const day of days) {
                    const 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"
                    const future_date = new Date(day_date.getTime() + (interval / 2));
                    if (future_date.getUTCMonth() == current_month)
                        dates.push(day_date);
                }
                return dates;
            };
            const day_dates = (0, array_1.concat)(month_dates.map((date) => days_of_month(date, this.interval)));
            const all_ticks = day_dates.map((day_date) => day_date.getTime());
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.DaysTicker = DaysTicker;
    _a = DaysTicker;
    DaysTicker.__name__ = "DaysTicker";
    (() => {
        _a.define(({ Int, Array }) => ({
            days: [Array(Int), []],
        }));
        _a.override({
            num_minor_ticks: 0,
        });
    })();
},
/* models/tickers/single_interval_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    class BaseSingleIntervalTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_interval(_data_low, _data_high, _n_desired_ticks) {
            return this.interval;
        }
        get_min_interval() {
            return this.interval;
        }
        get_max_interval() {
            return this.interval;
        }
    }
    exports.BaseSingleIntervalTicker = BaseSingleIntervalTicker;
    BaseSingleIntervalTicker.__name__ = "BaseSingleIntervalTicker";
    class SingleIntervalTicker extends BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.SingleIntervalTicker = SingleIntervalTicker;
    _a = SingleIntervalTicker;
    SingleIntervalTicker.__name__ = "SingleIntervalTicker";
    (() => {
        _a.define(({ Number }) => ({
            interval: [Number],
        }));
    })();
},
/* models/tickers/months_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const single_interval_ticker_1 = require(182) /* ./single_interval_ticker */;
    const util_1 = require(176) /* ./util */;
    const array_1 = require(10) /* ../../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) {
        const start_date = (0, util_1.last_year_no_later_than)(new Date(start_time));
        const end_date = (0, util_1.last_year_no_later_than)(new Date(end_time));
        end_date.setUTCFullYear(end_date.getUTCFullYear() + 1);
        const dates = [];
        const 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;
    }
    class MonthsTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            const 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;
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, _desired_n_ticks) {
            const year_dates = date_range_by_year(data_low, data_high);
            const months = this.months;
            const months_of_year = (year_date) => {
                return months.map((month) => {
                    const month_date = (0, util_1.copy_date)(year_date);
                    month_date.setUTCMonth(month);
                    return month_date;
                });
            };
            const month_dates = (0, array_1.concat)(year_dates.map(months_of_year));
            const all_ticks = month_dates.map((month_date) => month_date.getTime());
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.MonthsTicker = MonthsTicker;
    _a = MonthsTicker;
    MonthsTicker.__name__ = "MonthsTicker";
    (() => {
        _a.define(({ Int, Array }) => ({
            months: [Array(Int), []],
        }));
    })();
},
/* models/tickers/years_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const basic_ticker_1 = require(185) /* ./basic_ticker */;
    const single_interval_ticker_1 = require(182) /* ./single_interval_ticker */;
    const util_1 = require(176) /* ./util */;
    class YearsTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
            this.interval = util_1.ONE_YEAR;
            this.basic_ticker = new basic_ticker_1.BasicTicker({ num_minor_ticks: 0 });
        }
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks) {
            const start_year = (0, util_1.last_year_no_later_than)(new Date(data_low)).getUTCFullYear();
            const end_year = (0, util_1.last_year_no_later_than)(new Date(data_high)).getUTCFullYear();
            const years = this.basic_ticker.get_ticks_no_defaults(start_year, end_year, cross_loc, desired_n_ticks).major;
            const all_ticks = years.map((year) => Date.UTC(year, 0, 1));
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.YearsTicker = YearsTicker;
    YearsTicker.__name__ = "YearsTicker";
},
/* models/tickers/basic_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const adaptive_ticker_1 = require(178) /* ./adaptive_ticker */;
    class BasicTicker extends adaptive_ticker_1.AdaptiveTicker {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BasicTicker = BasicTicker;
    BasicTicker.__name__ = "BasicTicker";
},
/* models/axes/linear_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_axis_1 = require(169) /* ./continuous_axis */;
    const basic_tick_formatter_1 = require(187) /* ../formatters/basic_tick_formatter */;
    const basic_ticker_1 = require(185) /* ../tickers/basic_ticker */;
    class LinearAxisView extends continuous_axis_1.ContinuousAxisView {
    }
    exports.LinearAxisView = LinearAxisView;
    LinearAxisView.__name__ = "LinearAxisView";
    class LinearAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LinearAxis = LinearAxis;
    _a = LinearAxis;
    LinearAxis.__name__ = "LinearAxis";
    (() => {
        _a.prototype.default_view = LinearAxisView;
        _a.override({
            ticker: () => new basic_ticker_1.BasicTicker(),
            formatter: () => new basic_tick_formatter_1.BasicTickFormatter(),
        });
    })();
},
/* models/formatters/basic_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tick_formatter_1 = require(164) /* ./tick_formatter */;
    const string_1 = require(40) /* ../../core/util/string */;
    function unicode_replace(input) {
        let output = "";
        for (const c of input) {
            if (c == "-")
                output += "\u2212";
            else
                output += c;
        }
        return output;
    }
    exports.unicode_replace = unicode_replace;
    class BasicTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
            this.last_precision = 3;
        }
        get scientific_limit_low() {
            return 10.0 ** this.power_limit_low;
        }
        get scientific_limit_high() {
            return 10.0 ** this.power_limit_high;
        }
        _need_sci(ticks) {
            if (!this.use_scientific)
                return false;
            const { scientific_limit_high } = this;
            const { scientific_limit_low } = this;
            const zeroish = ticks.length < 2 ? 0 : Math.abs(ticks[1] - ticks[0]) / 10000;
            for (const tick of ticks) {
                const tick_abs = Math.abs(tick);
                if (tick_abs <= zeroish)
                    continue;
                if (tick_abs >= scientific_limit_high || tick_abs <= scientific_limit_low) {
                    return true;
                }
            }
            return false;
        }
        _format_with_precision(ticks, need_sci, precision) {
            if (need_sci) {
                return ticks.map((tick) => unicode_replace(tick.toExponential(precision)));
            }
            else {
                return ticks.map((tick) => unicode_replace((0, string_1.to_fixed)(tick, precision)));
            }
        }
        _auto_precision(ticks, need_sci) {
            const labels = new Array(ticks.length);
            const asc = this.last_precision <= 15;
            outer: for (let x = this.last_precision; asc ? x <= 15 : x >= 1; asc ? x++ : x--) {
                if (need_sci) {
                    labels[0] = ticks[0].toExponential(x);
                    for (let 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 (let 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;
        }
        doFormat(ticks, _opts) {
            if (ticks.length == 0)
                return [];
            const need_sci = this._need_sci(ticks);
            const precision = this.precision == "auto" ? this._auto_precision(ticks, need_sci) : this.precision;
            return this._format_with_precision(ticks, need_sci, precision);
        }
    }
    exports.BasicTickFormatter = BasicTickFormatter;
    _a = BasicTickFormatter;
    BasicTickFormatter.__name__ = "BasicTickFormatter";
    (() => {
        _a.define(({ Boolean, Int, Auto, Or }) => ({
            precision: [Or(Int, Auto), "auto"],
            use_scientific: [Boolean, true],
            power_limit_high: [Int, 5],
            power_limit_low: [Int, -3],
        }));
    })();
},
/* models/axes/log_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_axis_1 = require(169) /* ./continuous_axis */;
    const log_tick_formatter_1 = require(189) /* ../formatters/log_tick_formatter */;
    const log_ticker_1 = require(190) /* ../tickers/log_ticker */;
    class LogAxisView extends continuous_axis_1.ContinuousAxisView {
    }
    exports.LogAxisView = LogAxisView;
    LogAxisView.__name__ = "LogAxisView";
    class LogAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LogAxis = LogAxis;
    _a = LogAxis;
    LogAxis.__name__ = "LogAxis";
    (() => {
        _a.prototype.default_view = LogAxisView;
        _a.override({
            ticker: () => new log_ticker_1.LogTicker(),
            formatter: () => new log_tick_formatter_1.LogTickFormatter(),
        });
    })();
},
/* models/formatters/log_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tick_formatter_1 = require(164) /* ./tick_formatter */;
    const basic_tick_formatter_1 = require(187) /* ./basic_tick_formatter */;
    const log_ticker_1 = require(190) /* ../tickers/log_ticker */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    const { abs, log, round } = Math;
    class LogTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.basic_formatter = new basic_tick_formatter_1.BasicTickFormatter();
        }
        format_graphics(ticks, opts) {
            var _b, _c;
            if (ticks.length == 0)
                return [];
            const base = (_c = (_b = this.ticker) === null || _b === void 0 ? void 0 : _b.base) !== null && _c !== void 0 ? _c : 10;
            const expos = this._exponents(ticks, base);
            if (expos == null)
                return this.basic_formatter.format_graphics(ticks, opts);
            else {
                return expos.map((expo) => {
                    if (abs(expo) < this.min_exponent) {
                        const b = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${base ** expo}`) });
                        const e = new graphics_1.TextBox({ text: "" });
                        return new graphics_1.BaseExpo(b, e);
                    }
                    else {
                        const b = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${base}`) });
                        const e = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${expo}`) });
                        return new graphics_1.BaseExpo(b, e);
                    }
                });
            }
        }
        _exponents(ticks, base) {
            let last_exponent = null;
            const exponents = [];
            for (const tick of ticks) {
                const exponent = round(log(tick) / log(base));
                if (last_exponent != exponent) {
                    last_exponent = exponent;
                    exponents.push(exponent);
                }
                else
                    return null;
            }
            return exponents;
        }
        doFormat(ticks, opts) {
            var _b, _c;
            if (ticks.length == 0)
                return [];
            const base = (_c = (_b = this.ticker) === null || _b === void 0 ? void 0 : _b.base) !== null && _c !== void 0 ? _c : 10;
            const expos = this._exponents(ticks, base);
            if (expos == null)
                return this.basic_formatter.doFormat(ticks, opts);
            else
                return expos.map((expo) => {
                    if (abs(expo) < this.min_exponent)
                        return (0, basic_tick_formatter_1.unicode_replace)(`${base ** expo}`);
                    else
                        return (0, basic_tick_formatter_1.unicode_replace)(`${base}^${expo}`);
                });
        }
    }
    exports.LogTickFormatter = LogTickFormatter;
    _a = LogTickFormatter;
    LogTickFormatter.__name__ = "LogTickFormatter";
    (() => {
        _a.define(({ Int, Ref, Nullable }) => ({
            ticker: [Nullable(Ref(log_ticker_1.LogTicker)), null],
            min_exponent: [Int, 0],
        }));
    })();
},
/* models/tickers/log_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const adaptive_ticker_1 = require(178) /* ./adaptive_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    class LogTicker extends adaptive_ticker_1.AdaptiveTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, desired_n_ticks) {
            const num_minor_ticks = this.num_minor_ticks;
            const minor_ticks = [];
            const base = this.base;
            const log_low = Math.log(data_low) / Math.log(base);
            const log_high = Math.log(data_high) / Math.log(base);
            const log_interval = log_high - log_low;
            let ticks;
            if (!isFinite(log_interval) || log_interval == 0) {
                ticks = [];
            }
            else if (log_interval < 2) { // treat as linear ticker
                const interval = this.get_interval(data_low, data_high, desired_n_ticks);
                const start_factor = Math.floor(data_low / interval);
                const end_factor = Math.ceil(data_high / interval);
                ticks = (0, array_1.range)(start_factor, end_factor + 1)
                    .filter((factor) => factor != 0)
                    .map((factor) => factor * interval)
                    .filter((tick) => data_low <= tick && tick <= data_high);
                if (num_minor_ticks > 0 && ticks.length > 0) {
                    const minor_interval = interval / num_minor_ticks;
                    const minor_offsets = (0, array_1.range)(0, num_minor_ticks).map((i) => i * minor_interval);
                    for (const x of minor_offsets.slice(1)) {
                        minor_ticks.push(ticks[0] - x);
                    }
                    for (const tick of ticks) {
                        for (const x of minor_offsets) {
                            minor_ticks.push(tick + x);
                        }
                    }
                }
            }
            else {
                const startlog = Math.ceil(log_low * 0.999999);
                const endlog = Math.floor(log_high * 1.000001);
                const interval = Math.ceil((endlog - startlog) / 9.0);
                ticks = (0, array_1.range)(startlog - 1, endlog + 1, interval)
                    .map((i) => base ** i);
                if (num_minor_ticks > 0 && ticks.length > 0) {
                    const minor_interval = base ** interval / num_minor_ticks;
                    const minor_offsets = (0, array_1.range)(1, num_minor_ticks + 1).map((i) => i * minor_interval);
                    for (const x of minor_offsets) {
                        minor_ticks.push(ticks[0] / x);
                    }
                    minor_ticks.push(ticks[0]);
                    for (const tick of ticks) {
                        for (const x of minor_offsets) {
                            minor_ticks.push(tick * x);
                        }
                    }
                }
            }
            return {
                major: ticks.filter((tick) => data_low <= tick && tick <= data_high),
                minor: minor_ticks.filter((tick) => data_low <= tick && tick <= data_high),
            };
        }
    }
    exports.LogTicker = LogTicker;
    _a = LogTicker;
    LogTicker.__name__ = "LogTicker";
    (() => {
        _a.override({
            mantissas: [1, 5],
        });
    })();
},
/* models/axes/mercator_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const axis_1 = require(161) /* ./axis */;
    const linear_axis_1 = require(186) /* ./linear_axis */;
    const mercator_tick_formatter_1 = require(192) /* ../formatters/mercator_tick_formatter */;
    const mercator_ticker_1 = require(193) /* ../tickers/mercator_ticker */;
    class MercatorAxisView extends axis_1.AxisView {
    }
    exports.MercatorAxisView = MercatorAxisView;
    MercatorAxisView.__name__ = "MercatorAxisView";
    class MercatorAxis extends linear_axis_1.LinearAxis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MercatorAxis = MercatorAxis;
    _a = MercatorAxis;
    MercatorAxis.__name__ = "MercatorAxis";
    (() => {
        _a.prototype.default_view = MercatorAxisView;
        _a.override({
            ticker: () => new mercator_ticker_1.MercatorTicker({ dimension: "lat" }),
            formatter: () => new mercator_tick_formatter_1.MercatorTickFormatter({ dimension: "lat" }),
        });
    })();
},
/* models/formatters/mercator_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const basic_tick_formatter_1 = require(187) /* ./basic_tick_formatter */;
    const enums_1 = require(20) /* ../../core/enums */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    class MercatorTickFormatter extends basic_tick_formatter_1.BasicTickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, opts) {
            if (this.dimension == null)
                throw new Error("MercatorTickFormatter.dimension not configured");
            if (ticks.length == 0)
                return [];
            const n = ticks.length;
            const proj_ticks = new Array(n);
            if (this.dimension == "lon") {
                for (let i = 0; i < n; i++) {
                    const [lon] = projections_1.wgs84_mercator.invert(ticks[i], opts.loc);
                    proj_ticks[i] = lon;
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    const [, lat] = projections_1.wgs84_mercator.invert(opts.loc, ticks[i]);
                    proj_ticks[i] = lat;
                }
            }
            return super.doFormat(proj_ticks, opts);
        }
    }
    exports.MercatorTickFormatter = MercatorTickFormatter;
    _a = MercatorTickFormatter;
    MercatorTickFormatter.__name__ = "MercatorTickFormatter";
    (() => {
        _a.define(({ Nullable }) => ({
            dimension: [Nullable(enums_1.LatLon), null],
        }));
    })();
},
/* models/tickers/mercator_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const basic_ticker_1 = require(185) /* ./basic_ticker */;
    const enums_1 = require(20) /* ../../core/enums */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    class MercatorTicker extends basic_ticker_1.BasicTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks) {
            if (this.dimension == null) {
                throw new Error(`${this}.dimension wasn't configured`);
            }
            [data_low, data_high] = (0, projections_1.clip_mercator)(data_low, data_high, this.dimension);
            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);
        }
        _get_ticks_lon(data_low, data_high, cross_loc, desired_n_ticks) {
            const [proj_low] = projections_1.wgs84_mercator.invert(data_low, cross_loc);
            const [proj_high, proj_cross_loc] = projections_1.wgs84_mercator.invert(data_high, cross_loc);
            const proj_ticks = super.get_ticks_no_defaults(proj_low, proj_high, cross_loc, desired_n_ticks);
            const major = [];
            for (const tick of proj_ticks.major) {
                if ((0, projections_1.in_bounds)(tick, "lon")) {
                    const [lon] = projections_1.wgs84_mercator.compute(tick, proj_cross_loc);
                    major.push(lon);
                }
            }
            const minor = [];
            for (const tick of proj_ticks.minor) {
                if ((0, projections_1.in_bounds)(tick, "lon")) {
                    const [lon] = projections_1.wgs84_mercator.compute(tick, proj_cross_loc);
                    minor.push(lon);
                }
            }
            return { major, minor };
        }
        _get_ticks_lat(data_low, data_high, cross_loc, desired_n_ticks) {
            const [, proj_low] = projections_1.wgs84_mercator.invert(cross_loc, data_low);
            const [proj_cross_loc, proj_high] = projections_1.wgs84_mercator.invert(cross_loc, data_high);
            const proj_ticks = super.get_ticks_no_defaults(proj_low, proj_high, cross_loc, desired_n_ticks);
            const major = [];
            for (const tick of proj_ticks.major) {
                if ((0, projections_1.in_bounds)(tick, "lat")) {
                    const [, lat] = projections_1.wgs84_mercator.compute(proj_cross_loc, tick);
                    major.push(lat);
                }
            }
            const minor = [];
            for (const tick of proj_ticks.minor) {
                if ((0, projections_1.in_bounds)(tick, "lat")) {
                    const [, lat] = projections_1.wgs84_mercator.compute(proj_cross_loc, tick);
                    minor.push(lat);
                }
            }
            return { major, minor };
        }
    }
    exports.MercatorTicker = MercatorTicker;
    _a = MercatorTicker;
    MercatorTicker.__name__ = "MercatorTicker";
    (() => {
        _a.define(({ Nullable }) => ({
            dimension: [Nullable(enums_1.LatLon), null],
        }));
    })();
},
/* models/tickers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var adaptive_ticker_1 = require(178) /* ./adaptive_ticker */;
    __esExport("AdaptiveTicker", adaptive_ticker_1.AdaptiveTicker);
    var basic_ticker_1 = require(185) /* ./basic_ticker */;
    __esExport("BasicTicker", basic_ticker_1.BasicTicker);
    var categorical_ticker_1 = require(167) /* ./categorical_ticker */;
    __esExport("CategoricalTicker", categorical_ticker_1.CategoricalTicker);
    var composite_ticker_1 = require(180) /* ./composite_ticker */;
    __esExport("CompositeTicker", composite_ticker_1.CompositeTicker);
    var continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    __esExport("ContinuousTicker", continuous_ticker_1.ContinuousTicker);
    var datetime_ticker_1 = require(177) /* ./datetime_ticker */;
    __esExport("DatetimeTicker", datetime_ticker_1.DatetimeTicker);
    var days_ticker_1 = require(181) /* ./days_ticker */;
    __esExport("DaysTicker", days_ticker_1.DaysTicker);
    var fixed_ticker_1 = require(195) /* ./fixed_ticker */;
    __esExport("FixedTicker", fixed_ticker_1.FixedTicker);
    var log_ticker_1 = require(190) /* ./log_ticker */;
    __esExport("LogTicker", log_ticker_1.LogTicker);
    var mercator_ticker_1 = require(193) /* ./mercator_ticker */;
    __esExport("MercatorTicker", mercator_ticker_1.MercatorTicker);
    var months_ticker_1 = require(183) /* ./months_ticker */;
    __esExport("MonthsTicker", months_ticker_1.MonthsTicker);
    var single_interval_ticker_1 = require(182) /* ./single_interval_ticker */;
    __esExport("SingleIntervalTicker", single_interval_ticker_1.SingleIntervalTicker);
    var ticker_1 = require(163) /* ./ticker */;
    __esExport("Ticker", ticker_1.Ticker);
    var years_ticker_1 = require(184) /* ./years_ticker */;
    __esExport("YearsTicker", years_ticker_1.YearsTicker);
    var binned_ticker_1 = require(196) /* ./binned_ticker */;
    __esExport("BinnedTicker", binned_ticker_1.BinnedTicker);
},
/* models/tickers/fixed_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    class FixedTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks_no_defaults(_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
        get_interval(_data_low, _data_high, _desired_n_ticks) {
            return 0;
        }
        get_min_interval() {
            return 0;
        }
        get_max_interval() {
            return 0;
        }
    }
    exports.FixedTicker = FixedTicker;
    _a = FixedTicker;
    FixedTicker.__name__ = "FixedTicker";
    (() => {
        _a.define(({ Number, Arrayable }) => ({
            ticks: [Arrayable(Number), []],
            minor_ticks: [Arrayable(Number), []],
        }));
    })();
},
/* models/tickers/binned_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const ticker_1 = require(163) /* ./ticker */;
    const scanning_color_mapper_1 = require(197) /* ../mappers/scanning_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class BinnedTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks(data_low, data_high, _range, _cross_loc) {
            const { binning } = this.mapper.metrics;
            const k_low = Math.max(0, (0, arrayable_1.left_edge_index)(data_low, binning));
            const k_high = Math.min((0, arrayable_1.left_edge_index)(data_high, binning) + 1, binning.length - 1);
            const _major = [];
            for (let k = k_low; k <= k_high; k++) {
                _major.push(binning[k]);
            }
            const { num_major_ticks } = this;
            const major = [];
            const n = num_major_ticks == "auto" ? _major.length : num_major_ticks;
            const step = Math.max(1, Math.floor(_major.length / n));
            for (let i = 0; i < _major.length; i += step) {
                major.push(_major[i]);
            }
            return {
                major,
                minor: [],
            };
        }
    }
    exports.BinnedTicker = BinnedTicker;
    _a = BinnedTicker;
    BinnedTicker.__name__ = "BinnedTicker";
    (() => {
        _a.define(({ Number, Ref, Or, Auto }) => ({
            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();
    const continuous_color_mapper_1 = require(198) /* ./continuous_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class ScanningColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.binning[index];
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            if (value < scan_data.binning[0])
                return -1;
            else if (value > scan_data.binning[scan_data.binning.length - 1])
                return palette_length;
            else
                return (0, arrayable_1.left_edge_index)(value, scan_data.binning);
        }
    }
    exports.ScanningColorMapper = ScanningColorMapper;
    ScanningColorMapper.__name__ = "ScanningColorMapper";
},
/* models/mappers/continuous_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const color_mapper_1 = require(199) /* ./color_mapper */;
    const glyph_renderer_1 = require(201) /* ../renderers/glyph_renderer */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    class ContinuousColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
            this._scan_data = null;
        }
        connect_signals() {
            super.connect_signals();
            const connect_renderers = () => {
                // TODO: if already connected this will bail. However, it won't remove old connections.
                for (const [renderer] of this.domain) {
                    this.connect(renderer.view.change, () => this.update_data());
                    this.connect(renderer.data_source.selected.change, () => this.update_data());
                }
            };
            const { high, low, high_color, low_color, palette, nan_color } = this.properties;
            this.on_change([high, low, high_color, low_color, palette, nan_color], () => this.update_data());
            this.connect(this.properties.domain.change, () => connect_renderers());
            connect_renderers();
        }
        update_data() {
            const { domain, palette } = this;
            const all_data = [...this._collect(domain)];
            this._scan_data = this.scan(all_data, palette.length);
            this.metrics_change.emit();
            this.change.emit();
        }
        get metrics() {
            if (this._scan_data == null) {
                this.update_data();
            }
            return this._scan_data;
        }
        *_collect(domain) {
            for (const [renderer, fields] of domain) {
                for (const field of (0, types_1.isArray)(fields) ? fields : [fields]) {
                    if (renderer.view.properties.indices.is_unset)
                        continue;
                    const column = renderer.data_source.get_column(field);
                    if (column == null)
                        continue;
                    let array = renderer.view.indices.select(column);
                    const masked = renderer.view.masked;
                    const selected = renderer.data_source.selected.indices;
                    let subset;
                    if (masked != null && selected.length > 0)
                        subset = (0, array_1.intersection)([...masked], selected);
                    else if (masked != null)
                        subset = [...masked];
                    else if (selected.length > 0)
                        subset = selected;
                    if (subset != null) {
                        array = (0, array_1.map)(subset, (i) => array[i]);
                    }
                    if (array.length > 0 && !(0, types_1.isNumber)(array[0])) {
                        for (const subarray of array) {
                            yield* subarray;
                        }
                    }
                    else {
                        yield* array;
                    }
                }
            }
        }
        _v_compute(data, values, palette, colors) {
            const { nan_color } = colors;
            let { low_color, high_color } = colors;
            if (low_color == null)
                low_color = palette[0];
            if (high_color == null)
                high_color = palette[palette.length - 1];
            const { domain } = this;
            const all_data = !(0, array_1.is_empty)(domain) ? [...this._collect(domain)] : data;
            this._scan_data = this.scan(all_data, palette.length);
            this.metrics_change.emit();
            for (let i = 0, end = data.length; i < end; i++) {
                const d = data[i];
                if (isNaN(d))
                    values[i] = nan_color;
                else
                    values[i] = this.cmap(d, palette, low_color, high_color);
            }
        }
        _colors(conv) {
            return Object.assign(Object.assign({}, super._colors(conv)), { low_color: this.low_color != null ? conv(this.low_color) : undefined, high_color: this.high_color != null ? conv(this.high_color) : undefined });
        }
        cmap(value, palette, low_color, high_color) {
            const index = this.value_to_index(value, palette.length);
            if (index < 0)
                return low_color;
            else if (index >= palette.length)
                return high_color;
            else
                return palette[index];
        }
    }
    exports.ContinuousColorMapper = ContinuousColorMapper;
    _a = ContinuousColorMapper;
    ContinuousColorMapper.__name__ = "ContinuousColorMapper";
    (() => {
        _a.define(({ Number, String, Ref, Color, Or, Tuple, Array, 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) {
    var _a;
    __esModule();
    const mapper_1 = require(200) /* ./mapper */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const types_1 = require(24) /* ../../core/types */;
    const color_1 = require(22) /* ../../core/util/color */;
    const platform_1 = require(27) /* ../../core/util/platform */;
    const ndarray_1 = require(30) /* ../../core/util/ndarray */;
    // 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) {
        const new_palette = new Uint32Array(palette.length);
        for (let i = 0, end = palette.length; i < end; i++)
            new_palette[i] = _convert_color(palette[i]);
        return new_palette;
    }
    exports._convert_palette = _convert_palette;
    class ColorMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.metrics_change = new signaling_1.Signal0(this, "metrics_change");
        }
        v_compute(xs) {
            const values = new Array(xs.length);
            this._v_compute(xs, values, this.palette, this._colors((c) => c));
            return values;
        }
        get rgba_mapper() {
            const self = this;
            const palette = _convert_palette(this.palette);
            const colors = this._colors(_convert_color);
            return {
                v_compute(xs) {
                    const length_divisor = (0, ndarray_1.is_NDArray)(xs) && xs.dimension == 3 ? xs.shape[2] : 1;
                    const values = new types_1.ColorArray(xs.length / length_divisor);
                    self._v_compute_uint32(xs, values, palette, colors);
                    return new Uint8ClampedArray((0, platform_1.to_big_endian)(values).buffer);
                },
            };
        }
        _colors(conv) {
            return { nan_color: conv(this.nan_color) };
        }
        _v_compute_uint32(xs, values, palette, colors) {
            this._v_compute(xs, values, palette, colors);
        }
    }
    exports.ColorMapper = ColorMapper;
    _a = ColorMapper;
    ColorMapper.__name__ = "ColorMapper";
    (() => {
        _a.define(({ Color, Array }) => ({
            palette: [Array(Color)],
            nan_color: [Color, "gray"],
        }));
    })();
},
/* models/mappers/mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(86) /* ../transforms/transform */;
    class Mapper extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        compute(_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");
        }
    }
    exports.Mapper = Mapper;
    Mapper.__name__ = "Mapper";
},
/* models/renderers/glyph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const data_renderer_1 = require(202) /* ./data_renderer */;
    const line_1 = require(203) /* ../glyphs/line */;
    const patch_1 = require(213) /* ../glyphs/patch */;
    const harea_step_1 = require(214) /* ../glyphs/harea_step */;
    const harea_1 = require(217) /* ../glyphs/harea */;
    const varea_step_1 = require(218) /* ../glyphs/varea_step */;
    const varea_1 = require(219) /* ../glyphs/varea */;
    const glyph_1 = require(205) /* ../glyphs/glyph */;
    const columnar_data_source_1 = require(101) /* ../sources/columnar_data_source */;
    const cds_view_1 = require(220) /* ../sources/cds_view */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const object_1 = require(9) /* ../../core/util/object */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const eq_1 = require(26) /* ../../core/util/eq */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    const decoration_1 = require(210) /* ../graphics/decoration */;
    const selection_defaults = {
        fill: {},
        line: {},
    };
    const decimated_defaults = {
        fill: { fill_alpha: 0.3, fill_color: "grey" },
        line: { line_alpha: 0.3, line_color: "grey" },
    };
    const nonselection_defaults = {
        fill: { fill_alpha: 0.2 },
        line: {},
    };
    const muted_defaults = {
        fill: { fill_alpha: 0.2 },
        line: {},
    };
    class GlyphRendererView extends data_renderer_1.DataRendererView {
        get glyph_view() {
            return this.glyph;
        }
        *children() {
            yield* super.children();
            yield this.cds_view;
            yield this.glyph;
            yield this.selection_glyph;
            yield this.nonselection_glyph;
            if (this.hover_glyph != null)
                yield this.hover_glyph;
            yield this.muted_glyph;
            yield this.decimated_glyph;
        }
        get data_source() {
            return this.model.properties.data_source;
        }
        async lazy_initialize() {
            var _b;
            await super.lazy_initialize();
            this.cds_view = await (0, build_views_1.build_view)(this.model.view, { parent: this });
            const base_glyph = this.model.glyph;
            this.glyph = await this.build_glyph_view(base_glyph);
            const has_fill = "fill" in this.glyph.visuals;
            const has_line = "line" in this.glyph.visuals;
            const glyph_attrs = Object.assign({}, base_glyph.attributes);
            delete glyph_attrs.id;
            function mk_glyph(defaults) {
                const 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: {} });
            }
            let { selection_glyph, nonselection_glyph, hover_glyph, muted_glyph } = this.model;
            selection_glyph = glyph_from_mode(selection_defaults, selection_glyph);
            this.selection_glyph = await this.build_glyph_view(selection_glyph);
            nonselection_glyph = glyph_from_mode(nonselection_defaults, nonselection_glyph);
            this.nonselection_glyph = await this.build_glyph_view(nonselection_glyph);
            if (hover_glyph != null)
                this.hover_glyph = await this.build_glyph_view(hover_glyph);
            muted_glyph = glyph_from_mode(muted_defaults, muted_glyph);
            this.muted_glyph = await this.build_glyph_view(muted_glyph);
            const decimated_glyph = glyph_from_mode(decimated_defaults, "auto");
            this.decimated_glyph = await this.build_glyph_view(decimated_glyph);
            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();
        }
        async build_glyph_view(glyph) {
            return (0, build_views_1.build_view)(glyph, { parent: this });
        }
        remove() {
            var _b;
            this.cds_view.remove();
            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.remove();
        }
        connect_signals() {
            super.connect_signals();
            const render = () => this.request_render();
            const update = () => 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, (indices) => 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, () => {
                    // XXX: hoping for the best, assuming no in-place mutation
                    const { inspected } = this.model.data_source;
                    const current_inspected = {
                        indices: inspected.indices,
                        line_indices: inspected.line_indices,
                        multiline_indices: inspected.multiline_indices,
                        image_indices: inspected.image_indices,
                        selected_glyphs: inspected.selected_glyphs,
                    };
                    if (!(0, eq_1.is_equal)(this._previous_inspected, current_inspected)) {
                        this._previous_inspected = current_inspected;
                        render();
                    }
                });
            this.connect(this.model.properties.view.change, async () => {
                this.cds_view.remove();
                this.cds_view = await (0, build_views_1.build_view)(this.model.view, { parent: this });
                update();
            });
            this.connect(this.model.view.properties.indices.change, update);
            this.connect(this.model.view.properties.masked.change, () => this.set_visuals());
            this.connect(this.model.properties.visible.change, () => this.plot_view.invalidate_dataranges = true);
            const { x_ranges, y_ranges } = this.plot_view.frame;
            for (const [, range] of x_ranges) {
                if (range instanceof factor_range_1.FactorRange) {
                    this.connect(range.invalidate_synthetic, update);
                }
            }
            for (const [, range] of y_ranges) {
                if (range instanceof factor_range_1.FactorRange) {
                    this.connect(range.invalidate_synthetic, update);
                }
            }
            const { transformchange, exprchange } = this.model.glyph;
            this.connect(transformchange, update);
            this.connect(exprchange, update);
        }
        _update_masked_indices() {
            const masked = this.glyph.mask_data();
            this.model.view.masked = masked;
            return masked;
        }
        update_data(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
        set_data(indices) {
            const source = this.model.data_source;
            this.all_indices = this.model.view.indices;
            const { all_indices } = this;
            this.glyph.set_data(source, all_indices, indices);
            this.set_visuals();
            this._update_masked_indices();
            const { lod_factor } = this.plot_model;
            const n = this.all_indices.count;
            this.decimated = new types_1.Indices(n);
            for (let i = 0; i < n; i += lod_factor) {
                this.decimated.set(i);
            }
            this.plot_view.invalidate_dataranges = true;
        }
        set_visuals() {
            var _b, _c;
            const source = this.model.data_source;
            const { all_indices } = this;
            this.glyph.set_visuals(source, all_indices);
            this.glyph.after_visuals();
            this.decimated_glyph.set_visuals(source, all_indices);
            this.decimated_glyph.after_visuals();
            this.selection_glyph.set_visuals(source, all_indices);
            this.selection_glyph.after_visuals();
            this.nonselection_glyph.set_visuals(source, all_indices);
            this.nonselection_glyph.after_visuals();
            (_b = this.hover_glyph) === null || _b === void 0 ? void 0 : _b.set_visuals(source, all_indices);
            (_c = this.hover_glyph) === null || _c === void 0 ? void 0 : _c.after_visuals();
            this.muted_glyph.set_visuals(source, all_indices);
            this.muted_glyph.after_visuals();
        }
        get has_webgl() {
            return this.glyph.has_webgl;
        }
        _render() {
            const 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)
            const all_indices = [...this.all_indices];
            let indices = [...this._update_masked_indices()];
            const { ctx } = this.layer;
            ctx.save();
            // selected is in full set space
            const { selected } = this.model.data_source;
            const selected_full_indices = (() => {
                if (selected.is_empty())
                    return [];
                else {
                    if (this.glyph instanceof line_1.LineView && selected.selected_glyph === this.glyph.model)
                        return this.model.view.convert_indices_from_subset(indices);
                    else
                        return selected.indices;
                }
            })();
            // inspected is in full set space
            const { inspected } = this.model.data_source;
            this._previous_inspected = {
                indices: inspected.indices,
                line_indices: inspected.line_indices,
                multiline_indices: inspected.multiline_indices,
                image_indices: inspected.image_indices,
                selected_glyphs: inspected.selected_glyphs,
            };
            const inspected_full_indices = new Set((() => {
                if (inspected.is_empty())
                    return [];
                else {
                    if (inspected.selected_glyph != null)
                        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((i) => parseInt(i));
                    }
                }
            })());
            // inspected is transformed to subset space
            const inspected_subset_indices = (0, arrayable_1.filter)(indices, (i) => inspected_full_indices.has(all_indices[i]));
            const { lod_threshold } = this.plot_model;
            let glyph;
            let nonselection_glyph;
            let 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 = [...this.decimated];
                glyph = this.decimated_glyph;
                nonselection_glyph = this.decimated_glyph;
                selection_glyph = this.selection_glyph;
            }
            else {
                glyph = this.model.muted ? this.muted_glyph : this.glyph;
                nonselection_glyph = this.nonselection_glyph;
                selection_glyph = this.selection_glyph;
            }
            if (this.hover_glyph != null && inspected_subset_indices.length != 0) {
                // TODO: keep working on Indices instead of converting back and forth
                const set = new Set(indices);
                for (const i of inspected_subset_indices) {
                    set.delete(i);
                }
                indices = [...set];
            }
            // Render with no selection
            if (selected_full_indices.length == 0) {
                if (this.glyph instanceof line_1.LineView) {
                    if (this.hover_glyph != null && inspected_subset_indices.length != 0)
                        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 ||
                    this.glyph instanceof varea_step_1.VAreaStepView ||
                    this.glyph instanceof harea_step_1.HAreaStepView) {
                    if (inspected.selected_glyphs.length == 0 || this.hover_glyph == null) {
                        glyph.render(ctx, all_indices);
                    }
                    else {
                        for (const sglyph of inspected.selected_glyphs) {
                            if (sglyph == this.glyph.model)
                                this.hover_glyph.render(ctx, all_indices);
                        }
                    }
                }
                else {
                    glyph.render(ctx, indices);
                    if (this.hover_glyph != null && inspected_subset_indices.length != 0)
                        this.hover_glyph.render(ctx, inspected_subset_indices);
                }
                // Render with selection
            }
            else {
                // reset the selection mask
                const selected_mask = new Set(selected_full_indices);
                // intersect/different selection with render mask
                const selected_subset_indices = new Array();
                const nonselected_subset_indices = new Array();
                // now, selected is changed to subset space, except for Line glyph
                if (this.glyph instanceof line_1.LineView) {
                    for (const i of all_indices) {
                        if (selected_mask.has(i))
                            selected_subset_indices.push(i);
                        else
                            nonselected_subset_indices.push(i);
                    }
                }
                else {
                    for (const i of indices) {
                        if (selected_mask.has(all_indices[i]))
                            selected_subset_indices.push(i);
                        else
                            nonselected_subset_indices.push(i);
                    }
                }
                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();
        }
        get_reference_point(field, value) {
            if (field != null) {
                const array = this.model.data_source.get_column(field);
                if (array != null) {
                    for (const [key, index] of (0, object_1.entries)(this.model.view.indices_map)) {
                        if (array[parseInt(key)] == value)
                            return index;
                    }
                }
            }
            return 0;
        }
        draw_legend(ctx, x0, x1, y0, y1, field, label, index) {
            if (this.glyph.data_size == 0) {
                return;
            }
            const subset_index = (() => {
                if (index == null)
                    return this.get_reference_point(field, label);
                else {
                    const { indices_map } = this.model.view;
                    return index in indices_map ? indices_map[index] : null;
                }
            })();
            if (subset_index != null) {
                this.glyph.draw_legend_for_index(ctx, { x0, x1, y0, y1 }, subset_index);
            }
        }
        hit_test(geometry) {
            if (!this.model.visible)
                return null;
            const 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);
        }
    }
    exports.GlyphRendererView = GlyphRendererView;
    GlyphRendererView.__name__ = "GlyphRendererView";
    class GlyphRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        get_selection_manager() {
            return this.data_source.selection_manager;
        }
        add_decoration(marking, node) {
            const decoration = new decoration_1.Decoration({ marking, node });
            const glyphs = [
                this.glyph,
                this.selection_glyph,
                this.nonselection_glyph,
                this.hover_glyph,
                this.muted_glyph,
            ];
            for (const glyph of glyphs) {
                if (glyph instanceof glyph_1.Glyph)
                    glyph.decorations = [...glyph.decorations, decoration];
            }
            return decoration;
        }
    }
    exports.GlyphRenderer = GlyphRenderer;
    _a = GlyphRenderer;
    GlyphRenderer.__name__ = "GlyphRenderer";
    (() => {
        _a.prototype.default_view = GlyphRendererView;
        _a.define(({ Boolean, Auto, Or, Ref, Null, Nullable }) => ({
            data_source: [Ref(columnar_data_source_1.ColumnarDataSource)],
            view: [Ref(cds_view_1.CDSView), () => new cds_view_1.CDSView()],
            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) {
    var _a, _b;
    __esModule();
    const renderer_1 = require(74) /* ./renderer */;
    const data_range1d_1 = require(95) /* ../ranges/data_range1d */;
    class DataRendererView extends renderer_1.RendererView {
        constructor() {
            super(...arguments);
            this[_a] = true;
        }
        get xscale() {
            return this.coordinates.x_scale;
        }
        get yscale() {
            return this.coordinates.y_scale;
        }
        bounds() {
            return this.glyph_view.bounds();
        }
        log_bounds() {
            return this.glyph_view.log_bounds();
        }
    }
    exports.DataRendererView = DataRendererView;
    _a = data_range1d_1.auto_ranged;
    DataRendererView.__name__ = "DataRendererView";
    class DataRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        get selection_manager() {
            return this.get_selection_manager();
        }
    }
    exports.DataRenderer = DataRenderer;
    _b = DataRenderer;
    DataRenderer.__name__ = "DataRenderer";
    (() => {
        _b.override({
            level: "glyph",
        });
    })();
},
/* models/glyphs/line.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const utils_1 = require(211) /* ./utils */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const selection_1 = require(103) /* ../selections/selection */;
    class LineView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { LineGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(542) /* ./webgl/line_gl */));
            return LineGL;
        }
        _render(ctx, indices, data) {
            const { sx, sy } = data !== null && data !== void 0 ? data : this;
            const nonselection = this.parent.nonselection_glyph == this;
            let iprev = null;
            const gap = (i) => iprev != null && i - iprev != 1;
            let move = true;
            ctx.beginPath();
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                if (nonselection && !move && iprev != null && i - iprev > 1 && isFinite(sx[iprev + 1] + sy[iprev + 1]))
                    ctx.lineTo(sx[iprev + 1], sy[iprev + 1]); // End of previous line
                if (!isFinite(sx_i + sy_i))
                    move = true;
                else {
                    if (move || gap(i)) {
                        if (nonselection && i > 0 && isFinite(sx[i - 1] + sy[i - 1])) {
                            ctx.moveTo(sx[i - 1], sy[i - 1]); // Start of new line
                            ctx.lineTo(sx_i, sy_i);
                        }
                        else
                            ctx.moveTo(sx_i, sy_i);
                        move = false;
                    }
                    else
                        ctx.lineTo(sx_i, sy_i);
                    iprev = i;
                }
            }
            if (nonselection && !move && iprev != null) {
                const n = sx.length;
                if (iprev < n - 1 && isFinite(sx[iprev + 1] + sy[iprev + 1]))
                    ctx.lineTo(sx[iprev + 1], sy[iprev + 1]); // End of final line
            }
            this.visuals.line.set_value(ctx);
            ctx.stroke();
        }
        _hit_point(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)
            */
            const result = new selection_1.Selection();
            const point = { x: geometry.sx, y: geometry.sy };
            let shortest = 9999;
            const threshold = Math.max(2, this.line_width.value / 2);
            for (let i = 0, end = this.sx.length - 1; i < end; i++) {
                const p0 = { x: this.sx[i], y: this.sy[i] };
                const p1 = { x: this.sx[i + 1], y: this.sy[i + 1] };
                const 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;
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let val;
            let values;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                values = this._y;
            }
            else {
                val = this.renderer.xscale.invert(sx);
                values = this._x;
            }
            const indices = [];
            for (let i = 0, end = values.length - 1; i < end; i++) {
                const curr = values[i];
                const next = values[i + 1];
                if ((curr <= val && val <= next) || (next <= val && val <= curr)) {
                    indices.push(i);
                }
            }
            const result = new selection_1.Selection();
            if (indices.length != 0) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
                result.line_indices = indices;
            }
            return result;
        }
        get_interpolation_hit(i, geometry) {
            const [x2, y2, x3, y3] = [this._x[i], this._y[i], this._x[i + 1], this._y[i + 1]];
            return (0, utils_1.line_interpolation)(this.renderer, geometry, x2, y2, x3, y3);
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_line_scalar_legend)(this.visuals, ctx, bbox);
        }
    }
    exports.LineView = LineView;
    LineView.__name__ = "LineView";
    class Line extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Line = Line;
    _a = Line;
    Line.__name__ = "Line";
    (() => {
        _a.prototype.default_view = LineView;
        _a.mixins(mixins.LineScalar);
    })();
},
/* models/glyphs/xy_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const glyph_1 = require(205) /* ./glyph */;
    class XYGlyphView extends glyph_1.GlyphView {
        _project_data() {
            projections_1.inplace.project_xy(this._x, this._y);
        }
        _index_data(index) {
            const { _x, _y, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x = _x[i];
                const y = _y[i];
                index.add_point(x, y);
            }
        }
        scenterxy(i) {
            return [this.sx[i], this.sy[i]];
        }
    }
    exports.XYGlyphView = XYGlyphView;
    XYGlyphView.__name__ = "XYGlyphView";
    class XYGlyph extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.XYGlyph = XYGlyph;
    _a = XYGlyph;
    XYGlyph.__name__ = "XYGlyph";
    (() => {
        _a.define(({}) => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y: [p.YCoordinateSpec, { field: "y" }],
        }));
    })();
},
/* models/glyphs/glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const bbox = tslib_1.__importStar(require(57) /* ../../core/util/bbox */);
    const visuals = tslib_1.__importStar(require(75) /* ../../core/visuals */);
    const settings_1 = require(29) /* ../../core/settings */;
    const view_1 = require(54) /* ../../core/view */;
    const model_1 = require(50) /* ../../model */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const logging_1 = require(19) /* ../../core/logging */;
    const types_1 = require(24) /* ../../core/types */;
    const types_2 = require(8) /* ../../core/util/types */;
    const ragged_array_1 = require(206) /* ../../core/util/ragged_array */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const eq_1 = require(26) /* ../../core/util/eq */;
    const spatial_1 = require(207) /* ../../core/util/spatial */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    const selection_1 = require(103) /* ../selections/selection */;
    const decoration_1 = require(210) /* ../graphics/decoration */;
    const { abs, ceil } = Math;
    class GlyphView extends view_1.View {
        constructor() {
            super(...arguments);
            this._index = null;
            this._data_size = null;
            this._nohit_warned = new Set();
            this.decorations = new Map();
        }
        get renderer() {
            return this.parent;
        }
        get has_webgl() {
            return this.glglyph != null;
        }
        get index() {
            const { _index } = this;
            if (_index != null)
                return _index;
            else
                throw new Error(`${this}.index_data() wasn't called`);
        }
        get data_size() {
            const { base } = this;
            if (base != null) {
                return base.data_size;
            }
            else {
                const { _data_size } = this;
                if (_data_size != null)
                    return _data_size;
                else
                    throw new Error(`${this}.set_data() wasn't called`);
            }
        }
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        *children() {
            yield* super.children();
            yield* this.decorations.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await (0, build_views_1.build_views)(this.decorations, this.model.decorations, { parent: this.parent });
            const { webgl } = this.canvas;
            if (webgl != null && this.load_glglyph != null) {
                const cls = await this.load_glglyph();
                this.glglyph = new cls(webgl.regl_wrapper, this);
            }
        }
        request_render() {
            this.parent.request_render();
        }
        get canvas() {
            return this.renderer.parent.canvas_view;
        }
        render(ctx, indices, data) {
            var _b;
            if (this.glglyph != null) {
                this.glglyph.render(ctx, indices, (_b = this.base) !== null && _b !== void 0 ? _b : this);
            }
            else if (this.canvas.webgl != null && settings_1.settings.force_webgl) {
                throw new Error(`${this} doesn't support webgl rendering`);
            }
            else {
                this._render(ctx, indices, data !== null && data !== void 0 ? data : this.base);
            }
        }
        has_finished() {
            return true;
        }
        notify_finished() {
            this.renderer.notify_finished();
        }
        _bounds(bounds) {
            return bounds;
        }
        bounds() {
            return this._bounds(this.index.bbox);
        }
        log_bounds() {
            const { x0, x1 } = this.index.bounds(bbox.positive_x());
            const { y0, y1 } = this.index.bounds(bbox.positive_y());
            return this._bounds({ x0, y0, x1, y1 });
        }
        get_anchor_point(anchor, i, [sx, sy]) {
            switch (anchor) {
                case "center":
                case "center_center": {
                    const [x, y] = this.scenterxy(i, sx, sy);
                    return { x, y };
                }
                default:
                    return null;
            }
        }
        sdist(scale, pts, spans, pts_location = "edge", dilate = false) {
            const n = pts.length;
            const sdist = new types_1.ScreenArray(n);
            const compute = scale.s_compute;
            if (pts_location == "center") {
                for (let i = 0; i < n; i++) {
                    const pts_i = pts[i];
                    const halfspan_i = spans.get(i) / 2;
                    const spt0 = compute(pts_i - halfspan_i);
                    const spt1 = compute(pts_i + halfspan_i);
                    sdist[i] = abs(spt1 - spt0);
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    const pts_i = pts[i];
                    const spt0 = compute(pts_i);
                    const spt1 = compute(pts_i + spans.get(i));
                    sdist[i] = abs(spt1 - spt0);
                }
            }
            if (dilate)
                (0, arrayable_1.inplace_map)(sdist, (sd) => ceil(sd));
            return sdist;
        }
        draw_legend_for_index(_ctx, _bbox, _index) { }
        hit_test(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;
        }
        _hit_rect_against_index(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.coordinates.x_scale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.coordinates.y_scale.r_invert(sy0, sy1);
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _project_data() { }
        *_iter_visuals() {
            for (const visual of this.visuals) {
                for (const prop of visual) {
                    if (prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec)
                        yield prop;
                }
            }
        }
        set_base(base) {
            if (base != this && base instanceof this.constructor)
                this.base = base;
        }
        _configure(prop, descriptor) {
            Object.defineProperty(this, (0, types_2.isString)(prop) ? prop : prop.attr, Object.assign({ configurable: true, enumerable: true }, descriptor));
        }
        set_visuals(source, indices) {
            var _b;
            for (const prop of this._iter_visuals()) {
                const { base } = this;
                if (base != null) {
                    const base_prop = base.model.properties[prop.attr];
                    if (base_prop != null && (0, eq_1.is_equal)(prop.get_value(), base_prop.get_value())) {
                        this._configure(prop, {
                            get() { return base[`${prop.attr}`]; },
                        });
                        continue;
                    }
                }
                const uniform = prop.uniform(source).select(indices);
                this._configure(prop, { value: uniform });
            }
            for (const visual of this.visuals) {
                visual.update();
            }
            (_b = this.glglyph) === null || _b === void 0 ? void 0 : _b.set_visuals_changed();
        }
        set_data(source, indices, indices_to_update) {
            var _b;
            const { x_source, y_source } = this.renderer.coordinates;
            const visual_props = new Set(this._iter_visuals());
            this._data_size = indices.count;
            for (const prop of this.model) {
                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) {
                    const base_array = prop.array(source);
                    let array = indices.select(base_array);
                    const 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 (let i = 0; i < array.length; i++) {
                                array[i] = range.v_synthetic(array[i]);
                            }
                        }
                    }
                    let final_array;
                    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 {
                    const uniform = prop.uniform(source).select(indices);
                    this._configure(prop, { value: uniform });
                    if (prop instanceof p.DistanceSpec) {
                        const max_value = uniform.is_Scalar() ? uniform.value : (0, arrayable_1.max)(uniform.array);
                        this._configure(`max_${prop.attr}`, { value: max_value });
                    }
                }
            }
            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
            for (const decoration of this.decorations.values()) {
                decoration.marking.set_data(source, indices);
            }
            (_b = this.glglyph) === null || _b === void 0 ? void 0 : _b.set_data_changed();
            this.index_data();
        }
        _set_data(_indices) { }
        /**
         * Any data transformations that require visuals.
         */
        after_visuals() { }
        get _index_size() {
            return this.data_size;
        }
        index_data() {
            const index = new spatial_1.SpatialIndex(this._index_size);
            this._index_data(index);
            index.finish();
            this._index = index;
        }
        mask_data() {
            /** 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();
        }
        map_data() {
            var _b;
            const self = this;
            const { x_scale, y_scale } = this.renderer.coordinates;
            for (const prop of this.model) {
                if (prop instanceof p.BaseCoordinateSpec) {
                    const scale = prop.dimension == "x" ? x_scale : y_scale;
                    let array = self[`_${prop.attr}`];
                    if (array instanceof ragged_array_1.RaggedArray) {
                        const 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;
                }
            }
            this._map_data();
            (_b = this.glglyph) === null || _b === void 0 ? void 0 : _b.set_data_mapped();
        }
        // This is where specs not included in coords are computed, e.g. radius.
        _map_data() { }
    }
    exports.GlyphView = GlyphView;
    GlyphView.__name__ = "GlyphView";
    class Glyph extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Glyph = Glyph;
    _a = Glyph;
    Glyph.__name__ = "Glyph";
    (() => {
        _a.define(({ Array, Ref }) => ({
            decorations: [Array(Ref(decoration_1.Decoration)), []],
        }));
    })();
},
/* core/util/ragged_array.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const eq_1 = require(26) /* ./eq */;
    const assert_1 = require(12) /* ./assert */;
    class RaggedArray {
        constructor(offsets, array) {
            this.offsets = offsets;
            this.array = array;
        }
        [(_a = Symbol.toStringTag, eq_1.equals)](that, cmp) {
            return cmp.arrays(this.offsets, that.offsets) && cmp.arrays(this.array, that.array);
        }
        get length() {
            return this.offsets.length;
        }
        clone() {
            return new RaggedArray(this.offsets.slice(), this.array.slice());
        }
        static from(items, ctor) {
            const n = items.length;
            let offset = 0;
            const offsets = (() => {
                const offsets = new Uint32Array(n);
                for (let i = 0; i < n; i++) {
                    const 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;
            })();
            const array = new ctor(offset);
            for (let i = 0; i < n; i++) {
                array.set(items[i], offsets[i]);
            }
            return new RaggedArray(offsets, array);
        }
        *[Symbol.iterator]() {
            const { offsets, length } = this;
            for (let i = 0; i < length; i++) {
                yield this.array.subarray(offsets[i], offsets[i + 1]);
            }
        }
        _check_bounds(i) {
            (0, assert_1.assert)(0 <= i && i < this.length, `Out of bounds: 0 <= ${i} < ${this.length}`);
        }
        get(i) {
            this._check_bounds(i);
            const { offsets } = this;
            return this.array.subarray(offsets[i], offsets[i + 1]);
        }
        set(i, array) {
            this._check_bounds(i);
            this.array.set(array, this.offsets[i]);
        }
    }
    exports.RaggedArray = RaggedArray;
    RaggedArray.__name__ = "RaggedArray";
    RaggedArray[_a] = "RaggedArray";
},
/* core/util/spatial.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const flatbush_1 = tslib_1.__importDefault(require(208) /* flatbush */);
    const types_1 = require(24) /* ../types */;
    const bbox_1 = require(57) /* ./bbox */;
    function upperBound(value, arr) {
        let i = 0;
        let j = arr.length - 1;
        while (i < j) {
            const m = (i + j) >> 1;
            if (arr[m] > value) {
                j = m;
            }
            else {
                i = m + 1;
            }
        }
        return arr[i];
    }
    class _FlatBush extends flatbush_1.default {
        get boxes() {
            return this._boxes;
        }
        search_indices(minX, minY, maxX, maxY) {
            if (this._pos !== this._boxes.length) {
                throw new Error("Data not yet indexed - call index.finish().");
            }
            let nodeIndex = this._boxes.length - 4;
            const queue = [];
            const results = new types_1.Indices(this.numItems);
            while (nodeIndex !== undefined) {
                // find the end index of the node
                const end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // search through child nodes
                for (let pos = nodeIndex; pos < end; pos += 4) {
                    const index = this._indices[pos >> 2] | 0;
                    // check if node bbox intersects with query bbox
                    const nodeMinX = this._boxes[pos + 0];
                    const nodeMinY = this._boxes[pos + 1];
                    const nodeMaxX = this._boxes[pos + 2];
                    const 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;
        }
    }
    _FlatBush.__name__ = "_FlatBush";
    class SpatialIndex {
        constructor(size) {
            this.index = null;
            if (size > 0) {
                this.index = new _FlatBush(size);
            }
        }
        add_rect(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);
        }
        add_point(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);
        }
        add_empty() {
            var _a;
            (_a = this.index) === null || _a === void 0 ? void 0 : _a.add(Infinity, Infinity, -Infinity, -Infinity);
        }
        finish() {
            var _a;
            (_a = this.index) === null || _a === void 0 ? void 0 : _a.finish();
        }
        _normalize(rect) {
            let { x0, y0, x1, y1 } = rect;
            if (x0 > x1)
                [x0, x1] = [x1, x0];
            if (y0 > y1)
                [y0, y1] = [y1, y0];
            return { x0, y0, x1, y1 };
        }
        get bbox() {
            if (this.index == null)
                return (0, bbox_1.empty)();
            else {
                const { minX, minY, maxX, maxY } = this.index;
                return { x0: minX, y0: minY, x1: maxX, y1: maxY };
            }
        }
        indices(rect) {
            if (this.index == null)
                return new types_1.Indices(0);
            else {
                const { x0, y0, x1, y1 } = this._normalize(rect);
                return this.index.search_indices(x0, y0, x1, y1);
            }
        }
        bounds(rect) {
            const bounds = (0, bbox_1.empty)();
            if (this.index == null)
                return bounds;
            const { boxes } = this.index;
            for (const i of this.indices(rect)) {
                const x0 = boxes[4 * i + 0];
                const y0 = boxes[4 * i + 1];
                const x1 = boxes[4 * i + 2];
                const 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;
            }
            return bounds;
        }
    }
    exports.SpatialIndex = SpatialIndex;
    SpatialIndex.__name__ = "SpatialIndex";
},
/* flatbush/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const flatqueue_1 = tslib_1.__importDefault(require(209) /* flatqueue */);
    const ARRAY_TYPES = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
    const VERSION = 3; // serialized format version
    /** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
    class Flatbush {
        /**
         * Recreate a Flatbush index from raw `ArrayBuffer` or `SharedArrayBuffer` data.
         * @param {ArrayBuffer | SharedArrayBuffer} data
         * @returns {Flatbush} index
         */
        static from(data) {
            // @ts-expect-error duck typing array buffers
            if (!data || data.byteLength === undefined || data.buffer) {
                throw new Error('Data must be an instance of ArrayBuffer or SharedArrayBuffer.');
            }
            const [magic, versionAndType] = new Uint8Array(data, 0, 2);
            if (magic !== 0xfb) {
                throw new Error('Data does not appear to be in a Flatbush format.');
            }
            const version = versionAndType >> 4;
            if (version !== VERSION) {
                throw new Error(`Got v${version} data when expected v${VERSION}.`);
            }
            const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];
            if (!ArrayType) {
                throw new Error('Unrecognized array type.');
            }
            const [nodeSize] = new Uint16Array(data, 2, 1);
            const [numItems] = new Uint32Array(data, 4, 1);
            return new Flatbush(numItems, nodeSize, ArrayType, undefined, data);
        }
        /**
         * Create a Flatbush index that will hold a given number of items.
         * @param {number} numItems
         * @param {number} [nodeSize=16] Size of the tree node (16 by default).
         * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
         * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used to store data (`ArrayBuffer` by default).
         * @param {ArrayBuffer | SharedArrayBuffer} [data] (Only used internally)
         */
        constructor(numItems, nodeSize = 16, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {
            if (numItems === undefined)
                throw new Error('Missing required argument: numItems.');
            if (isNaN(numItems) || numItems <= 0)
                throw new Error(`Unexpected 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)
            let n = numItems;
            let 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;
            this.IndexArrayType = numNodes < 16384 ? Uint16Array : Uint32Array;
            const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
            const nodesByteSize = numNodes * 4 * this.ArrayType.BYTES_PER_ELEMENT;
            if (arrayTypeIndex < 0) {
                throw new Error(`Unexpected typed array class: ${ArrayType}.`);
            }
            // @ts-expect-error duck typing array buffers
            if (data && data.byteLength !== undefined && !data.buffer) {
                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 ArrayBufferType(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
            /** @type FlatQueue<number> */
            this._queue = new flatqueue_1.default();
        }
        /**
         * Add a given rectangle to the index.
         * @param {number} minX
         * @param {number} minY
         * @param {number} maxX
         * @param {number} maxY
         * @returns {number} A zero-based, incremental number that represents the newly added rectangle.
         */
        add(minX, minY, maxX, maxY) {
            const index = this._pos >> 2;
            const boxes = this._boxes;
            this._indices[index] = index;
            boxes[this._pos++] = minX;
            boxes[this._pos++] = minY;
            boxes[this._pos++] = maxX;
            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;
        }
        /** Perform indexing of the added rectangles. */
        finish() {
            if (this._pos >> 2 !== this.numItems) {
                throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
            }
            const boxes = this._boxes;
            if (this.numItems <= this.nodeSize) {
                // only one node, skip sorting and just fill the root box
                boxes[this._pos++] = this.minX;
                boxes[this._pos++] = this.minY;
                boxes[this._pos++] = this.maxX;
                boxes[this._pos++] = this.maxY;
                return;
            }
            const width = (this.maxX - this.minX) || 1;
            const height = (this.maxY - this.minY) || 1;
            const hilbertValues = new Uint32Array(this.numItems);
            const hilbertMax = (1 << 16) - 1;
            // map item centers into Hilbert coordinate space and calculate Hilbert values
            for (let i = 0, pos = 0; i < this.numItems; i++) {
                const minX = boxes[pos++];
                const minY = boxes[pos++];
                const maxX = boxes[pos++];
                const maxY = boxes[pos++];
                const x = Math.floor(hilbertMax * ((minX + maxX) / 2 - this.minX) / width);
                const 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, boxes, this._indices, 0, this.numItems - 1, this.nodeSize);
            // generate nodes at each tree level, bottom-up
            for (let i = 0, pos = 0; i < this._levelBounds.length - 1; i++) {
                const end = this._levelBounds[i];
                // generate a parent node for each block of consecutive <nodeSize> nodes
                while (pos < end) {
                    const nodeIndex = pos;
                    // calculate bbox for the new node
                    let nodeMinX = boxes[pos++];
                    let nodeMinY = boxes[pos++];
                    let nodeMaxX = boxes[pos++];
                    let nodeMaxY = boxes[pos++];
                    for (let j = 1; j < this.nodeSize && pos < end; j++) {
                        nodeMinX = Math.min(nodeMinX, boxes[pos++]);
                        nodeMinY = Math.min(nodeMinY, boxes[pos++]);
                        nodeMaxX = Math.max(nodeMaxX, boxes[pos++]);
                        nodeMaxY = Math.max(nodeMaxY, boxes[pos++]);
                    }
                    // add the new node to the tree data
                    this._indices[this._pos >> 2] = nodeIndex;
                    boxes[this._pos++] = nodeMinX;
                    boxes[this._pos++] = nodeMinY;
                    boxes[this._pos++] = nodeMaxX;
                    boxes[this._pos++] = nodeMaxY;
                }
            }
        }
        /**
         * Search the index by a bounding box.
         * @param {number} minX
         * @param {number} minY
         * @param {number} maxX
         * @param {number} maxY
         * @param {(index: number) => boolean} [filterFn] An optional function for filtering the results.
         * @returns {number[]} An array of indices of items intersecting or touching the given bounding box.
         */
        search(minX, minY, maxX, maxY, filterFn) {
            if (this._pos !== this._boxes.length) {
                throw new Error('Data not yet indexed - call index.finish().');
            }
            /** @type number | undefined */
            let nodeIndex = this._boxes.length - 4;
            const queue = [];
            const results = [];
            while (nodeIndex !== undefined) {
                // find the end index of the node
                const end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // search through child nodes
                for (let /** @type number */ pos = nodeIndex; pos < end; pos += 4) {
                    // 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
                    const index = this._indices[pos >> 2] | 0;
                    if (nodeIndex >= this.numItems * 4) {
                        queue.push(index); // node; add it to the search queue
                    }
                    else if (filterFn === undefined || filterFn(index)) {
                        results.push(index); // leaf item
                    }
                }
                nodeIndex = queue.pop();
            }
            return results;
        }
        /**
         * Search items in order of distance from the given point.
         * @param {number} x
         * @param {number} y
         * @param {number} [maxResults=Infinity]
         * @param {number} [maxDistance=Infinity]
         * @param {(index: number) => boolean} [filterFn] An optional function for filtering the results.
         * @returns {number[]} An array of indices of items found.
         */
        neighbors(x, y, maxResults = Infinity, maxDistance = Infinity, filterFn) {
            if (this._pos !== this._boxes.length) {
                throw new Error('Data not yet indexed - call index.finish().');
            }
            /** @type number | undefined */
            let nodeIndex = this._boxes.length - 4;
            const q = this._queue;
            const results = [];
            const maxDistSquared = maxDistance * maxDistance;
            outer: while (nodeIndex !== undefined) {
                // find the end index of the node
                const end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // add child nodes to the queue
                for (let pos = nodeIndex; pos < end; pos += 4) {
                    const index = this._indices[pos >> 2] | 0;
                    const dx = axisDist(x, this._boxes[pos], this._boxes[pos + 2]);
                    const dy = axisDist(y, this._boxes[pos + 1], this._boxes[pos + 3]);
                    const dist = dx * dx + dy * dy;
                    if (dist > maxDistSquared)
                        continue;
                    if (nodeIndex >= this.numItems * 4) {
                        q.push(index << 1, dist); // node (use even id)
                    }
                    else if (filterFn === undefined || filterFn(index)) {
                        q.push((index << 1) + 1, dist); // leaf item (use odd id)
                    }
                }
                // pop items from the queue
                // @ts-expect-error q.length check eliminates undefined values
                while (q.length && (q.peek() & 1)) {
                    const dist = q.peekValue();
                    // @ts-expect-error
                    if (dist > maxDistSquared)
                        break outer;
                    // @ts-expect-error
                    results.push(q.pop() >> 1);
                    if (results.length === maxResults)
                        break outer;
                }
                // @ts-expect-error
                nodeIndex = q.length ? q.pop() >> 1 : undefined;
            }
            q.clear();
            return results;
        }
    }
    exports.default = Flatbush;
    /**
     * 1D distance from a value to a range.
     * @param {number} k
     * @param {number} min
     * @param {number} max
     */
    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.
     * @param {number} value
     * @param {number[]} arr
     */
    function upperBound(value, arr) {
        let i = 0;
        let j = arr.length - 1;
        while (i < j) {
            const 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.
     * @param {Uint32Array} values
     * @param {InstanceType<TypedArrayConstructor>} boxes
     * @param {Uint16Array | Uint32Array} indices
     * @param {number} left
     * @param {number} right
     * @param {number} nodeSize
     */
    function sort(values, boxes, indices, left, right, nodeSize) {
        if (Math.floor(left / nodeSize) >= Math.floor(right / nodeSize))
            return;
        const pivot = values[(left + right) >> 1];
        let i = left - 1;
        let 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.
     * @param {Uint32Array} values
     * @param {InstanceType<TypedArrayConstructor>} boxes
     * @param {Uint16Array | Uint32Array} indices
     * @param {number} i
     * @param {number} j
     */
    function swap(values, boxes, indices, i, j) {
        const temp = values[i];
        values[i] = values[j];
        values[j] = temp;
        const k = 4 * i;
        const m = 4 * j;
        const a = boxes[k];
        const b = boxes[k + 1];
        const c = boxes[k + 2];
        const 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;
        const 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)
     * @param {number} x
     * @param {number} y
     */
    function hilbert(x, y) {
        let a = x ^ y;
        let b = 0xFFFF ^ a;
        let c = 0xFFFF ^ (x | y);
        let d = x & (y ^ 0xFFFF);
        let A = a | (b >> 1);
        let B = (a >> 1) ^ a;
        let C = ((c >> 1) ^ (b & (d >> 1))) ^ c;
        let 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);
        let i0 = x ^ y;
        let 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.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class FlatQueue {
        constructor() {
            this.ids = [];
            this.values = [];
            this.length = 0;
        }
        clear() {
            this.length = 0;
        }
        push(id, value) {
            let pos = this.length++;
            while (pos > 0) {
                const parent = (pos - 1) >> 1;
                const 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;
        }
        pop() {
            if (this.length === 0)
                return undefined;
            const top = this.ids[0];
            this.length--;
            if (this.length > 0) {
                const id = this.ids[0] = this.ids[this.length];
                const value = this.values[0] = this.values[this.length];
                const halfLength = this.length >> 1;
                let pos = 0;
                while (pos < halfLength) {
                    let left = (pos << 1) + 1;
                    const right = left + 1;
                    let bestIndex = this.ids[left];
                    let bestValue = this.values[left];
                    const 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;
        }
        peek() {
            if (this.length === 0)
                return undefined;
            return this.ids[0];
        }
        peekValue() {
            if (this.length === 0)
                return undefined;
            return this.values[0];
        }
        shrink() {
            this.ids.length = this.values.length = this.length;
        }
    }
    exports.default = FlatQueue;
},
/* models/graphics/decoration.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const marking_1 = require(142) /* ./marking */;
    const model_1 = require(50) /* ../../model */;
    const view_1 = require(54) /* ../../core/view */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    class DecorationView extends view_1.View {
        *children() {
            yield* super.children();
            yield this.marking;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.marking = await (0, build_views_1.build_view)(this.model.marking, { parent: this.parent });
        }
    }
    exports.DecorationView = DecorationView;
    DecorationView.__name__ = "DecorationView";
    class Decoration extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Decoration = Decoration;
    _a = Decoration;
    Decoration.__name__ = "Decoration";
    (() => {
        _a.prototype.default_view = DecorationView;
        _a.define(({ Enum, Ref }) => ({
            marking: [Ref(marking_1.Marking)],
            node: [Enum("start", "middle", "end")],
        }));
    })();
},
/* models/glyphs/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    function generic_line_scalar_legend(visuals, ctx, { x0, x1, y0, 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, { x0, x1, y0, y1 }, i) {
        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, { x0, x1, y0, y1 }) {
        var _a, _b;
        const w = Math.abs(x1 - x0);
        const dw = w * 0.1;
        const h = Math.abs(y1 - y0);
        const dh = h * 0.1;
        const sx0 = x0 + dw;
        const sx1 = x1 - dw;
        const sy0 = y0 + dh;
        const sy1 = y1 - dh;
        ctx.beginPath();
        ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        visuals.fill.apply(ctx);
        (_a = visuals.hatch) === null || _a === void 0 ? void 0 : _a.apply(ctx);
        (_b = visuals.line) === null || _b === void 0 ? void 0 : _b.apply(ctx);
    }
    exports.generic_area_scalar_legend = generic_area_scalar_legend;
    function generic_area_vector_legend(visuals, ctx, { x0, x1, y0, y1 }, i) {
        var _a, _b;
        const w = Math.abs(x1 - x0);
        const dw = w * 0.1;
        const h = Math.abs(y1 - y0);
        const dh = h * 0.1;
        const sx0 = x0 + dw;
        const sx1 = x1 - dw;
        const sy0 = y0 + dh;
        const sy1 = y1 - dh;
        ctx.beginPath();
        ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        visuals.fill.apply(ctx, i);
        (_a = visuals.hatch) === null || _a === void 0 ? void 0 : _a.apply(ctx, i);
        (_b = visuals.line) === null || _b === void 0 ? void 0 : _b.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) {
        const { sx, sy } = geometry;
        let x0, x1;
        let y0, y1;
        if (geometry.type == "point") {
            // The +/- adjustments here are to dilate the hit point into a virtual "segment" to use below
            [y0, y1] = renderer.yscale.r_invert(sy - 1, sy + 1);
            [x0, x1] = renderer.xscale.r_invert(sx - 1, sx + 1);
        }
        else {
            // The +/- adjustments here are to handle cases such as purely horizontal or vertical lines
            if (geometry.direction == "v") {
                [y0, y1] = renderer.yscale.r_invert(sy, sy);
                [x0, x1] = [Math.min(x2 - 1, x3 - 1), Math.max(x2 + 1, x3 + 1)];
            }
            else {
                [x0, x1] = renderer.xscale.r_invert(sx, sx);
                [y0, y1] = [Math.min(y2 - 1, y3 - 1), Math.max(y2 + 1, y3 + 1)];
            }
        }
        const { x, y } = hittest.check_2_segments_intersect(x0, y0, x1, y1, x2, y2, x3, y3);
        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) {
        let inside = false;
        let x1 = px[px.length - 1];
        let y1 = py[py.length - 1];
        for (let i = 0; i < px.length; i++) {
            const x2 = px[i];
            const 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) {
        const A = ((Math.cos(angle) / a) ** 2 + (Math.sin(angle) / b) ** 2);
        const B = 2 * Math.cos(angle) * Math.sin(angle) * ((1 / a) ** 2 - (1 / b) ** 2);
        const C = ((Math.cos(angle) / b) ** 2 + (Math.sin(angle) / a) ** 2);
        const eqn = A * (x - x0) ** 2 + B * (x - x0) * (y - y0) + C * (y - y0) ** 2;
        const inside = eqn <= 1;
        return inside;
    }
    exports.point_in_ellipse = point_in_ellipse;
    function dist_2_pts(p0, p1) {
        return (p0.x - p1.x) ** 2 + (p0.y - p1.y) ** 2;
    }
    exports.dist_2_pts = dist_2_pts;
    function dist_to_segment_squared(p, v, w) {
        const l2 = dist_2_pts(v, w);
        if (l2 == 0)
            return dist_2_pts(p, v);
        const 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);
        const 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
         */
        const 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 {
            let a = l0_y0 - l1_y0;
            let b = l0_x0 - l1_x0;
            const num1 = ((l1_x1 - l1_x0) * a) - ((l1_y1 - l1_y0) * b);
            const num2 = ((l0_x1 - l0_x0) * a) - ((l0_y1 - l0_y0) * b);
            a = num1 / den;
            b = num2 / den;
            const x = l0_x0 + (a * (l0_x1 - l0_x0));
            const y = l0_y0 + (a * (l0_y1 - l0_y0));
            return { hit: (a > 0 && a < 1) && (b > 0 && b < 1), x, y };
        }
    }
    exports.check_2_segments_intersect = check_2_segments_intersect;
},
/* models/glyphs/patch.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const utils_1 = require(211) /* ./utils */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const selection_1 = require(103) /* ../selections/selection */;
    class PatchView extends xy_glyph_1.XYGlyphView {
        _render(ctx, indices, data) {
            const { sx, sy } = data !== null && data !== void 0 ? data : this;
            let move = true;
            ctx.beginPath();
            for (const i of indices) {
                const sx_i = sx[i];
                const 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);
                }
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
            this.visuals.line.apply(ctx);
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_area_scalar_legend)(this.visuals, ctx, bbox);
        }
        _hit_point(geometry) {
            const 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;
        }
    }
    exports.PatchView = PatchView;
    PatchView.__name__ = "PatchView";
    class Patch extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Patch = Patch;
    _a = Patch;
    Patch.__name__ = "Patch";
    (() => {
        _a.prototype.default_view = PatchView;
        _a.mixins([mixins.LineScalar, mixins.FillScalar, mixins.HatchScalar]);
    })();
},
/* models/glyphs/harea_step.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(215) /* ./area */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const enums_1 = require(20) /* ../../core/enums */;
    const flip_step_mode_1 = require(216) /* ../../core/util/flip_step_mode */;
    const selection_1 = require(103) /* ../selections/selection */;
    class HAreaStepView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            for (let i = 0; i < this.data_size; i++) {
                const x1 = this._x1[i];
                const x2 = this._x2[i];
                const y = this._y[i];
                index.add_rect(min(x1, x2), y, max(x1, x2), y);
            }
        }
        _step_path(ctx, mode, sx, sy, from_i, to_i) {
            // Assume the path was already moved to the first point
            let prev_x = sx[from_i];
            let prev_y = sy[from_i];
            const idx_dir = from_i < to_i ? 1 : -1;
            for (let i = from_i + idx_dir; i != to_i; i += idx_dir) {
                switch (mode) {
                    case "before":
                        ctx.lineTo(sx[i], prev_y);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    case "after":
                        ctx.lineTo(prev_x, sy[i]);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    case "center":
                        {
                            const mid_y = (prev_y + sy[i]) / 2;
                            ctx.lineTo(prev_x, mid_y);
                            ctx.lineTo(sx[i], mid_y);
                            ctx.lineTo(sx[i], sy[i]);
                            break;
                        }
                }
                prev_x = sx[i];
                prev_y = sy[i];
            }
        }
        _render(ctx, _indices, data) {
            const { sx1, sx2, sy } = data !== null && data !== void 0 ? data : this;
            const forward_mode = this.model.step_mode;
            const backward_mode = (0, flip_step_mode_1.flip_step_mode)(this.model.step_mode);
            ctx.beginPath();
            ctx.moveTo(sx1[0], sy[0]);
            this._step_path(ctx, forward_mode, sx1, sy, 0, sy.length);
            this._step_path(ctx, backward_mode, sx2, sy, sy.length, -1);
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        scenterxy(i) {
            const scx = (this.sx1[i] + this.sx2[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
        _hit_point(geometry) {
            const { sx1, sx2, sy } = this;
            for (let i = 0; i < this.data_size - 1; i++) {
                let px;
                let py;
                switch (this.model.step_mode) {
                    case "before":
                        px = [sy[i], sy[i + 1], sy[i + 1], sy[i]];
                        py = [sx1[i + 1], sx1[i + 1], sx2[i + 1], sx2[i + 1]];
                        break;
                    case "after":
                        px = [sy[i], sy[i + 1], sy[i + 1], sy[i]];
                        py = [sx1[i], sx1[i], sx2[i], sx2[i]];
                        break;
                    case "center":
                        {
                            const mid_y = (sy[i] + sy[i + 1]) / 2;
                            px = [sy[i], mid_y, mid_y, sy[i + 1], sy[i + 1], mid_y, mid_y, sy[i]];
                            py = [sx1[i], sx1[i], sx1[i + 1], sx1[i + 1], sx2[i + 1], sx2[i + 1], sx2[i], sx2[i]];
                            break;
                        }
                }
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    const result = new selection_1.Selection();
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                    return result;
                }
            }
            return new selection_1.Selection();
        }
        _map_data() {
            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);
        }
    }
    exports.HAreaStepView = HAreaStepView;
    HAreaStepView.__name__ = "HAreaStepView";
    class HAreaStep extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HAreaStep = HAreaStep;
    _a = HAreaStep;
    HAreaStep.__name__ = "HAreaStep";
    (() => {
        _a.prototype.default_view = HAreaStepView;
        _a.define(({}) => ({
            x1: [p.XCoordinateSpec, { field: "x1" }],
            x2: [p.YCoordinateSpec, { field: "x2" }],
            y: [p.YCoordinateSpec, { field: "y" }],
            step_mode: [enums_1.StepMode, "before"],
        }));
    })();
},
/* models/glyphs/area.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    class AreaView extends glyph_1.GlyphView {
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_area_scalar_legend)(this.visuals, ctx, bbox);
        }
    }
    exports.AreaView = AreaView;
    AreaView.__name__ = "AreaView";
    class Area extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Area = Area;
    _a = Area;
    Area.__name__ = "Area";
    (() => {
        _a.mixins([mixins.FillScalar, mixins.HatchScalar]);
    })();
},
/* core/util/flip_step_mode.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function flip_step_mode(mode) {
        switch (mode) {
            case "before":
                return "after";
            case "after":
                return "before";
            case "center":
                return "center";
        }
    }
    exports.flip_step_mode = flip_step_mode;
},
/* models/glyphs/harea.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(215) /* ./area */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(103) /* ../selections/selection */;
    class HAreaView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x1 = this._x1[i];
                const x2 = this._x2[i];
                const y = this._y[i];
                index.add_rect(min(x1, x2), y, max(x1, x2), y);
            }
        }
        _render(ctx, _indices, data) {
            const { sx1, sx2, sy } = data !== null && data !== void 0 ? data : this;
            ctx.beginPath();
            for (let 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 (let 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);
        }
        _hit_point(geometry) {
            const L = this.sy.length;
            const result = new selection_1.Selection();
            for (let i = 0, end = L - 1; i < end; i++) {
                const sx = [this.sx1[i], this.sx1[i + 1], this.sx2[i + 1], this.sx2[i]];
                const sy = [this.sy[i], this.sy[i + 1], this.sy[i + 1], this.sy[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                    break;
                }
            }
            return result;
        }
        scenterxy(i) {
            const scx = (this.sx1[i] + this.sx2[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
        _map_data() {
            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);
        }
    }
    exports.HAreaView = HAreaView;
    HAreaView.__name__ = "HAreaView";
    class HArea extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HArea = HArea;
    _a = HArea;
    HArea.__name__ = "HArea";
    (() => {
        _a.prototype.default_view = HAreaView;
        _a.define(({}) => ({
            x1: [p.XCoordinateSpec, { field: "x1" }],
            x2: [p.XCoordinateSpec, { field: "x2" }],
            y: [p.YCoordinateSpec, { field: "y" }],
        }));
    })();
},
/* models/glyphs/varea_step.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(215) /* ./area */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const enums_1 = require(20) /* ../../core/enums */;
    const flip_step_mode_1 = require(216) /* ../../core/util/flip_step_mode */;
    const selection_1 = require(103) /* ../selections/selection */;
    class VAreaStepView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            for (let i = 0; i < this.data_size; i++) {
                const x = this._x[i];
                const y1 = this._y1[i];
                const y2 = this._y2[i];
                index.add_rect(x, min(y1, y2), x, max(y1, y2));
            }
        }
        _step_path(ctx, mode, sx, sy, from_i, to_i) {
            // Assume the path was already moved to the first point
            let prev_x = sx[from_i];
            let prev_y = sy[from_i];
            const idx_dir = from_i < to_i ? 1 : -1;
            for (let i = from_i + idx_dir; i != to_i; i += idx_dir) {
                switch (mode) {
                    case "before":
                        ctx.lineTo(prev_x, sy[i]);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    case "after":
                        ctx.lineTo(sx[i], prev_y);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    case "center":
                        {
                            const mid_x = (prev_x + sx[i]) / 2;
                            ctx.lineTo(mid_x, prev_y);
                            ctx.lineTo(mid_x, sy[i]);
                            ctx.lineTo(sx[i], sy[i]);
                            break;
                        }
                }
                prev_x = sx[i];
                prev_y = sy[i];
            }
        }
        _render(ctx, _indices, data) {
            const { sx, sy1, sy2 } = data !== null && data !== void 0 ? data : this;
            const forward_mode = this.model.step_mode;
            const backward_mode = (0, flip_step_mode_1.flip_step_mode)(this.model.step_mode);
            ctx.beginPath();
            ctx.moveTo(sx[0], sy1[0]);
            this._step_path(ctx, forward_mode, sx, sy1, 0, sx.length);
            this._step_path(ctx, backward_mode, sx, sy2, sx.length, -1);
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.sy1[i] + this.sy2[i]) / 2;
            return [scx, scy];
        }
        _hit_point(geometry) {
            const { sx, sy1, sy2 } = this;
            for (let i = 0; i < this.data_size - 1; i++) {
                let px;
                let py;
                switch (this.model.step_mode) {
                    case "before":
                        px = [sx[i], sx[i + 1], sx[i + 1], sx[i]];
                        py = [sy1[i + 1], sy1[i + 1], sy2[i + 1], sy2[i + 1]];
                        break;
                    case "after":
                        px = [sx[i], sx[i + 1], sx[i + 1], sx[i]];
                        py = [sy1[i], sy1[i], sy2[i], sy2[i]];
                        break;
                    case "center":
                        {
                            const mid_x = (sx[i] + sx[i + 1]) / 2;
                            px = [sx[i], mid_x, mid_x, sx[i + 1], sx[i + 1], mid_x, mid_x, sx[i]];
                            py = [sy1[i], sy1[i], sy1[i + 1], sy1[i + 1], sy2[i + 1], sy2[i + 1], sy2[i], sy2[i]];
                            break;
                        }
                }
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    const result = new selection_1.Selection();
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                    return result;
                }
            }
            return new selection_1.Selection();
        }
        _map_data() {
            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);
        }
    }
    exports.VAreaStepView = VAreaStepView;
    VAreaStepView.__name__ = "VAreaStepView";
    class VAreaStep extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VAreaStep = VAreaStep;
    _a = VAreaStep;
    VAreaStep.__name__ = "VAreaStep";
    (() => {
        _a.prototype.default_view = VAreaStepView;
        _a.define(({}) => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y1: [p.YCoordinateSpec, { field: "y1" }],
            y2: [p.YCoordinateSpec, { field: "y2" }],
            step_mode: [enums_1.StepMode, "before"],
        }));
    })();
},
/* models/glyphs/varea.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(215) /* ./area */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(103) /* ../selections/selection */;
    class VAreaView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x = this._x[i];
                const y1 = this._y1[i];
                const y2 = this._y2[i];
                index.add_rect(x, min(y1, y2), x, max(y1, y2));
            }
        }
        _render(ctx, _indices, data) {
            const { sx, sy1, sy2 } = data !== null && data !== void 0 ? data : this;
            ctx.beginPath();
            for (let 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 (let 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);
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.sy1[i] + this.sy2[i]) / 2;
            return [scx, scy];
        }
        _hit_point(geometry) {
            const L = this.sx.length;
            const result = new selection_1.Selection();
            for (let i = 0, end = L - 1; i < end; i++) {
                const sx = [this.sx[i], this.sx[i + 1], this.sx[i + 1], this.sx[i]];
                const sy = [this.sy1[i], this.sy1[i + 1], this.sy2[i + 1], this.sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                    break;
                }
            }
            return result;
        }
        _map_data() {
            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);
        }
    }
    exports.VAreaView = VAreaView;
    VAreaView.__name__ = "VAreaView";
    class VArea extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VArea = VArea;
    _a = VArea;
    VArea.__name__ = "VArea";
    (() => {
        _a.prototype.default_view = VAreaView;
        _a.define(({}) => ({
            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) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const view_1 = require(54) /* ../../core/view */;
    const types_1 = require(24) /* ../../core/types */;
    const filter_1 = require(221) /* ../filters/filter */;
    const all_indices_1 = require(222) /* ../filters/all_indices */;
    const intersection_filter_1 = require(223) /* ../filters/intersection_filter */;
    class CDSViewView extends view_1.View {
        initialize() {
            super.initialize();
            this.compute_indices();
        }
        connect_signals() {
            super.connect_signals();
            const { filter } = this.model.properties;
            this.on_change(filter, () => this.compute_indices());
            const connect_listeners = () => {
                const fn = () => this.compute_indices();
                const source = this.parent.data_source.get_value();
                this.connect(source.change, fn);
                this.connect(source.streaming, fn);
                this.connect(source.patching, fn);
                this.connect(source.properties.data.change, fn);
            };
            connect_listeners();
            const { data_source } = this.parent;
            this.on_change(data_source, () => {
                // TODO: disconnect
                connect_listeners();
            });
        }
        compute_indices() {
            var _b;
            // XXX: if the data source is empty, there still may be one
            // index originating from glyph's scalar values.
            const source = this.parent.data_source.get_value();
            const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
            const indices = types_1.Indices.all_set(size);
            const filtered = this.model.filter.compute_indices(source);
            indices.intersect(filtered);
            this.model.indices = indices;
            this.model._indices_map_to_subset();
        }
    }
    exports.CDSViewView = CDSViewView;
    CDSViewView.__name__ = "CDSViewView";
    class CDSView extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        _indices_map_to_subset() {
            this._indices = [...this.indices];
            this.indices_map = {};
            for (let i = 0; i < this._indices.length; i++) {
                this.indices_map[this._indices[i]] = i;
            }
        }
        convert_selection_from_subset(selection_subset) {
            return selection_subset.map((i) => this._indices[i]);
        }
        convert_selection_to_subset(selection_full) {
            return selection_full.map((i) => this.indices_map[i]);
        }
        convert_indices_from_subset(indices) {
            return indices.map((i) => this._indices[i]);
        }
        /** @deprecated */
        get filters() {
            const { filter } = this;
            if (filter instanceof intersection_filter_1.IntersectionFilter) {
                return filter.operands;
            }
            else if (filter instanceof all_indices_1.AllIndices) {
                return [];
            }
            else {
                return [filter];
            }
        }
        /** @deprecated */
        set filters(filters) {
            if (filters.length == 0) {
                this.filter = new all_indices_1.AllIndices();
            }
            else if (filters.length == 1) {
                this.filter = filters[0];
            }
            else {
                this.filter = new intersection_filter_1.IntersectionFilter({ operands: filters });
            }
        }
    }
    exports.CDSView = CDSView;
    _a = CDSView;
    CDSView.__name__ = "CDSView";
    (() => {
        _a.prototype.default_view = CDSViewView;
        _a.define(({ Ref }) => ({
            filter: [Ref(filter_1.Filter), () => new all_indices_1.AllIndices()],
        }));
        _a.internal(({ Int, Dict, Ref, Nullable }) => ({
            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();
    const model_1 = require(50) /* ../../model */;
    class Filter extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Filter = Filter;
    Filter.__name__ = "Filter";
},
/* models/filters/all_indices.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class AllIndices extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            var _a;
            const size = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            return types_1.Indices.all_set(size);
        }
    }
    exports.AllIndices = AllIndices;
    AllIndices.__name__ = "AllIndices";
},
/* models/filters/intersection_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class IntersectionFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            var _b;
            const { operands } = this;
            if (operands.length == 0) {
                const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
                return types_1.Indices.all_set(size);
            }
            else {
                const [index, ...rest] = operands.map((op) => op.compute_indices(source));
                for (const op of rest) {
                    index.intersect(op);
                }
                return index;
            }
        }
    }
    exports.IntersectionFilter = IntersectionFilter;
    _a = IntersectionFilter;
    IntersectionFilter.__name__ = "IntersectionFilter";
    (() => {
        _a.define(({ Array, Ref }) => ({
            operands: [Array(Ref(filter_1.Filter))],
        }));
    })();
},
/* models/formatters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var basic_tick_formatter_1 = require(187) /* ./basic_tick_formatter */;
    __esExport("BasicTickFormatter", basic_tick_formatter_1.BasicTickFormatter);
    var categorical_tick_formatter_1 = require(168) /* ./categorical_tick_formatter */;
    __esExport("CategoricalTickFormatter", categorical_tick_formatter_1.CategoricalTickFormatter);
    var datetime_tick_formatter_1 = require(171) /* ./datetime_tick_formatter */;
    __esExport("DatetimeTickFormatter", datetime_tick_formatter_1.DatetimeTickFormatter);
    var customjs_tick_formatter_1 = require(225) /* ./customjs_tick_formatter */;
    __esExport("CustomJSTickFormatter", customjs_tick_formatter_1.CustomJSTickFormatter);
    var log_tick_formatter_1 = require(189) /* ./log_tick_formatter */;
    __esExport("LogTickFormatter", log_tick_formatter_1.LogTickFormatter);
    var mercator_tick_formatter_1 = require(192) /* ./mercator_tick_formatter */;
    __esExport("MercatorTickFormatter", mercator_tick_formatter_1.MercatorTickFormatter);
    var numeral_tick_formatter_1 = require(226) /* ./numeral_tick_formatter */;
    __esExport("NumeralTickFormatter", numeral_tick_formatter_1.NumeralTickFormatter);
    var printf_tick_formatter_1 = require(227) /* ./printf_tick_formatter */;
    __esExport("PrintfTickFormatter", printf_tick_formatter_1.PrintfTickFormatter);
    var tick_formatter_1 = require(164) /* ./tick_formatter */;
    __esExport("TickFormatter", tick_formatter_1.TickFormatter);
},
/* models/formatters/customjs_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tick_formatter_1 = require(164) /* ./tick_formatter */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CustomJSTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        /*protected*/ _make_func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function("tick", "index", "ticks", ...this.names, code);
        }
        doFormat(ticks, _opts) {
            const cache = {};
            const func = this._make_func().bind(cache);
            return ticks.map((tick, index, ticks) => `${func(tick, index, ticks, ...this.values)}`);
        }
    }
    exports.CustomJSTickFormatter = CustomJSTickFormatter;
    _a = CustomJSTickFormatter;
    CustomJSTickFormatter.__name__ = "CustomJSTickFormatter";
    (() => {
        _a.define(({ Unknown, String, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [String, ""],
        }));
    })();
},
/* models/formatters/numeral_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const Numbro = tslib_1.__importStar(require(173) /* @bokeh/numbro */);
    const tick_formatter_1 = require(164) /* ./tick_formatter */;
    const enums_1 = require(20) /* ../../core/enums */;
    class NumeralTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        get _rounding_fn() {
            switch (this.rounding) {
                case "round":
                case "nearest":
                    return Math.round;
                case "floor":
                case "rounddown":
                    return Math.floor;
                case "ceil":
                case "roundup":
                    return Math.ceil;
            }
        }
        doFormat(ticks, _opts) {
            const { format, language, _rounding_fn } = this;
            return ticks.map((tick) => Numbro.format(tick, format, language, _rounding_fn));
        }
    }
    exports.NumeralTickFormatter = NumeralTickFormatter;
    _a = NumeralTickFormatter;
    NumeralTickFormatter.__name__ = "NumeralTickFormatter";
    (() => {
        _a.define(({ String }) => ({
            // 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) {
    var _a;
    __esModule();
    const tick_formatter_1 = require(164) /* ./tick_formatter */;
    const templating_1 = require(172) /* ../../core/util/templating */;
    class PrintfTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, _opts) {
            return ticks.map((tick) => (0, templating_1.sprintf)(this.format, tick));
        }
    }
    exports.PrintfTickFormatter = PrintfTickFormatter;
    _a = PrintfTickFormatter;
    PrintfTickFormatter.__name__ = "PrintfTickFormatter";
    (() => {
        _a.define(({ String }) => ({
            format: [String, "%s"],
        }));
    })();
},
/* models/scales/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_scale_1 = require(93) /* ./categorical_scale */;
    __esExport("CategoricalScale", categorical_scale_1.CategoricalScale);
    var composite_scale_1 = require(94) /* ./composite_scale */;
    __esExport("CompositeScale", composite_scale_1.CompositeScale);
    var continuous_scale_1 = require(91) /* ./continuous_scale */;
    __esExport("ContinuousScale", continuous_scale_1.ContinuousScale);
    var linear_interpolation_scale_1 = require(229) /* ./linear_interpolation_scale */;
    __esExport("LinearInterpolationScale", linear_interpolation_scale_1.LinearInterpolationScale);
    var linear_scale_1 = require(90) /* ./linear_scale */;
    __esExport("LinearScale", linear_scale_1.LinearScale);
    var log_scale_1 = require(92) /* ./log_scale */;
    __esExport("LogScale", log_scale_1.LogScale);
    var scale_1 = require(85) /* ./scale */;
    __esExport("Scale", scale_1.Scale);
},
/* models/scales/linear_interpolation_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const scale_1 = require(85) /* ./scale */;
    const linear_scale_1 = require(90) /* ./linear_scale */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class LinearInterpolationScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            const { source_range, target_range } = this.properties;
            if (!source_range.is_unset && !target_range.is_unset) {
                this.linear_scale = new linear_scale_1.LinearScale({
                    source_range: source_range.get_value(),
                    target_range: target_range.get_value(),
                });
            }
        }
        connect_signals() {
            super.connect_signals();
            const { source_range, target_range } = this.properties;
            this.on_change([source_range, target_range], () => {
                this.linear_scale = new linear_scale_1.LinearScale({
                    source_range: this.source_range,
                    target_range: this.target_range,
                });
            });
        }
        get s_compute() {
            throw new Error("not implemented");
        }
        get s_invert() {
            throw new Error("not implemented");
        }
        compute(x) {
            return x;
        }
        v_compute(vs) {
            const { binning } = this;
            const { start, end } = this.source_range;
            const min_val = start;
            const max_val = end;
            const n = binning.length;
            const step = (end - start) / (n - 1);
            const mapping = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                mapping[i] = start + i * step;
            }
            const vvs = (0, arrayable_1.map)(vs, (v) => {
                if (v < min_val)
                    return min_val;
                if (v > max_val)
                    return max_val;
                const k = (0, arrayable_1.left_edge_index)(v, binning);
                if (k == -1)
                    return min_val;
                if (k >= n - 1)
                    return max_val;
                const b0 = binning[k];
                const b1 = binning[k + 1];
                const c = (v - b0) / (b1 - b0);
                const m0 = mapping[k];
                const m1 = mapping[k + 1];
                return m0 + c * (m1 - m0);
            });
            return this.linear_scale.v_compute(vvs);
        }
        invert(xprime) {
            return xprime;
        }
        v_invert(xprimes) {
            return new Float64Array(xprimes);
        }
    }
    exports.LinearInterpolationScale = LinearInterpolationScale;
    _a = LinearInterpolationScale;
    LinearInterpolationScale.__name__ = "LinearInterpolationScale";
    (() => {
        _a.internal(({ Number, Arrayable, Ref }) => ({
            binning: [Arrayable(Number)],
            linear_scale: [Ref(linear_scale_1.LinearScale)],
        }));
    })();
},
/* models/ranges/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var data_range_1 = require(96) /* ./data_range */;
    __esExport("DataRange", data_range_1.DataRange);
    var data_range1d_1 = require(95) /* ./data_range1d */;
    __esExport("DataRange1d", data_range1d_1.DataRange1d);
    var factor_range_1 = require(98) /* ./factor_range */;
    __esExport("FactorRange", factor_range_1.FactorRange);
    var range_1 = require(87) /* ./range */;
    __esExport("Range", range_1.Range);
    var range1d_1 = require(88) /* ./range1d */;
    __esExport("Range1d", range1d_1.Range1d);
},
/* core/layout/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(147) /* ./types */;
    __esExport("Sizeable", types_1.Sizeable);
    __esExport("SizingPolicy", types_1.SizingPolicy);
    var layoutable_1 = require(148) /* ./layoutable */;
    __esExport("Layoutable", layoutable_1.Layoutable);
    __esExport("ContentLayoutable", layoutable_1.ContentLayoutable);
    __esExport("TextLayout", layoutable_1.TextLayout);
    __esExport("FixedLayout", layoutable_1.FixedLayout);
    var alignments_1 = require(232) /* ./alignments */;
    __esExport("HStack", alignments_1.HStack);
    __esExport("VStack", alignments_1.VStack);
    var grid_1 = require(233) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
    __esExport("Row", grid_1.Row);
    __esExport("Column", grid_1.Column);
},
/* core/layout/alignments.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layoutable_1 = require(148) /* ./layoutable */;
    const bbox_1 = require(57) /* ../util/bbox */;
    const { max, round } = Math;
    class Stack extends layoutable_1.Layoutable {
        constructor() {
            super(...arguments);
            this.children = [];
        }
        *[Symbol.iterator]() {
            yield* this.children;
        }
    }
    exports.Stack = Stack;
    Stack.__name__ = "Stack";
    class HStack extends Stack {
        _measure(_viewport) {
            let width = 0;
            let height = 0;
            for (const child of this.children) {
                const size_hint = child.measure({ width: 0, height: 0 });
                width += size_hint.width;
                height = max(height, size_hint.height);
            }
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const top = this.absolute ? outer.top : 0;
                let left = this.absolute ? outer.left : 0;
                const { height } = outer;
                for (const child of this.children) {
                    const { width } = child.measure({ width: 0, height: 0 });
                    child.set_geometry(new bbox_1.BBox({ left, width, top, height }));
                    left += width;
                }
            }
        }
    }
    exports.HStack = HStack;
    HStack.__name__ = "HStack";
    class VStack extends Stack {
        _measure(_viewport) {
            let width = 0;
            let height = 0;
            for (const child of this.children) {
                const size_hint = child.measure({ width: 0, height: 0 });
                width = max(width, size_hint.width);
                height += size_hint.height;
            }
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const left = this.absolute ? outer.left : 0;
                let top = this.absolute ? outer.top : 0;
                const { width } = outer;
                for (const child of this.children) {
                    const { height } = child.measure({ width: 0, height: 0 });
                    child.set_geometry(new bbox_1.BBox({ top, height, left, width }));
                    top += height;
                }
            }
        }
    }
    exports.VStack = VStack;
    VStack.__name__ = "VStack";
    class NodeLayout extends layoutable_1.Layoutable {
        constructor() {
            super(...arguments);
            this.children = [];
        }
        *[Symbol.iterator]() {
            yield* this.children;
        }
        _measure(viewport) {
            const { width_policy, height_policy } = this.sizing;
            const { min, max } = Math;
            let max_width = 0;
            let max_height = 0;
            for (const layout of this.children) {
                const { width, height } = layout.measure(viewport);
                max_width = max(max_width, width);
                max_height = max(max_height, height);
            }
            const width = (() => {
                const { width } = this.sizing;
                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;
                    }
                }
            })();
            const height = (() => {
                const { height } = this.sizing;
                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, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const bbox = this.absolute ? outer : outer.relative();
                const { left, right, top, bottom } = bbox;
                const vcenter = round(bbox.vcenter);
                const hcenter = round(bbox.hcenter);
                for (const layout of this.children) {
                    const { margin, halign = "start", valign = "start" } = layout.sizing;
                    const { width, height, inner } = layout.measure(outer);
                    const bbox = (() => {
                        const anchor = `${valign}_${halign}`;
                        switch (anchor) {
                            case "start_start": // "top_left"
                                return new bbox_1.BBox({ left: left + margin.left, top: top + margin.top, width, height });
                            case "start_center": // "top_center"
                                return new bbox_1.BBox({ hcenter, top: top + margin.top, width, height });
                            case "start_end": // "top_right"
                                return new bbox_1.BBox({ right: right - margin.right, top: top + margin.top, width, height });
                            case "center_start": // "center_left"
                                return new bbox_1.BBox({ left: left + margin.left, vcenter, width, height });
                            case "center_center": // "center"
                                return new bbox_1.BBox({ hcenter, vcenter, width, height });
                            case "center_end": // "center_right"
                                return new bbox_1.BBox({ right: right - margin.right, vcenter, width, height });
                            case "end_start": // "bottom_left"
                                return new bbox_1.BBox({ left: left + margin.left, bottom: bottom - margin.bottom, width, height });
                            case "end_center": // "bottom_center"
                                return new bbox_1.BBox({ hcenter, bottom: bottom - margin.bottom, width, height });
                            case "end_end": // "bottom_right"
                                return new bbox_1.BBox({ right: right - margin.right, bottom: bottom - margin.bottom, width, height });
                        }
                    })();
                    const inner_bbox = inner == null ? bbox : new bbox_1.BBox({
                        left: bbox.left + inner.left,
                        top: bbox.top + inner.top,
                        right: bbox.right - inner.right,
                        bottom: bbox.bottom - inner.bottom,
                    });
                    layout.set_geometry(bbox, inner_bbox);
                }
            }
        }
    }
    exports.NodeLayout = NodeLayout;
    NodeLayout.__name__ = "NodeLayout";
},
/* core/layout/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(147) /* ./types */;
    const layoutable_1 = require(148) /* ./layoutable */;
    const types_2 = require(8) /* ../util/types */;
    const bbox_1 = require(57) /* ../util/bbox */;
    const array_1 = require(10) /* ../util/array */;
    const { max, round } = Math;
    class DefaultMap {
        constructor(def) {
            this._map = new Map();
            this.def = def;
        }
        get(key) {
            let value = this._map.get(key);
            if (value === undefined) {
                value = this.def();
                this._map.set(key, value);
            }
            return value;
        }
        apply(key, fn) {
            const value = this.get(key);
            this._map.set(key, fn(value));
        }
    }
    exports.DefaultMap = DefaultMap;
    DefaultMap.__name__ = "DefaultMap";
    class Container {
        constructor() {
            this._items = [];
            this._nrows = 0;
            this._ncols = 0;
        }
        get size() {
            return this._items.length;
        }
        get nrows() {
            return this._nrows;
        }
        get ncols() {
            return this._ncols;
        }
        add(span, data) {
            const { r1, c1 } = span;
            this._nrows = max(this._nrows, r1 + 1);
            this._ncols = max(this._ncols, c1 + 1);
            this._items.push({ span, data });
        }
        at(r, c) {
            const selected = this._items.filter(({ span }) => {
                return span.r0 <= r && r <= span.r1 &&
                    span.c0 <= c && c <= span.c1;
            });
            return selected.map(({ data }) => data);
        }
        row(r) {
            const selected = this._items.filter(({ span }) => span.r0 <= r && r <= span.r1);
            return selected.map(({ data }) => data);
        }
        col(c) {
            const selected = this._items.filter(({ span }) => span.c0 <= c && c <= span.c1);
            return selected.map(({ data }) => data);
        }
        *[Symbol.iterator]() {
            yield* this._items;
        }
        foreach(fn) {
            for (const { span, data } of this._items) {
                fn(span, data);
            }
        }
        map(fn) {
            const result = new Container();
            for (const { span, data } of this._items) {
                result.add(span, fn(span, data));
            }
            return result;
        }
    }
    exports.Container = Container;
    Container.__name__ = "Container";
    class Grid extends layoutable_1.Layoutable {
        *[Symbol.iterator]() {
            for (const { layout } of this.items) {
                yield layout;
            }
        }
        constructor(items = []) {
            super();
            this.rows = "auto";
            this.cols = "auto";
            this.spacing = 0;
            this.items = items;
        }
        is_width_expanding() {
            if (super.is_width_expanding())
                return true;
            if (this.sizing.width_policy == "fixed")
                return false;
            const { cols } = this._state;
            return (0, array_1.some)(cols, (col) => col.policy == "max");
        }
        is_height_expanding() {
            if (super.is_height_expanding())
                return true;
            if (this.sizing.height_policy == "fixed")
                return false;
            const { rows } = this._state;
            return (0, array_1.some)(rows, (row) => row.policy == "max");
        }
        _init() {
            var _a, _b, _c, _d;
            super._init();
            const items = new Container();
            for (const { layout, row, col, row_span = 1, col_span = 1 } of this.items) {
                if (layout.sizing.visible) {
                    const r0 = row;
                    const c0 = col;
                    const r1 = row + row_span - 1;
                    const c1 = col + col_span - 1;
                    items.add({ r0, c0, r1, c1 }, layout);
                }
            }
            const { nrows, ncols } = items;
            const rows = new Array(nrows);
            for (let y = 0; y < nrows; y++) {
                const row = (() => {
                    var _a;
                    const 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;
                })();
                const align = (_a = row.align) !== null && _a !== void 0 ? _a : "auto";
                if (row.policy == "fixed")
                    rows[y] = { policy: "fixed", height: row.height, align };
                else if (row.policy == "min")
                    rows[y] = { policy: "min", align };
                else if (row.policy == "fit" || row.policy == "max")
                    rows[y] = { policy: row.policy, flex: (_b = row.flex) !== null && _b !== void 0 ? _b : 1, align };
                else {
                    if ((0, array_1.some)(items.row(y), (layout) => layout.is_height_expanding()))
                        rows[y] = { policy: "max", flex: 1, align };
                    else
                        rows[y] = { policy: "min", align };
                }
            }
            const cols = new Array(ncols);
            for (let x = 0; x < ncols; x++) {
                const col = (() => {
                    var _a;
                    const 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;
                })();
                const align = (_c = col.align) !== null && _c !== void 0 ? _c : "auto";
                if (col.policy == "fixed")
                    cols[x] = { policy: "fixed", width: col.width, align };
                else if (col.policy == "min")
                    cols[x] = { policy: "min", align };
                else if (col.policy == "fit" || col.policy == "max")
                    cols[x] = { policy: col.policy, flex: (_d = col.flex) !== null && _d !== void 0 ? _d : 1, align };
                else {
                    if ((0, array_1.some)(items.col(x), (layout) => layout.is_width_expanding()))
                        cols[x] = { policy: "max", flex: 1, align };
                    else
                        cols[x] = { policy: "min", align };
                }
            }
            const [rspacing, cspacing] = (0, types_2.isNumber)(this.spacing) ? [this.spacing, this.spacing] : this.spacing;
            this._state = { items, nrows, ncols, rows, cols, rspacing, cspacing };
        }
        _measure_totals(row_heights, col_widths) {
            const { nrows, ncols, rspacing, cspacing } = this._state;
            return {
                height: (0, array_1.sum)(row_heights) + (nrows - 1) * rspacing,
                width: (0, array_1.sum)(col_widths) + (ncols - 1) * cspacing,
            };
        }
        _measure_cells(cell_viewport) {
            const { items, nrows, ncols, rows, cols, rspacing, cspacing } = this._state;
            const row_heights = new Array(nrows);
            for (let r = 0; r < nrows; r++) {
                const row = rows[r];
                row_heights[r] = row.policy == "fixed" ? row.height : 0;
            }
            const col_widths = new Array(ncols);
            for (let c = 0; c < ncols; c++) {
                const col = cols[c];
                col_widths[c] = col.policy == "fixed" ? col.width : 0;
            }
            const size_hints = new Container();
            items.foreach((span, layout) => {
                const { r0, c0, r1, c1 } = span;
                const rspace = (r1 - r0) * rspacing;
                const cspace = (c1 - c0) * cspacing;
                let height = 0;
                for (let r = r0; r <= r1; r++) {
                    height += cell_viewport(r, c0).height;
                }
                height += rspace;
                let width = 0;
                for (let c = c0; c <= c1; c++) {
                    width += cell_viewport(r0, c).width;
                }
                width += cspace;
                const size_hint = layout.measure({ width, height });
                size_hints.add(span, { layout, size_hint });
                const size = new types_1.Sizeable(size_hint).grow_by(layout.sizing.margin);
                size.height -= rspace;
                size.width -= cspace;
                const radjustable = [];
                for (let r = r0; r <= r1; r++) {
                    const row = rows[r];
                    if (row.policy == "fixed")
                        size.height -= row.height;
                    else
                        radjustable.push(r);
                }
                if (size.height > 0) {
                    const rheight = round(size.height / radjustable.length);
                    for (const r of radjustable) {
                        row_heights[r] = max(row_heights[r], rheight);
                    }
                }
                const cadjustable = [];
                for (let c = c0; c <= c1; c++) {
                    const col = cols[c];
                    if (col.policy == "fixed")
                        size.width -= col.width;
                    else
                        cadjustable.push(c);
                }
                if (size.width > 0) {
                    const cwidth = round(size.width / cadjustable.length);
                    for (const c of cadjustable) {
                        col_widths[c] = max(col_widths[c], cwidth);
                    }
                }
            });
            const size = this._measure_totals(row_heights, col_widths);
            return { size, row_heights, col_widths, size_hints };
        }
        _measure_grid(viewport) {
            const { nrows, ncols, rows, cols, rspacing, cspacing } = this._state;
            const preferred = this._measure_cells((y, x) => {
                const row = rows[y];
                const col = cols[x];
                return {
                    width: col.policy == "fixed" ? col.width : Infinity,
                    height: row.policy == "fixed" ? row.height : Infinity,
                };
            });
            let 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;
            let height_flex = 0;
            for (let y = 0; y < nrows; y++) {
                const 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 (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy == "fit" || row.policy == "max") {
                        const 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) {
                let nadjustable = 0;
                for (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy != "fixed")
                        nadjustable++;
                }
                let overflow_height = -available_height;
                for (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy != "fixed") {
                        const height = preferred.row_heights[y];
                        const cutoff = round(overflow_height / nadjustable);
                        preferred.row_heights[y] = max(height - cutoff, 0);
                        overflow_height -= cutoff > height ? height : cutoff;
                        nadjustable--;
                    }
                }
            }
            let 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;
            let width_flex = 0;
            for (let x = 0; x < ncols; x++) {
                const 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 (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy == "fit" || col.policy == "max") {
                        const 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) {
                let nadjustable = 0;
                for (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy != "fixed")
                        nadjustable++;
                }
                let overflow_width = -available_width;
                for (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy != "fixed") {
                        const width = preferred.col_widths[x];
                        const cutoff = round(overflow_width / nadjustable);
                        preferred.col_widths[x] = max(width - cutoff, 0);
                        overflow_width -= cutoff > width ? width : cutoff;
                        nadjustable--;
                    }
                }
            }
            const { row_heights, col_widths, size_hints } = this._measure_cells((y, x) => {
                return {
                    width: preferred.col_widths[x],
                    height: preferred.row_heights[y],
                };
            });
            const size = this._measure_totals(row_heights, col_widths);
            return { size, row_heights, col_widths, size_hints };
        }
        _measure(viewport) {
            const { size } = this._measure_grid(viewport);
            return size;
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            const { nrows, ncols, rspacing, cspacing } = this._state;
            const { row_heights, col_widths, size_hints } = this._measure_grid(outer);
            const rows = this._state.rows.map((row, r) => {
                return Object.assign(Object.assign({}, row), { top: 0, height: row_heights[r], get bottom() { return this.top + this.height; } });
            });
            const cols = this._state.cols.map((col, c) => {
                return Object.assign(Object.assign({}, col), { left: 0, width: col_widths[c], get right() { return this.left + this.width; } });
            });
            const items = size_hints.map((_, item) => {
                return Object.assign(Object.assign({}, item), { outer: new bbox_1.BBox(), inner: new bbox_1.BBox() });
            });
            for (let r = 0, top = !this.absolute ? this.position.top : outer.top; r < nrows; r++) {
                const row = rows[r];
                row.top = top;
                top += row.height + rspacing;
            }
            for (let c = 0, left = !this.absolute ? this.position.left : outer.left; c < ncols; c++) {
                const col = cols[c];
                col.left = left;
                left += col.width + cspacing;
            }
            function span_width(c0, c1) {
                let width = (c1 - c0) * cspacing;
                for (let c = c0; c <= c1; c++) {
                    width += cols[c].width;
                }
                return width;
            }
            function span_height(r0, r1) {
                let height = (r1 - r0) * rspacing;
                for (let r = r0; r <= r1; r++) {
                    height += rows[r].height;
                }
                return height;
            }
            items.foreach(({ r0, c0, r1, c1 }, item) => {
                const { layout, size_hint } = item;
                const { sizing } = layout;
                const { width, height } = size_hint;
                const span = {
                    width: span_width(c0, c1),
                    height: span_height(r0, r1),
                };
                const halign = c0 == c1 && cols[c0].align != "auto" ? cols[c0].align : sizing.halign;
                const valign = r0 == r1 && rows[r0].align != "auto" ? rows[r0].align : sizing.valign;
                let 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;
                let 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, top, width, height });
            });
            const row_aligns = rows.map(() => {
                return {
                    start: new DefaultMap(() => 0),
                    end: new DefaultMap(() => 0),
                };
            });
            const col_aligns = cols.map(() => {
                return {
                    start: new DefaultMap(() => 0),
                    end: new DefaultMap(() => 0),
                };
            });
            items.foreach(({ r0, c0, r1, c1 }, { size_hint, outer }) => {
                const { inner } = size_hint;
                if (inner != null) {
                    row_aligns[r0].start.apply(outer.top, (v) => max(v, inner.top));
                    row_aligns[r1].end.apply(rows[r1].bottom - outer.bottom, (v) => max(v, inner.bottom));
                    col_aligns[c0].start.apply(outer.left, (v) => max(v, inner.left));
                    col_aligns[c1].end.apply(cols[c1].right - outer.right, (v) => max(v, inner.right));
                }
            });
            items.foreach(({ r0, c0, r1, c1 }, item) => {
                const { size_hint, outer } = item;
                const inner_bbox = (extents) => {
                    const outer_bbox = this.absolute ? outer : outer.relative();
                    const left = outer_bbox.left + extents.left;
                    const top = outer_bbox.top + extents.top;
                    const right = outer_bbox.right - extents.right;
                    const bottom = outer_bbox.bottom - extents.bottom;
                    return new bbox_1.BBox({ left, top, right, bottom });
                };
                if (size_hint.inner != null) {
                    let inner = inner_bbox(size_hint.inner);
                    //if (size_hint.align !== false) {
                    const top = row_aligns[r0].start.get(outer.top);
                    const bottom = row_aligns[r1].end.get(rows[r1].bottom - outer.bottom);
                    const left = col_aligns[c0].start.get(outer.left);
                    const right = col_aligns[c1].end.get(cols[c1].right - outer.right);
                    try {
                        inner = inner_bbox({ top, bottom, left, right });
                    }
                    catch (_a) { }
                    //}
                    item.inner = inner;
                }
                else
                    item.inner = outer;
            });
            items.foreach((_, { layout, outer, inner }) => {
                layout.set_geometry(outer, inner);
            });
        }
    }
    exports.Grid = Grid;
    Grid.__name__ = "Grid";
    class Row extends Grid {
        constructor(items) {
            super();
            this.items = items.map((item, i) => ({ layout: item, row: 0, col: i }));
            this.rows = "fit";
        }
    }
    exports.Row = Row;
    Row.__name__ = "Row";
    class Column extends Grid {
        constructor(items) {
            super();
            this.items = items.map((item, i) => ({ layout: item, row: i, col: 0 }));
            this.cols = "fit";
        }
    }
    exports.Column = Column;
    Column.__name__ = "Column";
},
/* core/layout/border.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(147) /* ./types */;
    const layoutable_1 = require(148) /* ./layoutable */;
    const bbox_1 = require(57) /* ../util/bbox */;
    class BorderLayout extends layoutable_1.Layoutable {
        constructor() {
            super(...arguments);
            this.aligns = { left: true, right: true, top: true, bottom: true };
            this.min_border = { left: 0, top: 0, right: 0, bottom: 0 };
            this.padding = { left: 0, top: 0, right: 0, bottom: 0 };
            this.center_border_width = 0;
        }
        *[Symbol.iterator]() {
            yield this.top_panel;
            yield this.bottom_panel;
            yield this.left_panel;
            yield this.right_panel;
            yield this.center_panel;
        }
        _measure(viewport) {
            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,
            });
            const left_hint = this.left_panel.measure({ width: 0, height: viewport.height });
            const left = Math.max(left_hint.width, this.min_border.left) + this.padding.left;
            const right_hint = this.right_panel.measure({ width: 0, height: viewport.height });
            const right = Math.max(right_hint.width, this.min_border.right) + this.padding.right;
            const top_hint = this.top_panel.measure({ width: viewport.width, height: 0 });
            const top = Math.max(top_hint.height, this.min_border.top) + this.padding.top;
            const bottom_hint = this.bottom_panel.measure({ width: viewport.width, height: 0 });
            const bottom = Math.max(bottom_hint.height, this.min_border.bottom) + this.padding.bottom;
            const center_viewport = new types_1.Sizeable(viewport).shrink_by({ left, right, top, bottom });
            const center = this.center_panel.measure(center_viewport);
            const width = left + center.width + right;
            const height = top + center.height + bottom;
            const align = (() => {
                const { width_policy, height_policy } = this.center_panel.sizing;
                return Object.assign(Object.assign({}, this.aligns), { fixed_width: width_policy == "fixed", fixed_height: height_policy == "fixed" });
            })();
            return { width, height, inner: { left, right, top, bottom }, align };
        }
        _set_geometry(outer, inner) {
            var _a, _b, _c, _d;
            super._set_geometry(outer, inner);
            if (this.sizing.visible) {
                this.center_panel.set_geometry(inner);
                const left_hint = this.left_panel.measure({ width: 0, height: outer.height });
                const right_hint = this.right_panel.measure({ width: 0, height: outer.height });
                const top_hint = this.top_panel.measure({ width: outer.width, height: 0 });
                const bottom_hint = this.bottom_panel.measure({ width: outer.width, height: 0 });
                const { left, top, right, bottom } = inner;
                this.top_panel.set_geometry(new bbox_1.BBox({ left, right, bottom: top, height: top_hint.height }));
                this.bottom_panel.set_geometry(new bbox_1.BBox({ left, right, top: bottom, height: bottom_hint.height }));
                this.left_panel.set_geometry(new bbox_1.BBox({ top, bottom, right: left, width: left_hint.width }));
                this.right_panel.set_geometry(new bbox_1.BBox({ top, bottom, left: right, width: right_hint.width }));
                const adjusted_inner = inner.shrink_by(this.center_border_width);
                if (this.inner_top_panel != null) {
                    const { left, right, top, width } = adjusted_inner;
                    const inner_top_hint = this.inner_top_panel.measure({ width, height: 0 });
                    this.inner_top_panel.set_geometry(new bbox_1.BBox({ left, right, top, height: inner_top_hint.height }));
                }
                if (this.inner_bottom_panel != null) {
                    const { left, right, bottom, width } = adjusted_inner;
                    const inner_bottom_hint = this.inner_bottom_panel.measure({ width, height: 0 });
                    this.inner_bottom_panel.set_geometry(new bbox_1.BBox({ left, right, bottom, height: inner_bottom_hint.height }));
                }
                if (this.inner_left_panel != null) {
                    const { top, bottom, left, height } = adjusted_inner;
                    const inner_left_hint = this.inner_left_panel.measure({ width: 0, height });
                    this.inner_left_panel.set_geometry(new bbox_1.BBox({ top, bottom, left, width: inner_left_hint.width }));
                }
                if (this.inner_right_panel != null) {
                    const { top, bottom, right, height } = adjusted_inner;
                    const inner_right_hint = this.inner_right_panel.measure({ width: 0, height });
                    this.inner_right_panel.set_geometry(new bbox_1.BBox({ top, bottom, right, width: inner_right_hint.width }));
                }
            }
            else {
                this.center_panel.set_geometry(new bbox_1.BBox());
                this.top_panel.set_geometry(new bbox_1.BBox());
                this.bottom_panel.set_geometry(new bbox_1.BBox());
                this.left_panel.set_geometry(new bbox_1.BBox());
                this.right_panel.set_geometry(new bbox_1.BBox());
                (_a = this.inner_top_panel) === null || _a === void 0 ? void 0 : _a.set_geometry(new bbox_1.BBox());
                (_b = this.inner_bottom_panel) === null || _b === void 0 ? void 0 : _b.set_geometry(new bbox_1.BBox());
                (_c = this.inner_left_panel) === null || _c === void 0 ? void 0 : _c.set_geometry(new bbox_1.BBox());
                (_d = this.inner_right_panel) === null || _d === void 0 ? void 0 : _d.set_geometry(new bbox_1.BBox());
            }
        }
    }
    exports.BorderLayout = BorderLayout;
    BorderLayout.__name__ = "BorderLayout";
},
/* models/annotations/band.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const upper_lower_1 = require(236) /* ./upper_lower */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    class BandView extends upper_lower_1.UpperLowerView {
        paint(ctx) {
            // Draw the band body
            ctx.beginPath();
            ctx.moveTo(this._lower_sx[0], this._lower_sy[0]);
            for (let 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 (let 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 (let 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 (let 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);
        }
    }
    exports.BandView = BandView;
    BandView.__name__ = "BandView";
    class Band extends upper_lower_1.UpperLower {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Band = Band;
    _a = Band;
    Band.__name__ = "Band";
    (() => {
        _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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(100) /* ./data_annotation */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class UpperLowerView extends data_annotation_1.DataAnnotationView {
        map_data() {
            const { frame } = this.plot_view;
            const dim = this.model.dimension;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const limit_scale = dim == "height" ? yscale : xscale;
            const base_scale = dim == "height" ? xscale : yscale;
            const limit_view = dim == "height" ? frame.bbox.yview : frame.bbox.xview;
            const base_view = dim == "height" ? frame.bbox.xview : frame.bbox.yview;
            const _lower_sx = (() => {
                switch (this.model.properties.lower.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._lower);
                    case "screen":
                        return limit_view.v_compute(this._lower);
                    case "data":
                        return limit_scale.v_compute(this._lower);
                }
            })();
            const _upper_sx = (() => {
                switch (this.model.properties.upper.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._upper);
                    case "screen":
                        return limit_view.v_compute(this._upper);
                    case "data":
                        return limit_scale.v_compute(this._upper);
                }
            })();
            const _base_sx = (() => {
                switch (this.model.properties.base.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._base);
                    case "screen":
                        return base_view.v_compute(this._base);
                    case "data":
                        return base_scale.v_compute(this._base);
                }
            })();
            const [i, j] = dim == "height" ? [1, 0] : [0, 1];
            const _lower = [_lower_sx, _base_sx];
            const _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];
        }
    }
    exports.UpperLowerView = UpperLowerView;
    UpperLowerView.__name__ = "UpperLowerView";
    class XOrYCoordinateSpec extends p.CoordinateSpec {
        constructor() {
            super(...arguments);
            this._value = p.unset;
        }
        get dimension() {
            return this.obj.dimension == "width" ? "x" : "y";
        }
        // XXX: a hack to make a coordinate & unit spec
        get units() {
            var _b;
            return this._value === p.unset ? "data" : (_b = this._value.units) !== null && _b !== void 0 ? _b : "data";
        }
    }
    exports.XOrYCoordinateSpec = XOrYCoordinateSpec;
    XOrYCoordinateSpec.__name__ = "XOrYCoordinateSpec";
    class UpperLower extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.UpperLower = UpperLower;
    _a = UpperLower;
    UpperLower.__name__ = "UpperLower";
    (() => {
        _a.define(() => ({
            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) {
    var _a, _b;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const data_range1d_1 = require(95) /* ../ranges/data_range1d */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const kinds_2 = require(238) /* ../common/kinds */;
    const painting_1 = require(239) /* ../common/painting */;
    const resolve = tslib_1.__importStar(require(240) /* ../common/resolve */);
    const node_1 = require(241) /* ../coordinates/node */;
    exports.EDGE_TOLERANCE = 2.5;
    const { abs } = Math;
    const Resizable = (0, kinds_1.Enum)("none", "left", "right", "top", "bottom", "x", "y", "all");
    const Movable = (0, kinds_1.Enum)("none", "x", "y", "both");
    const Limit = (0, kinds_1.Nullable)((0, kinds_1.Or)(kinds_1.Number, (0, kinds_1.Ref)(node_1.Node)));
    class BoxAnnotationView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this.bbox = new bbox_1.BBox();
            this[_a] = true;
            this._pan_state = null;
            this._pinch_state = null;
            this._is_hovered = false;
        }
        serializable_state() {
            return Object.assign(Object.assign({}, super.serializable_state()), { bbox: this.bbox.round() }); // TODO: probably round earlier
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
        }
        bounds() {
            const { left, left_units, right, right_units, top, top_units, bottom, bottom_units, } = this.model;
            const left_ok = left_units == "data" && !(left instanceof node_1.Node);
            const right_ok = right_units == "data" && !(right instanceof node_1.Node);
            const top_ok = top_units == "data" && !(top instanceof node_1.Node);
            const bottom_ok = bottom_units == "data" && !(bottom instanceof node_1.Node);
            const [x0, x1] = (() => {
                if (left_ok && right_ok)
                    return left <= right ? [left, right] : [right, left];
                else if (left_ok)
                    return [left, left];
                else if (right_ok)
                    return [right, right];
                else
                    return [NaN, NaN];
            })();
            const [y0, y1] = (() => {
                if (top_ok && bottom_ok)
                    return top <= bottom ? [top, bottom] : [bottom, top];
                else if (top_ok)
                    return [top, top];
                else if (bottom_ok)
                    return [bottom, bottom];
                else
                    return [NaN, NaN];
            })();
            return { x0, x1, y0, y1 };
        }
        log_bounds() {
            return (0, bbox_1.empty)();
        }
        get mappers() {
            function mapper(units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            }
            const overlay = this.model;
            const { x_scale, y_scale } = this.coordinates;
            const { x_view, y_view } = this.plot_view.frame.bbox;
            const { x_screen, y_screen } = this.plot_view.canvas.bbox;
            const lrtb = {
                left: mapper(overlay.left_units, x_scale, x_view, x_screen),
                right: mapper(overlay.right_units, x_scale, x_view, x_screen),
                top: mapper(overlay.top_units, y_scale, y_view, y_screen),
                bottom: mapper(overlay.bottom_units, y_scale, y_view, y_screen),
            };
            return lrtb;
        }
        _render() {
            const compute = (dim, value, mapper) => {
                return value instanceof node_1.Node ? this.resolve_node(value)[dim] : mapper.compute(value);
            };
            const { left, right, top, bottom } = this.model;
            const { mappers } = this;
            this.bbox = bbox_1.BBox.from_lrtb({
                left: compute("x", left, mappers.left),
                right: compute("x", right, mappers.right),
                top: compute("y", top, mappers.top),
                bottom: compute("y", bottom, mappers.bottom),
            });
            if (this.bbox.is_valid) {
                this._paint_box();
            }
        }
        get border_radius() {
            return resolve.border_radius(this.model.border_radius);
        }
        _paint_box() {
            const { ctx } = this.layer;
            ctx.save();
            ctx.beginPath();
            (0, painting_1.round_rect)(ctx, this.bbox, this.border_radius);
            const { _is_hovered, visuals } = this;
            const fill = _is_hovered && visuals.hover_fill.doit ? visuals.hover_fill : visuals.fill;
            const hatch = _is_hovered && visuals.hover_hatch.doit ? visuals.hover_hatch : visuals.hatch;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            fill.apply(ctx);
            hatch.apply(ctx);
            line.apply(ctx);
            ctx.restore();
        }
        interactive_bbox() {
            const tolerance = this.model.line_width + exports.EDGE_TOLERANCE;
            return this.bbox.grow_by(tolerance);
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable)
                return false;
            const bbox = this.interactive_bbox();
            return bbox.contains(sx, sy);
        }
        _hit_test(sx, sy) {
            const { left, right, bottom, top } = this.bbox;
            const tolerance = Math.max(exports.EDGE_TOLERANCE, this.model.line_width / 2);
            const dl = abs(left - sx);
            const dr = abs(right - sx);
            const dt = abs(top - sy);
            const db = abs(bottom - sy);
            const hits_left = dl < tolerance && dl < dr;
            const hits_right = dr < tolerance && dr < dl;
            const hits_top = dt < tolerance && dt < db;
            const hits_bottom = db < tolerance && db < dt;
            if (hits_top && hits_left)
                return "top_left";
            if (hits_top && hits_right)
                return "top_right";
            if (hits_bottom && hits_left)
                return "bottom_left";
            if (hits_bottom && hits_right)
                return "bottom_right";
            if (hits_left)
                return "left";
            if (hits_right)
                return "right";
            if (hits_top)
                return "top";
            if (hits_bottom)
                return "bottom";
            if (this.bbox.contains(sx, sy))
                return "area";
            return null;
        }
        get resizable() {
            const { resizable } = this.model;
            return {
                left: resizable == "left" || resizable == "x" || resizable == "all",
                right: resizable == "right" || resizable == "x" || resizable == "all",
                top: resizable == "top" || resizable == "y" || resizable == "all",
                bottom: resizable == "bottom" || resizable == "y" || resizable == "all",
            };
        }
        _can_hit(target) {
            const { left, right, top, bottom } = this.resizable;
            switch (target) {
                case "top_left": return top && left;
                case "top_right": return top && right;
                case "bottom_left": return bottom && left;
                case "bottom_right": return bottom && right;
                case "left": return left;
                case "right": return right;
                case "top": return top;
                case "bottom": return bottom;
                case "area": return this.model.movable != "none";
            }
        }
        _pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        bbox: this.bbox.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        _pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            const { mappers } = this;
            const resolve = (dim, limit, mapper) => {
                if (limit instanceof node_1.Node) {
                    return this.resolve_node(limit)[dim];
                }
                else if (limit == null) {
                    return NaN;
                }
                else {
                    return mapper.compute(limit);
                }
            };
            const slimits = bbox_1.BBox.from_lrtb({
                left: resolve("x", this.model.left_limit, mappers.left),
                right: resolve("x", this.model.right_limit, mappers.right),
                top: resolve("y", this.model.top_limit, mappers.top),
                bottom: resolve("y", this.model.bottom_limit, mappers.bottom),
            });
            const [dl, dr, dt, db] = (() => {
                const { dx, dy } = ev;
                const { target } = this._pan_state;
                const { symmetric } = this.model;
                const [Dx, Dy] = symmetric ? [-dx, -dy] : [0, 0];
                switch (target) {
                    // corners
                    case "top_left": return [dx, Dx, dy, Dy];
                    case "top_right": return [Dx, dx, dy, Dy];
                    case "bottom_left": return [dx, Dx, Dy, dy];
                    case "bottom_right": return [Dx, dx, Dy, dy];
                    // edges
                    case "left": return [dx, Dx, 0, 0];
                    case "right": return [Dx, dx, 0, 0];
                    case "top": return [0, 0, dy, Dy];
                    case "bottom": return [0, 0, Dy, dy];
                    // area
                    case "area": {
                        switch (this.model.movable) {
                            case "both": return [dx, dx, dy, dy];
                            case "x": return [dx, dx, 0, 0];
                            case "y": return [0, 0, dy, dy];
                            case "none": return [0, 0, 0, 0];
                        }
                    }
                }
            })();
            const slrtb = (() => {
                const min = (a, b) => (0, array_1.min)([a, b]);
                const sgn = (v) => v < 0 ? -1 : (v > 0 ? 1 : 0);
                const { bbox } = this._pan_state;
                let { left, right, left_sign, right_sign } = (() => {
                    const left = bbox.left + dl;
                    const right = bbox.right + dr;
                    const left_sign = sgn(dl);
                    const right_sign = sgn(dr);
                    if (left <= right) {
                        return { left, right, left_sign, right_sign };
                    }
                    else {
                        return { left: right, right: left, left_sign: right_sign, right_sign: left_sign };
                    }
                })();
                let { top, bottom, top_sign, bottom_sign } = (() => {
                    const top = bbox.top + dt;
                    const bottom = bbox.bottom + db;
                    const top_sign = sgn(dt);
                    const bottom_sign = sgn(db);
                    if (top <= bottom) {
                        return { top, bottom, top_sign, bottom_sign };
                    }
                    else {
                        return { top: bottom, bottom: top, top_sign: bottom_sign, bottom_sign: top_sign };
                    }
                })();
                const Dl = left - slimits.left;
                const Dr = slimits.right - right;
                const Dh = min(Dl < 0 ? Dl : NaN, Dr < 0 ? Dr : NaN);
                if (isFinite(Dh) && Dh < 0) {
                    left += -left_sign * (-Dh);
                    right += -right_sign * (-Dh);
                }
                const Dt = top - slimits.top;
                const Db = slimits.bottom - bottom;
                const Dv = min(Dt < 0 ? Dt : NaN, Db < 0 ? Db : NaN);
                if (isFinite(Dv) && Dv < 0) {
                    top += -top_sign * (-Dv);
                    bottom += -bottom_sign * (-Dv);
                }
                return bbox_1.BBox.from_lrtb({ left, right, top, bottom });
            })();
            const lrtb = (() => {
                const { left, right, top, bottom } = this.model;
                return {
                    left: left instanceof node_1.Node ? left : mappers.left.invert(slrtb.left),
                    right: right instanceof node_1.Node ? right : mappers.right.invert(slrtb.right),
                    top: top instanceof node_1.Node ? top : mappers.top.invert(slrtb.top),
                    bottom: bottom instanceof node_1.Node ? bottom : mappers.bottom.invert(slrtb.bottom),
                };
            })();
            this.model.update(lrtb);
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        _pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        _pinch_start(ev) {
            if (this.model.visible && this.model.editable && this.model.resizable != "none") {
                const { sx, sy } = ev;
                if (this.bbox.contains(sx, sy)) {
                    this._pinch_state = {
                        bbox: this.bbox.clone(),
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]); // TODO: pinch signal
                    return true;
                }
            }
            return false;
        }
        _pinch(ev) {
            (0, assert_1.assert)(this._pinch_state != null);
            const slrtb = (() => {
                const { scale } = ev;
                const { bbox } = this._pinch_state;
                const { left, top, right, bottom, width, height } = bbox;
                const dw = width * (scale - 1);
                const dh = height * (scale - 1);
                const { resizable } = this;
                const dl = resizable.left ? -dw / 2 : 0;
                const dr = resizable.right ? dw / 2 : 0;
                const dt = resizable.top ? -dh / 2 : 0;
                const db = resizable.bottom ? dh / 2 : 0;
                return bbox_1.BBox.from_lrtb({
                    left: left + dl,
                    right: right + dr,
                    top: top + dt,
                    bottom: bottom + db,
                });
            })();
            const lrtb = (() => {
                const { left, right, top, bottom } = this.model;
                const { mappers } = this;
                return {
                    left: left instanceof node_1.Node ? left : mappers.left.invert(slrtb.left),
                    right: right instanceof node_1.Node ? right : mappers.right.invert(slrtb.right),
                    top: top instanceof node_1.Node ? top : mappers.top.invert(slrtb.top),
                    bottom: bottom instanceof node_1.Node ? bottom : mappers.bottom.invert(slrtb.bottom),
                };
            })();
            this.model.update(lrtb);
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        _pinch_end(ev) {
            this._pinch_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line, hover_fill, hover_hatch } = this.visuals;
            return hover_line.doit || hover_fill.doit || hover_hatch.doit;
        }
        _move_start(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        _move(_ev) { }
        _move_end(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            var _c, _d;
            const target = (_d = (_c = this._pan_state) === null || _c === void 0 ? void 0 : _c.target) !== null && _d !== void 0 ? _d : this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            switch (target) {
                case "top_left": return this.model.tl_cursor;
                case "top_right": return this.model.tr_cursor;
                case "bottom_left": return this.model.bl_cursor;
                case "bottom_right": return this.model.br_cursor;
                case "left":
                case "right": return this.model.ew_cursor;
                case "top":
                case "bottom": return this.model.ns_cursor;
                case "area": {
                    switch (this.model.movable) {
                        case "both": return this.model.in_cursor;
                        case "x": return this.model.ew_cursor;
                        case "y": return this.model.ns_cursor;
                        case "none": return null;
                    }
                }
            }
        }
    }
    exports.BoxAnnotationView = BoxAnnotationView;
    _a = data_range1d_1.auto_ranged;
    BoxAnnotationView.__name__ = "BoxAnnotationView";
    class BoxAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
            this.pan = new signaling_1.Signal(this, "pan");
        }
        update({ left, right, top, bottom }) {
            this.setv({ left, right, top, bottom, visible: true });
        }
        clear() {
            this.visible = false;
        }
    }
    exports.BoxAnnotation = BoxAnnotation;
    _b = BoxAnnotation;
    BoxAnnotation.__name__ = "BoxAnnotation";
    (() => {
        _b.prototype.default_view = BoxAnnotationView;
        _b.mixins([
            mixins.Line,
            mixins.Fill,
            mixins.Hatch,
            ["hover_", mixins.Line],
            ["hover_", mixins.Fill],
            ["hover_", mixins.Hatch],
        ]);
        _b.define(({ Boolean, Number, Ref, Or }) => ({
            top: [Or(Number, Ref(node_1.Node)), () => new node_1.Node({ target: "frame", symbol: "top" })],
            bottom: [Or(Number, Ref(node_1.Node)), () => new node_1.Node({ target: "frame", symbol: "bottom" })],
            left: [Or(Number, Ref(node_1.Node)), () => new node_1.Node({ target: "frame", symbol: "left" })],
            right: [Or(Number, Ref(node_1.Node)), () => new node_1.Node({ target: "frame", symbol: "right" })],
            top_units: [enums_1.CoordinateUnits, "data"],
            bottom_units: [enums_1.CoordinateUnits, "data"],
            left_units: [enums_1.CoordinateUnits, "data"],
            right_units: [enums_1.CoordinateUnits, "data"],
            top_limit: [Limit, null],
            bottom_limit: [Limit, null],
            left_limit: [Limit, null],
            right_limit: [Limit, null],
            border_radius: [kinds_2.BorderRadius, 0],
            editable: [Boolean, false],
            resizable: [Resizable, "all"],
            movable: [Movable, "both"],
            symmetric: [Boolean, false],
        }));
        _b.internal(({ String }) => ({
            tl_cursor: [String, "nwse-resize"],
            tr_cursor: [String, "nesw-resize"],
            bl_cursor: [String, "nesw-resize"],
            br_cursor: [String, "nwse-resize"],
            ew_cursor: [String, "ew-resize"],
            ns_cursor: [String, "ns-resize"],
            in_cursor: [String, "move"],
        }));
        _b.override({
            fill_color: "#fff9ba",
            fill_alpha: 0.4,
            line_color: "#cccccc",
            line_alpha: 0.3,
            hover_fill_color: null,
            hover_fill_alpha: 0.4,
            hover_line_color: null,
            hover_line_alpha: 0.3,
        });
    })();
},
/* models/common/kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const enums = tslib_1.__importStar(require(20) /* ../../core/enums */);
    exports.Length = (0, kinds_1.NonNegative)(kinds_1.Int);
    const XY = (type) => (0, kinds_1.PartialStruct)({ x: type, y: type });
    const LRTB = (type) => (0, kinds_1.PartialStruct)({ left: type, right: type, top: type, bottom: type });
    exports.Anchor = ((0, kinds_1.Or)(enums.Anchor, (0, kinds_1.Tuple)((0, kinds_1.Or)(enums.Align, enums.HAlign, kinds_1.Percent), (0, kinds_1.Or)(enums.Align, enums.VAlign, kinds_1.Percent))));
    exports.TextAnchor = (0, kinds_1.Or)(exports.Anchor, kinds_1.Auto);
    exports.Padding = ((0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length), XY(exports.Length), (0, kinds_1.Tuple)(exports.Length, exports.Length, exports.Length, exports.Length), LRTB(exports.Length)));
    exports.BorderRadius = ((0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length, exports.Length, exports.Length), (0, kinds_1.PartialStruct)({
        top_left: exports.Length,
        top_right: exports.Length,
        bottom_right: exports.Length,
        bottom_left: exports.Length,
    })));
    exports.Index = (0, kinds_1.NonNegative)(kinds_1.Int);
    exports.Span = (0, kinds_1.NonNegative)(kinds_1.Int);
    const GridChild = (child) => (0, kinds_1.Tuple)((0, kinds_1.Ref)(child), exports.Index, exports.Index, (0, kinds_1.Opt)(exports.Span), (0, kinds_1.Opt)(exports.Span));
    exports.GridChild = GridChild;
    exports.GridSpacing = (0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length));
    exports.TrackAlign = (0, kinds_1.Enum)("start", "center", "end", "auto");
    exports.TrackSize = kinds_1.String;
    exports.TrackSizing = (0, kinds_1.PartialStruct)({ size: exports.TrackSize, align: exports.TrackAlign });
    exports.TrackSizingLike = (0, kinds_1.Or)(exports.TrackSize, exports.TrackSizing);
    exports.TracksSizing = (0, kinds_1.Or)(exports.TrackSizingLike, (0, kinds_1.Array)(exports.TrackSizingLike), (0, kinds_1.Map)(kinds_1.Int, exports.TrackSizingLike));
},
/* models/common/painting.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function round_rect(ctx, bbox, border_radius) {
        /**
         * Create a path for a rect with rounded corners.
         *
         * From https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-roundrect.
         */
        let { top_left, top_right, bottom_right, bottom_left } = border_radius;
        if (top_left != 0 || top_right != 0 || bottom_right != 0 || bottom_left != 0) {
            const { left, right, top, bottom, width, height } = bbox;
            const scale = Math.min(width / (top_left + top_right), height / (top_right + bottom_right), width / (bottom_right + bottom_left), height / (top_left + bottom_left));
            if (scale < 1.0) {
                top_left *= scale;
                top_right *= scale;
                bottom_right *= scale;
                bottom_left *= scale;
            }
            ctx.moveTo(left + top_left, top);
            ctx.lineTo(right - top_right, top);
            if (top_right != 0) {
                ctx.arcTo(right, top, right, top + top_right, top_right);
            }
            ctx.lineTo(right, bottom - bottom_right);
            if (bottom_right != 0) {
                ctx.arcTo(right, bottom, right - bottom_right, bottom, bottom_right);
            }
            ctx.lineTo(left + bottom_left, bottom);
            if (bottom_left != 0) {
                ctx.arcTo(left, bottom, left, bottom - bottom_left, bottom_left);
            }
            ctx.lineTo(left, top + top_left);
            if (top_left != 0) {
                ctx.arcTo(left, top, left + top_left, top, top_left);
            }
            ctx.closePath();
        }
        else {
            const { left, top, width, height } = bbox;
            ctx.rect(left, top, width, height);
        }
    }
    exports.round_rect = round_rect;
},
/* models/common/resolve.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    function anchor(anchor) {
        if ((0, types_1.isString)(anchor)) {
            switch (anchor) {
                case "top_left": return { x: 0.0, y: 0.0 };
                case "top":
                case "top_center": return { x: 0.5, y: 0.0 };
                case "top_right": return { x: 1.0, y: 0.0 };
                case "right":
                case "center_right": return { x: 1.0, y: 0.5 };
                case "bottom_right": return { x: 1.0, y: 1.0 };
                case "bottom":
                case "bottom_center": return { x: 0.5, y: 1.0 };
                case "bottom_left": return { x: 0.0, y: 1.0 };
                case "left":
                case "center_left": return { x: 0.0, y: 0.5 };
                case "center":
                case "center_center": return { x: 0.5, y: 0.5 };
            }
        }
        else {
            const x_anchor = (() => {
                const [x_anchor] = anchor;
                switch (x_anchor) {
                    case "start":
                    case "left": return 0.0;
                    case "center": return 0.5;
                    case "end":
                    case "right": return 1.0;
                    default:
                        return x_anchor;
                }
            })();
            const y_anchor = (() => {
                const [, y_anchor] = anchor;
                switch (y_anchor) {
                    case "start":
                    case "top": return 0.0;
                    case "center": return 0.5;
                    case "end":
                    case "bottom": return 1.0;
                    default:
                        return y_anchor;
                }
            })();
            return { x: x_anchor, y: y_anchor };
        }
    }
    exports.anchor = anchor;
    function text_anchor(text_anchor, align, baseline) {
        if (text_anchor != "auto") {
            return anchor(text_anchor);
        }
        else {
            const x_anchor = (() => {
                switch (align) {
                    case "left": return "start";
                    case "center": return "center";
                    case "right": return "end";
                }
            })();
            const y_anchor = (() => {
                switch (baseline) {
                    case "alphabetic":
                    case "ideographic":
                    case "hanging":
                        return "center";
                    case "top": return "start";
                    case "middle": return "center";
                    case "bottom": return "end";
                }
            })();
            return anchor([x_anchor, y_anchor]);
        }
    }
    exports.text_anchor = text_anchor;
    function padding(padding) {
        if ((0, types_1.isNumber)(padding)) {
            return { left: padding, right: padding, top: padding, bottom: padding };
        }
        else if ((0, types_1.isPlainObject)(padding)) {
            if ("x" in padding || "y" in padding) {
                const { x = 0, y = 0 } = padding;
                return { left: x, right: x, top: y, bottom: y };
            }
            else if ("left" in padding || "right" in padding || "top" in padding || "bottom" in padding) {
                const { left = 0, right = 0, top = 0, bottom = 0 } = padding;
                return { left, right, top, bottom };
            }
            else {
                (0, assert_1.unreachable)(); // TODO: TypeScript 4.9
            }
        }
        else {
            if (padding.length == 2) {
                const [x = 0, y = 0] = padding;
                return { left: x, right: x, top: y, bottom: y };
            }
            else {
                const [left = 0, right = 0, top = 0, bottom = 0] = padding;
                return { left, right, top, bottom };
            }
        }
    }
    exports.padding = padding;
    function border_radius(border_radius) {
        var _a, _b, _c, _d;
        if ((0, types_1.isNumber)(border_radius)) {
            return {
                top_left: border_radius,
                top_right: border_radius,
                bottom_right: border_radius,
                bottom_left: border_radius,
            };
        }
        else if ((0, types_1.isPlainObject)(border_radius)) {
            return {
                top_left: (_a = border_radius.top_left) !== null && _a !== void 0 ? _a : 0,
                top_right: (_b = border_radius.top_right) !== null && _b !== void 0 ? _b : 0,
                bottom_right: (_c = border_radius.bottom_right) !== null && _c !== void 0 ? _c : 0,
                bottom_left: (_d = border_radius.bottom_left) !== null && _d !== void 0 ? _d : 0,
            };
        }
        else {
            const [top_left = 0, top_right = 0, bottom_right = 0, bottom_left = 0] = border_radius;
            return { top_left, top_right, bottom_right, bottom_left };
        }
    }
    exports.border_radius = border_radius;
},
/* models/coordinates/node.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const coordinate_1 = require(242) /* ./coordinate */;
    const model_1 = require(50) /* ../../model */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    exports.ImplicitTarget = (0, kinds_1.Enum)("canvas", "plot", "frame", "parent");
    exports.NodeTarget = (0, kinds_1.Or)((0, kinds_1.Ref)(model_1.Model), exports.ImplicitTarget);
    class BoxNodes {
        constructor(target, frozen = false) {
            this._left = null;
            this._right = null;
            this._top = null;
            this._bottom = null;
            this.target = target;
            this.frozen = frozen;
        }
        _node(symbol) {
            const { target, frozen } = this;
            const node = new Node({ target, symbol });
            if (frozen) {
                this[`_${symbol}`] = node;
            }
            return node;
        }
        get left() {
            var _b;
            return (_b = this._left) !== null && _b !== void 0 ? _b : this._node("left");
        }
        get right() {
            var _b;
            return (_b = this._right) !== null && _b !== void 0 ? _b : this._node("right");
        }
        get top() {
            var _b;
            return (_b = this._top) !== null && _b !== void 0 ? _b : this._node("top");
        }
        get bottom() {
            var _b;
            return (_b = this._bottom) !== null && _b !== void 0 ? _b : this._node("bottom");
        }
        freeze() {
            return new BoxNodes(this.target, true);
        }
    }
    exports.BoxNodes = BoxNodes;
    BoxNodes.__name__ = "BoxNodes";
    class Node extends coordinate_1.Coordinate {
        constructor(attrs) {
            super(attrs);
        }
        static get frame() {
            return this._frame_nodes;
        }
        static get canvas() {
            return this._canvas_nodes;
        }
    }
    exports.Node = Node;
    _a = Node;
    Node.__name__ = "Node";
    (() => {
        _a.define(({ String, Int }) => ({
            target: [exports.NodeTarget],
            symbol: [String],
            offset: [Int, 0],
        }));
    })();
    Node._frame_nodes = new BoxNodes("frame");
    Node._canvas_nodes = new BoxNodes("canvas");
},
/* models/coordinates/coordinate.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class Coordinate extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Coordinate = Coordinate;
    Coordinate.__name__ = "Coordinate";
},
/* models/annotations/color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const base_color_bar_1 = require(143) /* ./base_color_bar */;
    const axes_1 = require(160) /* ../axes */;
    const formatters_1 = require(224) /* ../formatters */;
    const color_mapper_1 = require(199) /* ../mappers/color_mapper */;
    const mappers_1 = require(244) /* ../mappers */;
    const ranges_1 = require(230) /* ../ranges */;
    const scales_1 = require(228) /* ../scales */;
    const tickers_1 = require(194) /* ../tickers */;
    const array_1 = require(10) /* ../../core/util/array */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class ColorBarView extends base_color_bar_1.BaseColorBarView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.color_mapper.change, async () => {
                this._title_view.remove();
                this._axis_view.remove();
                this.initialize();
                await this.lazy_initialize();
                this.plot_view.invalidate_layout();
            });
            this.connect(this.model.color_mapper.metrics_change, () => this._metrics_changed());
            this.connect(this.model.properties.display_low.change, () => this._metrics_changed());
            this.connect(this.model.properties.display_high.change, () => this._metrics_changed());
        }
        get color_mapper() {
            // Color mapper that is used to render this colorbar.
            let mapper = this.model.color_mapper;
            if (mapper instanceof mappers_1.WeightedStackColorMapper)
                mapper = mapper.alpha_mapper;
            return mapper;
        }
        update_layout() {
            super.update_layout();
            this._set_canvas_image();
        }
        _create_axis() {
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.CategoricalColorMapper)
                return new axes_1.CategoricalAxis();
            else if (color_mapper instanceof mappers_1.LogColorMapper)
                return new axes_1.LogAxis();
            else
                return new axes_1.LinearAxis();
        }
        _create_formatter() {
            const { color_mapper } = this;
            if (this._ticker instanceof tickers_1.LogTicker)
                return new formatters_1.LogTickFormatter();
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper)
                return new formatters_1.CategoricalTickFormatter();
            else
                return new formatters_1.BasicTickFormatter();
        }
        _create_major_range() {
            /*
            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).
            */
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.CategoricalColorMapper)
                return new ranges_1.FactorRange({ factors: color_mapper.factors });
            else if (color_mapper instanceof mappers_1.ContinuousColorMapper) {
                const { min, max } = this._continuous_metrics(color_mapper);
                return new ranges_1.Range1d({ start: min, end: max });
            }
            else
                (0, assert_1.unreachable)();
        }
        _create_major_scale() {
            const { color_mapper } = this;
            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)
                return new scales_1.LinearInterpolationScale({ binning: this._scanning_binning(color_mapper) });
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper)
                return new scales_1.CategoricalScale();
            else
                (0, assert_1.unreachable)();
        }
        _create_ticker() {
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.LogColorMapper)
                return new tickers_1.LogTicker();
            else if (color_mapper instanceof mappers_1.ScanningColorMapper)
                return new tickers_1.BinnedTicker({ mapper: color_mapper });
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper)
                return new tickers_1.CategoricalTicker();
            else
                return new tickers_1.BasicTicker();
        }
        // Return min and max metrics of ContinuousColorMapper, modified to account
        // for low and high display cutoffs.
        _continuous_metrics(color_mapper) {
            const { display_low, display_high } = this.model;
            let { min, max } = color_mapper.metrics;
            if (display_high != null && display_low != null && display_high < display_low) {
                // Empty color bar.
                this._index_low = 0;
                this._index_high = -1;
                return { min: NaN, max: NaN };
            }
            this._index_high = null;
            if (display_high != null) {
                const palette_length = color_mapper.palette.length;
                const index_high = color_mapper.value_to_index(display_high, palette_length);
                if (index_high < palette_length - 1) {
                    this._index_high = index_high;
                    max = color_mapper.index_to_value(index_high + 1);
                }
            }
            this._index_low = null;
            if (display_low != null) {
                const index_low = color_mapper.value_to_index(display_low, color_mapper.palette.length);
                if (index_low > 0) {
                    this._index_low = index_low;
                    min = color_mapper.index_to_value(index_low);
                }
            }
            return { min, max };
        }
        _get_major_size_factor() {
            return this.color_mapper.palette.length;
        }
        _metrics_changed() {
            const range = this._major_range;
            const scale = this._major_scale;
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.ScanningColorMapper && scale instanceof scales_1.LinearInterpolationScale) {
                const binning = this._scanning_binning(color_mapper);
                scale.binning = binning;
                // Update the frame's LinearInterpolationScale and Range1d as they are
                // different objects to this._major_scale and this._major_range.
                const vertical = this.orientation == "vertical";
                const frame_scale = vertical ? this._frame.y_scale : this._frame.x_scale;
                if (frame_scale instanceof scales_1.LinearInterpolationScale) {
                    frame_scale.binning = binning;
                    const frame_range = vertical ? this._frame.y_range : this._frame.x_range;
                    if (frame_range instanceof ranges_1.Range1d) {
                        frame_range.start = binning[0];
                        frame_range.end = binning[binning.length - 1];
                    }
                }
            }
            else if (color_mapper instanceof mappers_1.ContinuousColorMapper && range instanceof ranges_1.Range1d) {
                const { min, max } = this._continuous_metrics(color_mapper);
                range.setv({ start: min, end: max });
            }
            this._set_canvas_image();
            this.plot_view.request_layout(); // this.request_render()
        }
        _paint_colors(ctx, bbox) {
            const { x, y, width, height } = bbox;
            ctx.save();
            ctx.globalAlpha = this.model.scale_alpha;
            if (this._image != null) {
                ctx.imageSmoothingEnabled = false;
                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();
        }
        // Return binning array of ScanningColorMapper, modified to account for low
        // and high display cutoffs.
        _scanning_binning(color_mapper) {
            let { binning, force_low_cutoff } = color_mapper.metrics;
            const { display_high } = this.model;
            let { display_low } = this.model;
            if (force_low_cutoff && (display_low == null || color_mapper.metrics.min > display_low)) {
                // ScanningColorMapper overrides display_low, for example when EqHistColorMapper
                // uses rescale_discrete_levels=True.
                display_low = color_mapper.metrics.min;
            }
            if (display_high != null && display_low != null && display_high < display_low) {
                // Empty color bar.
                this._index_low = 0;
                this._index_high = -1;
                return [NaN];
            }
            this._index_high = null;
            if (display_high != null) {
                const index_high = color_mapper.value_to_index(display_high, binning.length);
                if (index_high < binning.length - 1)
                    this._index_high = index_high;
            }
            this._index_low = null;
            if (display_low != null) {
                const index_low = color_mapper.value_to_index(display_low, binning.length);
                if (index_low > 0) {
                    this._index_low = index_low;
                }
            }
            if (this._index_low != null || this._index_high != null) {
                // Slice binning array.
                const start = this._index_low != null ? this._index_low : 0;
                const end = this._index_high != null ? this._index_high + 1 : binning.length - 1;
                const n = end - start + 1;
                if (n > 0) {
                    const new_binning = new Array(n);
                    for (let i = 0; i < n; i++)
                        new_binning[i] = binning[i + start];
                    binning = new_binning;
                }
                else
                    binning = [NaN];
            }
            return binning;
        }
        _set_canvas_image() {
            const { orientation } = this;
            let { palette } = this.color_mapper;
            if (this._index_high != null || this._index_low != null) {
                palette = palette.slice(this._index_low != null ? this._index_low : 0, this._index_high != null ? this._index_high + 1 : palette.length);
            }
            if (palette.length < 1) {
                // Early exit for empty color bar.
                this._image = null;
                return;
            }
            if (orientation == "vertical")
                palette = (0, array_1.reversed)(palette);
            const [w, h] = (() => {
                if (orientation == "vertical")
                    return [1, palette.length];
                else
                    return [palette.length, 1];
            })();
            const canvas = this._image = document.createElement("canvas");
            canvas.width = w;
            canvas.height = h;
            const image_ctx = canvas.getContext("2d");
            const 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.
            const cmap = new mappers_1.LinearColorMapper({ palette }).rgba_mapper;
            const buf8 = cmap.v_compute((0, array_1.range)(0, palette.length));
            image_data.data.set(buf8);
            image_ctx.putImageData(image_data, 0, 0);
        }
    }
    exports.ColorBarView = ColorBarView;
    ColorBarView.__name__ = "ColorBarView";
    class ColorBar extends base_color_bar_1.BaseColorBar {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ColorBar = ColorBar;
    _a = ColorBar;
    ColorBar.__name__ = "ColorBar";
    (() => {
        _a.prototype.default_view = ColorBarView;
        _a.define(({ Nullable, Number, Ref }) => ({
            color_mapper: [Ref(color_mapper_1.ColorMapper)],
            display_low: [Nullable(Number), null],
            display_high: [Nullable(Number), null],
        }));
    })();
},
/* models/mappers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_color_mapper_1 = require(245) /* ./categorical_color_mapper */;
    __esExport("CategoricalColorMapper", categorical_color_mapper_1.CategoricalColorMapper);
    var categorical_marker_mapper_1 = require(247) /* ./categorical_marker_mapper */;
    __esExport("CategoricalMarkerMapper", categorical_marker_mapper_1.CategoricalMarkerMapper);
    var categorical_pattern_mapper_1 = require(248) /* ./categorical_pattern_mapper */;
    __esExport("CategoricalPatternMapper", categorical_pattern_mapper_1.CategoricalPatternMapper);
    var continuous_color_mapper_1 = require(198) /* ./continuous_color_mapper */;
    __esExport("ContinuousColorMapper", continuous_color_mapper_1.ContinuousColorMapper);
    var color_mapper_1 = require(199) /* ./color_mapper */;
    __esExport("ColorMapper", color_mapper_1.ColorMapper);
    var linear_color_mapper_1 = require(249) /* ./linear_color_mapper */;
    __esExport("LinearColorMapper", linear_color_mapper_1.LinearColorMapper);
    var log_color_mapper_1 = require(250) /* ./log_color_mapper */;
    __esExport("LogColorMapper", log_color_mapper_1.LogColorMapper);
    var scanning_color_mapper_1 = require(197) /* ./scanning_color_mapper */;
    __esExport("ScanningColorMapper", scanning_color_mapper_1.ScanningColorMapper);
    var eqhist_color_mapper_1 = require(251) /* ./eqhist_color_mapper */;
    __esExport("EqHistColorMapper", eqhist_color_mapper_1.EqHistColorMapper);
    var stack_color_mapper_1 = require(252) /* ./stack_color_mapper */;
    __esExport("StackColorMapper", stack_color_mapper_1.StackColorMapper);
    var weighted_stack_color_mapper_1 = require(253) /* ./weighted_stack_color_mapper */;
    __esExport("WeightedStackColorMapper", weighted_stack_color_mapper_1.WeightedStackColorMapper);
},
/* models/mappers/categorical_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const categorical_mapper_1 = require(246) /* ./categorical_mapper */;
    const color_mapper_1 = require(199) /* ./color_mapper */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    class CategoricalColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(data, values, palette, { nan_color }) {
            (0, categorical_mapper_1.cat_v_compute)(data, this.factors, palette, values, this.start, this.end, nan_color);
        }
    }
    exports.CategoricalColorMapper = CategoricalColorMapper;
    _a = CategoricalColorMapper;
    CategoricalColorMapper.__name__ = "CategoricalColorMapper";
    (() => {
        _a.define(({ Number, Nullable }) => ({
            factors: [factor_range_1.FactorSeq],
            start: [Number, 0],
            end: [Nullable(Number), null],
        }));
    })();
},
/* models/mappers/categorical_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const types_1 = require(8) /* ../../core/util/types */;
    function _cat_equals(a, b) {
        if (a.length != b.length) {
            return false;
        }
        const n = a.length;
        for (let i = 0; i < n; 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) {
        let i = 0;
        for (const item of data) {
            let key;
            if (!(0, types_1.isArray)(item)) {
                key = (0, arrayable_1.index_of)(factors, item);
            }
            else {
                const d = item.slice(start, end !== null && end !== void 0 ? end : undefined);
                if (d.length == 1) {
                    key = (0, arrayable_1.index_of)(factors, d[0]);
                }
                else {
                    key = (0, arrayable_1.find_index)(factors, (x) => _cat_equals(x, d));
                }
            }
            const value = key in targets ? targets[key] : extra_value;
            values[i++] = value;
        }
    }
    exports.cat_v_compute = cat_v_compute;
},
/* models/mappers/categorical_marker_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const categorical_mapper_1 = require(246) /* ./categorical_mapper */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    const mapper_1 = require(200) /* ./mapper */;
    const enums_1 = require(20) /* ../../core/enums */;
    class CategoricalMarkerMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        v_compute(xs) {
            const 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;
        }
    }
    exports.CategoricalMarkerMapper = CategoricalMarkerMapper;
    _a = CategoricalMarkerMapper;
    CategoricalMarkerMapper.__name__ = "CategoricalMarkerMapper";
    (() => {
        _a.define(({ Number, Array, Nullable }) => ({
            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) {
    var _a;
    __esModule();
    const categorical_mapper_1 = require(246) /* ./categorical_mapper */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    const mapper_1 = require(200) /* ./mapper */;
    const enums_1 = require(20) /* ../../core/enums */;
    class CategoricalPatternMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        v_compute(xs) {
            const 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;
        }
    }
    exports.CategoricalPatternMapper = CategoricalPatternMapper;
    _a = CategoricalPatternMapper;
    CategoricalPatternMapper.__name__ = "CategoricalPatternMapper";
    (() => {
        _a.define(({ Number, Array, Nullable }) => ({
            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();
    const continuous_color_mapper_1 = require(198) /* ./continuous_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const math_1 = require(11) /* ../../core/util/math */;
    class LinearColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        scan(data, n) {
            const low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            const high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            const norm_factor = 1 / (high - low);
            const normed_interval = 1 / n;
            return { max: high, min: low, norm_factor, normed_interval };
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.min + scan_data.normed_interval * index / scan_data.norm_factor;
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            // This handles the edge case where value == high, since the code below maps
            // values exactly equal to high to palette.length when it should be one less.
            if (value == scan_data.max)
                return palette_length - 1;
            const normed_value = (value - scan_data.min) * scan_data.norm_factor;
            const index = Math.floor(normed_value / scan_data.normed_interval);
            return (0, math_1.clamp)(index, -1, palette_length);
        }
    }
    exports.LinearColorMapper = LinearColorMapper;
    LinearColorMapper.__name__ = "LinearColorMapper";
},
/* models/mappers/log_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(198) /* ./continuous_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const math_1 = require(11) /* ../../core/util/math */;
    class LogColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        scan(data, n) {
            const low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            const high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            const scale = n / Math.log(high / low); // subtract the low offset
            return { max: high, min: low, scale };
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.min * Math.exp(index / scan_data.scale);
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            // This handles the edge case where value == high, since the code below maps
            // values exactly equal to high to palette.length when it should be one less.
            if (value == scan_data.max)
                return palette_length - 1;
            else if (value > scan_data.max)
                return palette_length;
            else if (value < scan_data.min)
                return -1;
            const log = Math.log(value / scan_data.min);
            const index = Math.floor(log * scan_data.scale);
            return (0, math_1.clamp)(index, -1, palette_length);
        }
    }
    exports.LogColorMapper = LogColorMapper;
    LogColorMapper.__name__ = "LogColorMapper";
},
/* models/mappers/eqhist_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const scanning_color_mapper_1 = require(197) /* ./scanning_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    class EqHistColorMapper extends scanning_color_mapper_1.ScanningColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        // Public for unit tests
        /*protected*/ scan(data, n) {
            const low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            const high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            const nbins = this.bins;
            const eq_bin_edges = (0, array_1.linspace)(low, high, nbins + 1);
            const full_hist = (0, arrayable_1.bin_counts)(data, eq_bin_edges);
            // Remove empty bins from histogram to make interpolation more accurate and faster
            // 1) Count non-zeros
            let nhist = 0;
            for (let i = 0; i < nbins; i++) {
                if (full_hist[i] != 0)
                    nhist++;
            }
            // 2) Remove zeros, leaving extra element at beginning for rescale_discrete_levels
            const hist = new Array(nhist + 1);
            const eq_bin_centers = new Array(nhist + 1);
            for (let i = 0, j = 1; i < nbins; i++) {
                if (full_hist[i] != 0) {
                    hist[j] = full_hist[i];
                    eq_bin_centers[j] = (eq_bin_edges[i] + eq_bin_edges[i + 1]) / 2;
                    j++;
                }
            }
            hist[0] = 0;
            eq_bin_centers[0] = 2 * eq_bin_centers[1] - eq_bin_centers[nhist];
            // CDF scaled from 0 to 1 except for first value
            const cdf = (0, array_1.cumsum)(hist);
            const lo = cdf[1];
            const diff = cdf[nhist] - lo;
            for (let i = 1; i <= nhist; i++)
                cdf[i] = (cdf[i] - lo) / diff;
            cdf[0] = -1.0;
            let { rescale_discrete_levels } = this;
            let lower_span = 0;
            if (rescale_discrete_levels) {
                const discrete_levels = nhist;
                // Straight line y = mx + c through (2, 1.5) and (100, 1) where
                // x is number of discrete_levels and y is lower span limit.
                const m = -0.5 / 98.0; // (y[1] - y[0]) / (x[1] - x[0])
                const c = 1.5 - 2 * m; // y[0] - m*x[0]
                const multiple = m * discrete_levels + c;
                if (multiple > 1)
                    lower_span = 1 - multiple;
                else
                    rescale_discrete_levels = false;
            }
            // Color bin boundaries are equally spaced in CDF
            const cdf_bins = (0, array_1.linspace)(lower_span, 1, n + 1);
            const binning = (0, arrayable_1.interpolate)(cdf_bins, cdf, eq_bin_centers);
            // Ensure binning limits are correct
            let force_low_cutoff = false;
            if (rescale_discrete_levels) {
                const low_cutoff_index = (0, arrayable_1.sorted_index)(binning, low);
                // This index satisfies: binning[low_cutoff_index-1] < low <= binning[low_cutoff_index]
                // If low < binning[low_cutoff_index] then set previous bin to low so that the
                // lowest colorbar label equals low rather than than the arbitrary value set by
                // rescale_discrete_levels. This ensures the bottom colorbar label is correct.
                // If low == binning[low_cutoff_index] then do nothing as label is already correct.
                if (low < binning[low_cutoff_index] && low_cutoff_index > 0)
                    binning[low_cutoff_index - 1] = low;
                force_low_cutoff = true;
            }
            else
                binning[0] = low;
            binning[binning.length - 1] = high;
            return { min: low, max: high, binning, force_low_cutoff };
        }
    }
    exports.EqHistColorMapper = EqHistColorMapper;
    _a = EqHistColorMapper;
    EqHistColorMapper.__name__ = "EqHistColorMapper";
    (() => {
        _a.define(({ Boolean, Int }) => ({
            bins: [Int, 256 * 256],
            rescale_discrete_levels: [Boolean, false],
        }));
    })();
},
/* models/mappers/stack_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const color_mapper_1 = require(199) /* ./color_mapper */;
    class StackColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.StackColorMapper = StackColorMapper;
    StackColorMapper.__name__ = "StackColorMapper";
},
/* models/mappers/weighted_stack_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const color_mapper_1 = require(199) /* ./color_mapper */;
    const continuous_color_mapper_1 = require(198) /* ./continuous_color_mapper */;
    const stack_color_mapper_1 = require(252) /* ./stack_color_mapper */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const color_1 = require(22) /* ../../core/util/color */;
    class WeightedStackColorMapper extends stack_color_mapper_1.StackColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        // Weighted mix of colors.
        _mix_colors(colors_rgba, nan_color, weights, total_weight) {
            if (isNaN(total_weight))
                return nan_color;
            let r = 0.0, g = 0.0, b = 0.0, a = 0.0;
            const n = weights.length;
            if (total_weight != 0) {
                for (let i = 0; i < n; i++) {
                    if (isNaN(weights[i]))
                        continue;
                    const weight = weights[i] / total_weight;
                    r += colors_rgba[i * 4] * weight;
                    g += colors_rgba[i * 4 + 1] * weight;
                    b += colors_rgba[i * 4 + 2] * weight;
                    a += colors_rgba[i * 4 + 3] * weight;
                }
            }
            else {
                // Special case if total is zero then take mean color of all non-nan categories.
                let count = 0;
                for (let i = 0; i < n; i++) {
                    if (weights[i] == 0) {
                        r += colors_rgba[i * 4];
                        g += colors_rgba[i * 4 + 1];
                        b += colors_rgba[i * 4 + 2];
                        a += colors_rgba[i * 4 + 3];
                        count++;
                    }
                }
                r /= count;
                g /= count;
                b /= count;
                a /= count;
            }
            return (0, color_1.encode_rgba)([(0, color_1.byte)(r), (0, color_1.byte)(g), (0, color_1.byte)(b), (0, color_1.byte)(a)]);
        }
        _v_compute(_data, _values, _palette, _colors) {
            (0, assert_1.unreachable)();
        }
        _v_compute_uint32(data, values, palette, colors) {
            const n = values.length;
            const ncolor = palette.length;
            const nstack = data.length / n;
            (0, assert_1.assert)(nstack == ncolor, `Expected ${nstack} not ${ncolor} colors in palette`);
            // Color mixing is performed separately on each RGBA component, decode them just once
            const palette_as_rgba = new types_1.RGBAArray(ncolor * 4);
            for (let i = 0; i < ncolor; i++) {
                const [r, g, b, a] = (0, color_1.decode_rgba)(palette[i]);
                palette_as_rgba[i * 4] = r;
                palette_as_rgba[i * 4 + 1] = g;
                palette_as_rgba[i * 4 + 2] = b;
                palette_as_rgba[i * 4 + 3] = a;
            }
            // If color_baseline not specified, use nan-aware minimum of data.
            const color_baseline = this.color_baseline;
            const baseline = color_baseline == null ? (0, arrayable_1.min)(data) : color_baseline;
            // Mix colors based on weights.
            const { nan_color } = colors;
            const totals = new Array(n); // Array of totals per pixel
            const weights = new Array(ncolor); // For single pixel
            for (let i = 0; i < n; i++) {
                let total = NaN;
                for (let icol = 0; icol < ncolor; icol++) {
                    const index = i * ncolor + icol;
                    // If baseline non-zero, subtract it and clip to zero. Datashader only clips non-integers.
                    const val = baseline == 0 ? data[index] : Math.max(data[index] - baseline, 0);
                    weights[icol] = val;
                    if (!isNaN(val)) {
                        if (isNaN(total))
                            total = val;
                        else
                            total += val;
                    }
                }
                values[i] = this._mix_colors(palette_as_rgba, nan_color, weights, total);
                totals[i] = total + baseline * ncolor;
            }
            // Calculate alphas using alpha_mapper.
            const alpha_palette = (0, color_mapper_1._convert_palette)(this.alpha_mapper.palette);
            const alphas = new Uint32Array(n);
            this.alpha_mapper._v_compute(totals, alphas, alpha_palette, colors);
            // Combine RGBA and alphas.
            for (let i = 0; i < n; i++) {
                const alpha = (0, color_1.byte)((values[i] & 0xff) * (alphas[i] & 0xff) / 255.0);
                values[i] = (values[i] & 0xffffff00) | alpha;
            }
        }
    }
    exports.WeightedStackColorMapper = WeightedStackColorMapper;
    _a = WeightedStackColorMapper;
    WeightedStackColorMapper.__name__ = "WeightedStackColorMapper";
    (() => {
        _a.define(({ Array, Nullable, Number, Ref, String }) => ({
            alpha_mapper: [Ref(continuous_color_mapper_1.ContinuousColorMapper)],
            color_baseline: [Nullable(Number), null],
            stack_labels: [Nullable(Array(String)), null],
        }));
    })();
},
/* models/annotations/contour_color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const base_color_bar_1 = require(143) /* ./base_color_bar */;
    const ranges_1 = require(230) /* ../ranges */;
    const glyph_renderer_1 = require(201) /* ../renderers/glyph_renderer */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class ContourColorBarView extends base_color_bar_1.BaseColorBarView {
        *children() {
            yield* super.children();
            yield this._fill_view;
            yield this._line_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { fill_renderer, line_renderer } = this.model;
            this._fill_view = await (0, build_views_1.build_view)(fill_renderer, { parent: this.parent });
            this._line_view = await (0, build_views_1.build_view)(line_renderer, { parent: this.parent });
        }
        remove() {
            this._fill_view.remove();
            this._line_view.remove();
            super.remove();
        }
        _create_major_range() {
            const levels = this.model.levels;
            if (levels.length > 0) {
                return new ranges_1.Range1d({ start: levels[0], end: levels[levels.length - 1] });
            }
            else {
                return new ranges_1.Range1d({ start: 0, end: 1 });
            }
        }
        _paint_colors(ctx, bbox) {
            const vertical = this.orientation == "vertical";
            const levels = this.model.levels;
            const scale = this._major_scale;
            scale.source_range = this._major_range;
            if (vertical)
                scale.target_range = new ranges_1.Range1d({ start: bbox.bottom, end: bbox.top });
            else
                scale.target_range = new ranges_1.Range1d({ start: bbox.left, end: bbox.right });
            const scaled_levels = scale.v_compute(levels);
            const multi_polygons = this._fill_view.glyph;
            const nfill = multi_polygons.data_size;
            if (nfill > 0) {
                (0, assert_1.assert)(levels.length == nfill + 1, "Inconsistent number of filled contour levels");
                ctx.save();
                for (let i = 0; i < nfill; i++) {
                    ctx.beginPath();
                    if (vertical)
                        ctx.rect(bbox.left, scaled_levels[i], bbox.width, scaled_levels[i + 1] - scaled_levels[i]);
                    else
                        ctx.rect(scaled_levels[i], bbox.top, scaled_levels[i + 1] - scaled_levels[i], bbox.height);
                    multi_polygons.visuals.fill.apply(ctx, i);
                    multi_polygons.visuals.hatch.apply(ctx, i);
                }
                ctx.restore();
            }
            const multi_line = this._line_view.glyph;
            const nline = multi_line.data_size;
            if (nline > 0) {
                (0, assert_1.assert)(levels.length == nline, "Inconsistent number of line contour levels");
                ctx.save();
                for (let i = 0; i < nline; i++) {
                    ctx.beginPath();
                    if (vertical) {
                        ctx.moveTo(bbox.left, scaled_levels[i]);
                        ctx.lineTo(bbox.right, scaled_levels[i]);
                    }
                    else {
                        ctx.moveTo(scaled_levels[i], bbox.bottom);
                        ctx.lineTo(scaled_levels[i], bbox.top);
                    }
                    multi_line.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
                ctx.restore();
            }
        }
    }
    exports.ContourColorBarView = ContourColorBarView;
    ContourColorBarView.__name__ = "ContourColorBarView";
    class ContourColorBar extends base_color_bar_1.BaseColorBar {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContourColorBar = ContourColorBar;
    _a = ContourColorBar;
    ContourColorBar.__name__ = "ContourColorBar";
    (() => {
        _a.prototype.default_view = ContourColorBarView;
        _a.define(({ Array, Number, Ref }) => ({
            fill_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            line_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            levels: [Array(Number), []],
        }));
    })();
},
/* models/annotations/label.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const text_annotation_1 = require(145) /* ./text_annotation */;
    const math_1 = require(11) /* ../../core/util/math */;
    const enums_1 = require(20) /* ../../core/enums */;
    const side_panel_1 = require(146) /* ../../core/layout/side_panel */;
    class LabelView extends text_annotation_1.TextAnnotationView {
        update_layout() {
            const { panel } = this;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), false);
            else
                this.layout = undefined;
        }
        _get_size() {
            if (!this.displayed)
                return { width: 0, height: 0 };
            const graphics = this._text_view.graphics();
            const { angle, angle_units } = this.model;
            graphics.angle = (0, math_1.compute_angle)(angle, angle_units);
            graphics.visuals = this.visuals.text.values();
            const { width, height } = graphics.size();
            return { width, height };
        }
        _render() {
            const { angle, angle_units } = this.model;
            const rotation = (0, math_1.compute_angle)(angle, angle_units);
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            let sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return this.model.x;
                    case "screen":
                        return panel.bbox.xview.compute(this.model.x);
                    case "data":
                        return xscale.compute(this.model.x);
                }
            })();
            let sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return this.model.y;
                    case "screen":
                        return panel.bbox.yview.compute(this.model.y);
                    case "data":
                        return yscale.compute(this.model.y);
                }
            })();
            sx += this.model.x_offset;
            sy -= this.model.y_offset;
            this._paint(this.layer.ctx, { sx, sy }, rotation);
        }
    }
    exports.LabelView = LabelView;
    LabelView.__name__ = "LabelView";
    class Label extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Label = Label;
    _a = Label;
    Label.__name__ = "Label";
    (() => {
        _a.prototype.default_view = LabelView;
        _a.define(({ Number, Angle }) => ({
            x: [Number],
            x_units: [enums_1.CoordinateUnits, "data"],
            y: [Number],
            y_units: [enums_1.CoordinateUnits, "data"],
            angle: [Angle, 0],
            angle_units: [enums_1.AngleUnits, "rad"],
            x_offset: [Number, 0],
            y_offset: [Number, 0],
        }));
    })();
},
/* models/annotations/label_set.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(100) /* ./data_annotation */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const types_1 = require(24) /* ../../core/types */;
    class LabelSetView extends data_annotation_1.DataAnnotationView {
        map_data() {
            const { x_scale, y_scale } = this.coordinates;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            this.sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._x);
                    case "screen":
                        return panel.bbox.xview.v_compute(this._x);
                    case "data":
                        return x_scale.v_compute(this._x);
                }
            })();
            this.sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._y);
                    case "screen":
                        return panel.bbox.yview.v_compute(this._y);
                    case "data":
                        return y_scale.v_compute(this._y);
                }
            })();
        }
        paint() {
            const { ctx } = this.layer;
            for (let i = 0, end = this.text.length; i < end; i++) {
                const x_offset_i = this.x_offset.get(i);
                const y_offset_i = this.y_offset.get(i);
                const sx_i = this.sx[i] + x_offset_i;
                const sy_i = this.sy[i] - y_offset_i;
                const angle_i = this.angle.get(i);
                const text_i = this.text.get(i);
                if (!isFinite(sx_i + sy_i + angle_i) || text_i == null)
                    continue;
                this._paint(ctx, i, `${text_i}`, sx_i, sy_i, angle_i);
            }
        }
        _paint(ctx, i, text, sx, sy, angle) {
            const graphics = new graphics_1.TextBox({ text });
            graphics.angle = angle;
            graphics.position = { sx, sy };
            graphics.visuals = this.visuals.text.values(i);
            const { background_fill, border_line } = this.visuals;
            if (background_fill.doit || border_line.doit) {
                const { p0, p1, p2, p3 } = graphics.rect();
                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);
        }
    }
    exports.LabelSetView = LabelSetView;
    LabelSetView.__name__ = "LabelSetView";
    class LabelSet extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LabelSet = LabelSet;
    _a = LabelSet;
    LabelSet.__name__ = "LabelSet";
    (() => {
        _a.prototype.default_view = LabelSetView;
        _a.mixins([
            mixins.TextVector,
            ["border_", mixins.LineVector],
            ["background_", mixins.FillVector],
        ]);
        _a.define(() => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y: [p.YCoordinateSpec, { field: "y" }],
            x_units: [enums_1.CoordinateUnits, "data"],
            y_units: [enums_1.CoordinateUnits, "data"],
            text: [p.NullStringSpec, { field: "text" }],
            angle: [p.AngleSpec, 0],
            x_offset: [p.NumberSpec, { value: 0 }],
            y_offset: [p.NumberSpec, { value: 0 }],
        }));
        _a.override({
            background_fill_color: null,
            border_line_color: null,
        });
    })();
},
/* models/annotations/legend.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const legend_item_1 = require(258) /* ./legend_item */;
    const enums_1 = require(20) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const signaling_1 = require(15) /* ../../core/signaling */;
    const side_panel_1 = require(146) /* ../../core/layout/side_panel */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const types_1 = require(8) /* ../../core/util/types */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    const layout_1 = require(231) /* ../../core/layout */;
    const { max, ceil } = Math;
    class LegendEntry extends layout_1.ContentLayoutable {
        constructor(item, label, text, settings) {
            super();
            this.item = item;
            this.label = label;
            this.text = text;
            this.settings = settings;
        }
        get field() {
            return this.item.get_field_from_label_prop();
        }
        _content_size() {
            const text = this.text.size();
            const { glyph_width, glyph_height, label_standoff, label_width, label_height } = this.settings;
            const width = glyph_width + label_standoff + max(text.width, label_width);
            const height = max(glyph_height, text.height, label_height);
            return new layout_1.Sizeable({ width, height });
        }
    }
    LegendEntry.__name__ = "LegendEntry";
    class LegendView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this.bbox = new bbox_1.BBox();
        }
        _get_size() {
            const { width, height } = this.bbox;
            const { margin } = this.model;
            return {
                width: width + 2 * margin,
                height: height + 2 * margin,
            };
        }
        update_layout() {
            this.update_geometry();
            const { panel } = this;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size());
            else
                this.layout = undefined;
        }
        connect_signals() {
            super.connect_signals();
            const rerender = () => this.request_render();
            this.connect(this.model.change, rerender);
            this.connect(this.model.item_change, rerender);
        }
        get padding() {
            return this.model.border_line_color != null ? this.model.padding : 0;
        }
        update_geometry() {
            super.update_geometry();
            const { spacing, orientation } = this.model;
            const vertical = orientation == "vertical";
            const { padding } = this;
            const left = padding;
            const top = padding;
            const { title } = this.model;
            const title_box = new graphics_1.TextBox({ text: title !== null && title !== void 0 ? title : "" });
            title_box.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "top" };
            title_box.visuals = this.visuals.title_text.values();
            const _title_panel = new side_panel_1.Panel(this.model.title_location);
            title_box.angle = _title_panel.get_label_angle_heuristic("parallel");
            const entries = [];
            for (const item of this.model.items) {
                // Set a backref on render so that items can later signal item_change
                // upates on the model to trigger a re-render.
                item.legend = this.model;
                const labels = item.get_labels_list_from_label_prop();
                for (const label of labels) {
                    const text_box = new graphics_1.TextBox({ text: `${label}` }); // XXX: not always string
                    text_box.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "center" };
                    text_box.visuals = this.visuals.label_text.values();
                    const layout = new LegendEntry(item, label, text_box, this.model);
                    layout.set_sizing({ visible: item.visible });
                    entries.push({ layout, row: 0, col: 0 });
                }
            }
            const { ncols, nrows } = (() => {
                let { ncols, nrows } = this.model;
                const n = entries.length;
                if (vertical) {
                    if (nrows != "auto") {
                    }
                    else if (ncols != "auto")
                        nrows = ceil(n / ncols);
                    else
                        nrows = Infinity;
                    ncols = Infinity;
                }
                else {
                    if (ncols != "auto") {
                    }
                    else if (nrows != "auto")
                        ncols = ceil(n / nrows);
                    else
                        ncols = Infinity;
                    nrows = Infinity;
                }
                return { ncols, nrows };
            })();
            let row = 0;
            let col = 0;
            for (const entry of entries) {
                entry.row = row;
                entry.col = col;
                if (vertical) {
                    row += 1;
                    if (row >= nrows) {
                        row = 0;
                        col += 1;
                    }
                }
                else {
                    col += 1;
                    if (col >= ncols) {
                        col = 0;
                        row += 1;
                    }
                }
            }
            const grid = new layout_1.Grid(entries);
            this.grid = grid;
            grid.spacing = spacing;
            grid.set_sizing();
            const title_panel = new layout_1.TextLayout(title_box);
            this.title_panel = title_panel;
            const title_visible = title_box.text != "" && this.visuals.title_text.doit;
            title_panel.set_sizing({ visible: title_visible }); // doesn't work
            const border_box = (() => {
                if (!title_visible)
                    return new layout_1.Column([grid]);
                switch (this.model.title_location) {
                    case "above": return new layout_1.Column([title_panel, grid]);
                    case "below": return new layout_1.Column([grid, title_panel]);
                    case "left": return new layout_1.Row([title_panel, grid]);
                    case "right": return new layout_1.Row([grid, title_panel]);
                }
            })();
            this.border_box = border_box;
            border_box.position = { left, top };
            border_box.spacing = this.model.title_standoff;
            border_box.set_sizing();
            border_box.compute();
            const width = padding + border_box.bbox.width + padding;
            const height = padding + border_box.bbox.height + padding;
            // Position will be filled-in in `compute_geometry()`.
            this.bbox = new bbox_1.BBox({ left: 0, top: 0, width, height });
        }
        compute_geometry() {
            super.compute_geometry();
            const { margin, location } = this.model;
            const { width, height } = this.bbox;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const [hr, vr] = panel.bbox.ranges;
            let sx, sy;
            if ((0, types_1.isString)(location)) {
                switch (location) {
                    case "top_left":
                        sx = hr.start + margin;
                        sy = vr.start + margin;
                        break;
                    case "top":
                    case "top_center":
                        sx = (hr.end + hr.start) / 2 - width / 2;
                        sy = vr.start + margin;
                        break;
                    case "top_right":
                        sx = hr.end - margin - width;
                        sy = vr.start + margin;
                        break;
                    case "bottom_right":
                        sx = hr.end - margin - width;
                        sy = vr.end - margin - height;
                        break;
                    case "bottom":
                    case "bottom_center":
                        sx = (hr.end + hr.start) / 2 - width / 2;
                        sy = vr.end - margin - height;
                        break;
                    case "bottom_left":
                        sx = hr.start + margin;
                        sy = vr.end - margin - height;
                        break;
                    case "left":
                    case "center_left":
                        sx = hr.start + margin;
                        sy = (vr.end + vr.start) / 2 - height / 2;
                        break;
                    case "center":
                    case "center_center":
                        sx = (hr.end + hr.start) / 2 - width / 2;
                        sy = (vr.end + vr.start) / 2 - height / 2;
                        break;
                    case "right":
                    case "center_right":
                        sx = hr.end - margin - width;
                        sy = (vr.end + vr.start) / 2 - height / 2;
                        break;
                }
            }
            else {
                const [vx, vy] = location;
                sx = panel.bbox.xview.compute(vx);
                sy = panel.bbox.yview.compute(vy) - height;
            }
            this.bbox = new bbox_1.BBox({ left: sx, top: sy, width, height });
        }
        interactive_hit(sx, sy) {
            return this.bbox.contains(sx, sy);
        }
        _hit_test(sx, sy) {
            const { left, top } = this.bbox;
            sx -= left + this.grid.bbox.left;
            sy -= top + this.grid.bbox.top;
            for (const entry of this.grid) {
                if (entry.bbox.contains(sx, sy)) {
                    return { type: "entry", entry };
                }
            }
            return null;
        }
        cursor(sx, sy) {
            if (this.model.click_policy == "none")
                return null;
            if (this._hit_test(sx, sy) != null)
                return "pointer";
            return null;
        }
        on_hit(sx, sy) {
            const fn = (() => {
                switch (this.model.click_policy) {
                    case "hide": return (r) => r.visible = !r.visible;
                    case "mute": return (r) => r.muted = !r.muted;
                    case "none": return (_) => { };
                }
            })();
            const target = this._hit_test(sx, sy);
            if (target != null) {
                const { renderers } = target.entry.item;
                for (const renderer of renderers) {
                    fn(renderer);
                }
                return true;
            }
            return false;
        }
        _render() {
            // It would be better to update geometry (the internal layout) only when
            // necessary, but conditions for that are not clear, so for now update
            // at every render.
            this.update_geometry();
            this.compute_geometry();
            if (this.model.items.length == 0)
                return;
            if (!(0, array_1.some)(this.model.items, (item) => item.visible))
                return;
            const { ctx } = this.layer;
            ctx.save();
            this._draw_legend_box(ctx);
            this._draw_legend_items(ctx);
            this._draw_title(ctx);
            ctx.restore();
        }
        _draw_legend_box(ctx) {
            const { x, y, width, height } = this.bbox;
            ctx.beginPath();
            ctx.rect(x, y, width, height);
            this.visuals.background_fill.apply(ctx);
            this.visuals.border_line.apply(ctx);
        }
        _draw_title(ctx) {
            const { title } = this.model;
            if (title == null || title.length == 0 || !this.visuals.title_text.doit)
                return;
            const { left, top } = this.bbox;
            ctx.save();
            ctx.translate(left, top);
            ctx.translate(this.title_panel.bbox.left, this.title_panel.bbox.top);
            switch (this.model.title_location) {
                case "left": {
                    ctx.translate(0, this.title_panel.bbox.height);
                    break;
                }
                case "right": {
                    ctx.translate(this.title_panel.bbox.width, 0);
                    break;
                }
                case "above":
                case "below": {
                    break;
                }
            }
            this.title_panel.text.paint(ctx);
            ctx.restore();
        }
        _draw_legend_items(ctx) {
            const is_active = (() => {
                switch (this.model.click_policy) {
                    case "none": return (_item) => true;
                    case "hide": return (item) => (0, array_1.every)(item.renderers, (r) => r.visible);
                    case "mute": return (item) => (0, array_1.every)(item.renderers, (r) => !r.muted);
                }
            })();
            const has_item_background = (_i, row, col) => {
                if (!this.visuals.item_background_fill.doit)
                    return false;
                switch (this.model.item_background_policy) {
                    case "every": return true;
                    case "even": return (row % 2 == 0) == (col % 2 == 0);
                    case "odd": return (row % 2 == 0) != (col % 2 == 0);
                    case "none": return false;
                }
            };
            const { left, top } = this.bbox;
            ctx.translate(left, top);
            ctx.translate(this.grid.bbox.left, this.grid.bbox.top);
            for (const [{ layout: entry, row, col }, i] of (0, iterator_1.enumerate)(this.grid.items)) {
                const { bbox, text, item, label, field, settings } = entry;
                const { glyph_width, glyph_height, label_standoff } = settings;
                const { left, top, width, height } = bbox;
                ctx.translate(left, top);
                if (has_item_background(i, row, col)) {
                    ctx.beginPath();
                    ctx.rect(0, 0, width, height);
                    this.visuals.item_background_fill.apply(ctx);
                }
                const vcenter = height / 2;
                const x0 = 0;
                const y0 = vcenter - glyph_height / 2;
                const x1 = x0 + glyph_width;
                const y1 = y0 + glyph_height;
                for (const renderer of item.renderers) {
                    const view = this.plot_view.renderer_view(renderer);
                    view === null || view === void 0 ? void 0 : view.draw_legend(ctx, x0, x1, y0, y1, field, label, item.index);
                }
                ctx.translate(x1 + label_standoff, vcenter);
                text.paint(ctx);
                ctx.translate(-x1 - label_standoff, -vcenter);
                if (!is_active(item)) {
                    ctx.beginPath();
                    ctx.rect(0, 0, width, height);
                    this.visuals.inactive_fill.set_value(ctx);
                    ctx.fill();
                }
                ctx.translate(-left, -top);
            }
            ctx.translate(-this.grid.bbox.left, -this.grid.bbox.top);
            ctx.translate(-left, -top);
        }
    }
    exports.LegendView = LegendView;
    LegendView.__name__ = "LegendView";
    class Legend extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.item_change = new signaling_1.Signal0(this, "item_change");
        }
    }
    exports.Legend = Legend;
    _a = Legend;
    Legend.__name__ = "Legend";
    (() => {
        _a.prototype.default_view = LegendView;
        _a.mixins([
            ["label_", mixins.Text],
            ["title_", mixins.Text],
            ["inactive_", mixins.Fill],
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
            ["item_background_", mixins.Fill],
        ]);
        _a.define(({ Number, Int, String, Array, Tuple, Or, Ref, Nullable, Positive, Auto }) => ({
            orientation: [enums_1.Orientation, "vertical"],
            ncols: [Or(Positive(Int), Auto), "auto"],
            nrows: [Or(Positive(Int), Auto), "auto"],
            location: [Or(enums_1.LegendLocation, Tuple(Number, Number)), "top_right"],
            title: [Nullable(String), null],
            title_location: [enums_1.Location, "above"],
            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"],
            item_background_policy: [enums_1.AlternationPolicy, "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,
            item_background_fill_color: "#f1f1f1",
            item_background_fill_alpha: 0.8,
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(50) /* ../../model */;
    const glyph_renderer_1 = require(201) /* ../renderers/glyph_renderer */;
    const columnar_data_source_1 = require(101) /* ../sources/columnar_data_source */;
    const vectorization_1 = require(28) /* ../../core/vectorization */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const logging_1 = require(19) /* ../../core/logging */;
    const array_1 = require(10) /* ../../core/util/array */;
    class LegendItem extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        /*protected*/ _check_data_sources_on_renderers() {
            const field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length < 1) {
                    return false;
                }
                const source = this.renderers[0].data_source;
                for (const r of this.renderers) {
                    if (r.data_source != source) {
                        return false;
                    }
                }
            }
            return true;
        }
        /*protected*/ _check_field_label_on_data_source() {
            const field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length < 1) {
                    return false;
                }
                const source = this.renderers[0].data_source;
                if (!(0, array_1.includes)(source.columns(), field)) {
                    return false;
                }
            }
            return true;
        }
        initialize() {
            super.initialize();
            this.legend = null;
            this.connect(this.change, () => { var _b; return (_b = this.legend) === null || _b === void 0 ? void 0 : _b.item_change.emit(); });
            // Validate data_sources match
            const 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
            const field_validation = this._check_field_label_on_data_source();
            if (!field_validation)
                logging_1.logger.error(`Bad column name on label: ${this.label}`);
        }
        get_field_from_label_prop() {
            const { label } = this;
            return (0, vectorization_1.isField)(label) ? label.field : null;
        }
        get_labels_list_from_label_prop() {
            if (!this.visible) {
                return [];
            }
            const { index } = this;
            if (index != null && this.renderers.every((r) => !(index in r.view.indices_map))) {
                // this index points to nowhere, so skip this item altogether from its legend
                return [];
            }
            if ((0, vectorization_1.isValue)(this.label)) {
                const { value } = this.label;
                return value != null ? [value] : [];
            }
            const field = this.get_field_from_label_prop();
            if (field != null) {
                let source;
                if (this.renderers.length != 0)
                    source = this.renderers[0].data_source;
                else
                    return ["No source found"];
                if (source instanceof columnar_data_source_1.ColumnarDataSource) {
                    const data = source.get_column(field);
                    if (data != null)
                        return (0, array_1.uniq)(Array.from(data));
                    else
                        return ["Invalid field"];
                }
            }
            return [];
        }
    }
    exports.LegendItem = LegendItem;
    _a = LegendItem;
    LegendItem.__name__ = "LegendItem";
    (() => {
        _a.define(({ Boolean, Int, Array, Ref, Nullable }) => ({
            label: [p.NullStringSpec, null],
            renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
            index: [Nullable(Int), null],
            visible: [Boolean, true],
        }));
    })();
},
/* models/annotations/poly_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const data_range1d_1 = require(95) /* ../ranges/data_range1d */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const hittest_1 = require(212) /* ../../core/hittest */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class Polygon {
        constructor(xs = [], ys = []) {
            this.xs = xs;
            this.ys = ys;
            (0, assert_1.assert)(xs.length == ys.length);
        }
        clone() {
            return new Polygon(this.xs.slice(), this.ys.slice());
        }
        [Symbol.iterator]() {
            return this.nodes();
        }
        *nodes() {
            const { xs, ys, n } = this;
            for (let i = 0; i < n; i++) {
                yield [xs[i], ys[i], i];
            }
        }
        *edges() {
            const { xs, ys, n } = this;
            for (let i = 1; i < n; i++) {
                const p0 = { x: xs[i - 1], y: ys[i - 1] };
                const p1 = { x: xs[i], y: ys[i] };
                yield [p0, p1, i - 1];
            }
            if (n >= 3) {
                const p0 = { x: xs[n - 1], y: ys[n - 1] };
                const p1 = { x: xs[0], y: ys[0] };
                yield [p0, p1, n - 1];
            }
        }
        contains(x, y) {
            return (0, hittest_1.point_in_poly)(x, y, this.xs, this.ys);
        }
        get bbox() {
            const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(this.xs, this.ys);
            return new bbox_1.BBox({ x0, x1, y0, y1 });
        }
        get n() {
            return this.xs.length;
        }
        translate(dx, dy, ...i) {
            const poly = this.clone();
            const { xs, ys, n } = poly;
            if (i.length != 0) {
                for (const j of i) {
                    const k = j % n;
                    xs[k] += dx;
                    ys[k] += dy;
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    xs[i] += dx;
                    ys[i] += dy;
                }
            }
            return poly;
        }
    }
    Polygon.__name__ = "Polygon";
    class PolyAnnotationView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this.poly = new Polygon();
            this[_a] = true;
            this._pan_state = null;
            this._is_hovered = false;
        }
        serializable_state() {
            return Object.assign(Object.assign({}, super.serializable_state()), { bbox: this.poly.bbox.round() });
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
        }
        bounds() {
            const { xs_units, ys_units } = this.model;
            if (xs_units == "data" && ys_units == "data") {
                const { xs, ys } = this.model;
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return { x0, x1, y0, y1 };
            }
            else
                return (0, bbox_1.empty)();
        }
        log_bounds() {
            return (0, bbox_1.empty)();
        }
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const overlay = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                x: mapper(overlay.xs_units, x_scale, x_view, x_screen),
                y: mapper(overlay.ys_units, y_scale, y_view, y_screen),
            };
        }
        _render() {
            const { xs, ys } = this.model;
            (0, assert_1.assert)(xs.length == ys.length);
            this.poly = (() => {
                const { x, y } = this._mappers();
                return new Polygon(x.v_compute(xs), y.v_compute(ys));
            })();
            const { ctx } = this.layer;
            ctx.beginPath();
            for (const [sx, sy] of this.poly) {
                ctx.lineTo(sx, sy);
            }
            const { _is_hovered, visuals } = this;
            const fill = _is_hovered && visuals.hover_fill.doit ? visuals.hover_fill : visuals.fill;
            const hatch = _is_hovered && visuals.hover_hatch.doit ? visuals.hover_hatch : visuals.hatch;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            if (this.poly.n >= 3) {
                ctx.closePath();
                fill.apply(ctx);
                hatch.apply(ctx);
            }
            line.apply(ctx);
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable)
                return false;
            return this.poly.contains(sx, sy);
        }
        _hit_test(sx, sy) {
            const { abs } = Math;
            const EDGE_TOLERANCE = 2.5;
            const tolerance = Math.max(EDGE_TOLERANCE, this.model.line_width / 2);
            for (const [px, py, i] of this.poly) {
                if (abs(px - sx) < tolerance && abs(py - sy) < tolerance)
                    return { type: "node", i };
            }
            const spt = { x: sx, y: sy };
            let j = null;
            let dist = Infinity;
            for (const [p0, p1, i] of this.poly.edges()) {
                const d = (0, hittest_1.dist_to_segment)(spt, p0, p1);
                if (d < tolerance && d < dist) {
                    dist = d;
                    j = i;
                }
            }
            if (j != null) {
                return { type: "edge", i: j };
            }
            if (this.poly.contains(sx, sy)) {
                return { type: "area" };
            }
            return null;
        }
        _can_hit(_target) {
            return true;
        }
        _pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        poly: this.poly.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        _pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            const spoly = (() => {
                const { poly, target } = this._pan_state;
                const { dx, dy } = ev;
                switch (target.type) {
                    case "node": {
                        const { i } = target;
                        return poly.translate(dx, dy, i);
                    }
                    case "edge": {
                        const { i } = target;
                        return poly.translate(dx, dy, i, i + 1);
                    }
                    case "area": {
                        return poly.translate(dx, dy);
                    }
                }
            })();
            const { x, y } = this._mappers();
            const xs = x.v_invert(spoly.xs);
            const ys = y.v_invert(spoly.ys);
            this.model.update({ xs, ys });
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        _pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line, hover_fill, hover_hatch } = this.visuals;
            return hover_line.doit || hover_fill.doit || hover_hatch.doit;
        }
        _move_start(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        _move(_ev) { }
        _move_end(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            var _c, _d;
            const target = (_d = (_c = this._pan_state) === null || _c === void 0 ? void 0 : _c.target) !== null && _d !== void 0 ? _d : this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            switch (target.type) {
                case "node": return "move";
                case "edge": return "move";
                case "area": return "move";
            }
        }
    }
    exports.PolyAnnotationView = PolyAnnotationView;
    _a = data_range1d_1.auto_ranged;
    PolyAnnotationView.__name__ = "PolyAnnotationView";
    class PolyAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
            this.pan = new signaling_1.Signal(this, "pan");
        }
        update({ xs, ys }) {
            this.setv({ xs: xs.slice(), ys: ys.slice(), visible: true });
        }
        clear() {
            this.setv({ xs: [], ys: [], visible: false });
        }
    }
    exports.PolyAnnotation = PolyAnnotation;
    _b = PolyAnnotation;
    PolyAnnotation.__name__ = "PolyAnnotation";
    (() => {
        _b.prototype.default_view = PolyAnnotationView;
        _b.mixins([
            mixins.Line,
            mixins.Fill,
            mixins.Hatch,
            ["hover_", mixins.Line],
            ["hover_", mixins.Fill],
            ["hover_", mixins.Hatch],
        ]);
        _b.define(({ Boolean, Number, Arrayable }) => ({
            xs: [Arrayable(Number), []],
            ys: [Arrayable(Number), []],
            xs_units: [enums_1.CoordinateUnits, "data"],
            ys_units: [enums_1.CoordinateUnits, "data"],
            editable: [Boolean, false],
        }));
        _b.override({
            fill_color: "#fff9ba",
            fill_alpha: 0.4,
            line_color: "#cccccc",
            line_alpha: 0.3,
            hover_fill_color: null,
            hover_fill_alpha: 0.4,
            hover_line_color: null,
            hover_line_alpha: 0.3,
        });
    })();
},
/* models/annotations/scale_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const dimensional_1 = require(261) /* ./dimensional */;
    const range_1 = require(87) /* ../ranges/range */;
    const range1d_1 = require(88) /* ../ranges/range1d */;
    const enums_1 = require(20) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const graphics_1 = require(153) /* ../../core/graphics */;
    const side_panel_1 = require(146) /* ../../core/layout/side_panel */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const layout_1 = require(231) /* ../../core/layout */;
    const grid_1 = require(233) /* ../../core/layout/grid */;
    const linear_axis_1 = require(186) /* ../axes/linear_axis */;
    const ticker_1 = require(163) /* ../tickers/ticker */;
    const fixed_ticker_1 = require(195) /* ../tickers/fixed_ticker */;
    const linear_scale_1 = require(90) /* ../scales/linear_scale */;
    const coordinate_mapping_1 = require(84) /* ../coordinates/coordinate_mapping */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const math_1 = require(11) /* ../../core/util/math */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const templating_1 = require(172) /* ../../core/util/templating */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const { round } = Math;
    const LengthSizing = (0, kinds_1.Enum)("adaptive", "exact");
    class ScaleBarView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this.bbox = new bbox_1.BBox();
        }
        _get_size() {
            const { width, height } = this.bbox;
            const { margin } = this.model;
            return {
                width: width + 2 * margin,
                height: height + 2 * margin,
            };
        }
        initialize() {
            super.initialize();
            const { ticker } = this.model;
            this.axis = new linear_axis_1.LinearAxis(Object.assign({ ticker }, mixins.attrs_of(this.model, "bar_", mixins.Line, "axis_")));
            this.range = (() => {
                const { range, orientation } = this.model;
                if (range == "auto") {
                    const { frame } = this.parent;
                    switch (orientation) {
                        case "horizontal": return frame.x_range;
                        case "vertical": return frame.y_range;
                    }
                }
                else {
                    return range;
                }
            })();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const coordinates = (() => {
                const axis_source = new range1d_1.Range1d();
                const axis_target = new range1d_1.Range1d();
                const cross_source = new range1d_1.Range1d();
                const cross_target = new range1d_1.Range1d();
                this.axis_scale = new linear_scale_1.LinearScale({ source_range: axis_source, target_range: axis_target });
                this.cross_scale = new linear_scale_1.LinearScale({ source_range: cross_source, target_range: cross_target });
                if (this.model.orientation == "horizontal") {
                    return new coordinate_mapping_1.CoordinateTransform(this.axis_scale, this.cross_scale);
                }
                else {
                    return new coordinate_mapping_1.CoordinateTransform(this.cross_scale, this.axis_scale);
                }
            })();
            this.axis_view = await (0, build_views_1.build_view)(this.axis, { parent: this.plot_view });
            this.axis_view.coordinates = coordinates;
            this.axis_view.panel = new side_panel_1.Panel(this.model.orientation == "horizontal" ? "below" : "right");
            this.axis_view.update_layout();
        }
        remove() {
            this.axis_view.remove();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => {
                this.request_render();
            });
            this.connect(this.range.change, () => {
                this.request_render();
            });
        }
        update_layout() {
            this.update_geometry();
            const { panel } = this;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size());
            else
                this.layout = undefined;
        }
        update_geometry() {
            super.update_geometry();
        }
        get horizontal() {
            return this.model.orientation == "horizontal";
        }
        text_layout(args) {
            const { text, location, align, visuals } = args;
            const { orientation } = this.model;
            const text_box = new graphics_1.TextBox({ text });
            const text_panel = new side_panel_1.Panel(location);
            text_box.visuals = visuals.values();
            const text_orientation = (() => {
                switch (location) {
                    case "above":
                    case "below": return "horizontal";
                    default: return orientation;
                }
            })();
            text_box.angle = text_panel.get_label_angle_heuristic(text_orientation);
            text_box.base_font_size = this.plot_view.base_font_size;
            text_box.position = {
                sx: 0,
                sy: 0,
                x_anchor: "left",
                y_anchor: "top",
            };
            text_box.align = "auto";
            const text_layout = new layout_1.TextLayout(text_box);
            text_layout.absolute = true;
            const horizontal = orientation == "horizontal";
            const halign = horizontal ? align : undefined;
            const valign = !horizontal ? align : undefined;
            text_layout.set_sizing({
                width_policy: "min",
                height_policy: "min",
                visible: text != "" && visuals.doit,
                halign, valign,
            });
            return text_layout;
        }
        compute_geometry() {
            super.compute_geometry();
            const { orientation, bar_length, length_sizing, padding, margin, location } = this.model;
            const { border_line, bar_line } = this.visuals;
            const bar_width = bar_line.line_width.get_value();
            const border_width = border_line.line_width.get_value();
            const { frame } = this.parent;
            const frame_span = orientation == "horizontal" ? frame.bbox.width : frame.bbox.height;
            const bar_length_percent = (() => {
                if (0.0 <= bar_length && bar_length <= 1.0) {
                    return bar_length;
                }
                else {
                    return (0, math_1.clamp)(bar_length / frame_span, 0.0, 1.0);
                }
            })();
            const { new_value, new_unit, new_long_unit, scale_factor, exact } = (() => {
                const { unit, dimensional } = this.model;
                const value = this.range.span * bar_length_percent;
                return dimensional.compute(value, unit, length_sizing == "exact");
            })();
            const init_bar_length_px = frame_span * bar_length_percent;
            const bar_length_px = round(init_bar_length_px * scale_factor);
            const label_text = (() => {
                const { label } = this.model;
                return (0, templating_1.process_placeholders)(label, (_, name, format) => {
                    switch (name) {
                        case "value": {
                            if (exact) {
                                if (format != null) {
                                    return (0, templating_1.sprintf)(format, new_value);
                                }
                                else {
                                    return new_value.toFixed(2);
                                }
                            }
                            else {
                                return `${new_value}`;
                            }
                        }
                        case "unit": {
                            switch (format !== null && format !== void 0 ? format : "short") {
                                case "short": return new_unit;
                                case "long": return new_long_unit;
                            }
                        }
                        default: {
                            return "???";
                        }
                    }
                });
            })();
            this.label_layout = this.text_layout({
                text: label_text,
                location: this.model.label_location,
                align: this.model.label_align,
                visuals: this.visuals.label_text,
            });
            this.title_layout = this.text_layout({
                text: this.model.title,
                location: this.model.title_location,
                align: this.model.title_align,
                visuals: this.visuals.title_text,
            });
            const bar_size = (() => {
                if (orientation == "horizontal") {
                    return { width: bar_length_px, height: bar_width };
                }
                else {
                    return { width: bar_width, height: bar_length_px };
                }
            })();
            const axis_layout = this.axis_view.layout;
            (0, assert_1.assert)(axis_layout != null);
            this.axis_layout = axis_layout;
            axis_layout.absolute = true;
            if (orientation == "horizontal") {
                axis_layout.set_sizing({
                    width_policy: "fixed", width: bar_size.width,
                    height_policy: "min",
                    valign: "center",
                });
            }
            else {
                axis_layout.set_sizing({
                    width_policy: "min",
                    height_policy: "fixed", height: bar_size.height,
                    halign: "center",
                });
            }
            this.box_layout = (() => {
                const panels = {
                    above: [],
                    below: [],
                    left: [],
                    right: [],
                };
                function spacer(location, spacing) {
                    const layout = new layout_1.FixedLayout();
                    layout.absolute = true;
                    layout.set_sizing((() => {
                        if (location == "left" || location == "right") {
                            return { width_policy: "fixed", width: spacing };
                        }
                        else {
                            return { height_policy: "fixed", height: spacing };
                        }
                    })());
                    return layout;
                }
                function insert(layout, location, spacing) {
                    if (layout.visible) {
                        panels[location].push(spacer(location, spacing), layout);
                    }
                }
                insert(this.label_layout, this.model.label_location, this.model.label_standoff);
                insert(this.title_layout, this.model.title_location, this.model.title_standoff);
                const row = panels.above.length;
                const col = panels.left.length;
                const items = [
                    { layout: axis_layout, row, col },
                ];
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.above)) {
                    items.push({ layout, row: row - i - 1, col });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.below)) {
                    items.push({ layout, row: row + i + 1, col });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.left)) {
                    items.push({ layout, row, col: col - i - 1 });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.right)) {
                    items.push({ layout, row, col: col + i + 1 });
                }
                return new grid_1.Grid(items);
            })();
            const { box_layout } = this;
            box_layout.absolute = true;
            box_layout.position = { left: padding, top: padding };
            box_layout.set_sizing();
            box_layout.compute();
            const [axis_range, cross_range] = (() => {
                const { x_range, y_range } = this.axis_view.bbox;
                if (orientation == "horizontal") {
                    return [x_range, y_range];
                }
                else {
                    return [y_range, x_range];
                }
            })();
            this.axis_scale.source_range.end = new_value;
            this.axis_scale.target_range.setv(axis_range);
            this.cross_scale.source_range.end = 1.0;
            this.cross_scale.target_range.setv(cross_range);
            const width = border_width + padding + box_layout.bbox.width + padding + border_width;
            const height = border_width + padding + box_layout.bbox.height + padding + border_width;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const [hr, vr] = panel.bbox.ranges;
            const { sx, sy } = (() => {
                switch (location) {
                    case "top_left":
                        return {
                            sx: hr.start + margin,
                            sy: vr.start + margin,
                        };
                    case "top":
                    case "top_center":
                        return {
                            sx: (hr.end + hr.start) / 2 - width / 2,
                            sy: vr.start + margin,
                        };
                    case "top_right":
                        return {
                            sx: hr.end - margin - width,
                            sy: vr.start + margin,
                        };
                    case "bottom_right":
                        return {
                            sx: hr.end - margin - width,
                            sy: vr.end - margin - height,
                        };
                    case "bottom":
                    case "bottom_center":
                        return {
                            sx: (hr.end + hr.start) / 2 - width / 2,
                            sy: vr.end - margin - height,
                        };
                    case "bottom_left":
                        return {
                            sx: hr.start + margin,
                            sy: vr.end - margin - height,
                        };
                    case "left":
                    case "center_left":
                        return {
                            sx: hr.start + margin,
                            sy: (vr.end + vr.start) / 2 - height / 2,
                        };
                    case "center":
                    case "center_center":
                        return {
                            sx: (hr.end + hr.start) / 2 - width / 2,
                            sy: (vr.end + vr.start) / 2 - height / 2,
                        };
                    case "right":
                    case "center_right":
                        return {
                            sx: hr.end - margin - width,
                            sy: (vr.end + vr.start) / 2 - height / 2,
                        };
                }
            })();
            this.bbox = new bbox_1.BBox({ left: sx, top: sy, width, height });
        }
        _draw_box(ctx) {
            const { width, height } = this.bbox;
            ctx.beginPath();
            ctx.rect(0, 0, width, height);
            this.visuals.background_fill.apply(ctx);
            this.visuals.background_hatch.apply(ctx);
            this.visuals.border_line.apply(ctx);
        }
        _draw_axis(_ctx) {
            this.axis_view.render();
        }
        _draw_text(ctx, layout, location) {
            const { bbox } = layout;
            const [x_offset, y_offset] = (() => {
                const { orientation } = this.model;
                const horizontal = orientation == "horizontal";
                switch (location) {
                    case "left": return horizontal ? [0, 0] : [0, bbox.height];
                    case "right": return horizontal ? [0, 0] : [bbox.width, 0];
                    case "above": return [0, 0];
                    case "below": return [0, 0];
                }
            })();
            const { left, top } = bbox.translate(x_offset, y_offset);
            ctx.translate(left, top);
            layout.text.paint(ctx);
            ctx.translate(-left, -top);
        }
        _draw_label(ctx) {
            this._draw_text(ctx, this.label_layout, this.model.label_location);
        }
        _draw_title(ctx) {
            this._draw_text(ctx, this.title_layout, this.model.title_location);
        }
        _render() {
            // It would be better to update geometry (the internal layout) only when
            // necessary, but conditions for that are not clear, so for now update
            // at every render.
            this.update_geometry();
            this.compute_geometry();
            const { ctx } = this.layer;
            const { left, top } = this.bbox;
            ctx.translate(left, top);
            if (this.box_layout.visible) {
                this._draw_box(ctx);
            }
            if (this.axis_layout.visible) {
                this._draw_axis(ctx);
            }
            if (this.label_layout.visible) {
                this._draw_label(ctx);
            }
            if (this.title_layout.visible) {
                this._draw_title(ctx);
            }
            ctx.translate(-left, -top);
        }
    }
    exports.ScaleBarView = ScaleBarView;
    ScaleBarView.__name__ = "ScaleBarView";
    class ScaleBar extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ScaleBar = ScaleBar;
    _a = ScaleBar;
    ScaleBar.__name__ = "ScaleBar";
    (() => {
        _a.prototype.default_view = ScaleBarView;
        _a.mixins([
            ["bar_", mixins.Line],
            ["label_", mixins.Text],
            ["title_", mixins.Text],
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
            ["background_", mixins.Hatch],
        ]);
        _a.define(({ NonNegative, Number, String, Ref, Or, Auto }) => ({
            range: [Or(Ref(range_1.Range), Auto), "auto"],
            unit: [String, "m"],
            dimensional: [Ref(dimensional_1.Dimensional), () => new dimensional_1.MetricLength()],
            orientation: [enums_1.Orientation, "horizontal"],
            bar_length: [NonNegative(Number), 0.2],
            length_sizing: [LengthSizing, "adaptive"],
            location: [enums_1.Anchor, "top_right"],
            label: [String, "@{value} @{unit}"],
            label_align: [enums_1.Align, "center"],
            label_location: [enums_1.Location, "below"],
            label_standoff: [Number, 5],
            title: [String, ""],
            title_align: [enums_1.Align, "center"],
            title_location: [enums_1.Location, "above"],
            title_standoff: [Number, 5],
            margin: [Number, 10],
            padding: [Number, 10],
            ticker: [Ref(ticker_1.Ticker), () => new fixed_ticker_1.FixedTicker({ ticks: [] })],
        }));
        _a.override({
            bar_line_width: 2,
            border_line_color: "#e5e5e5",
            border_line_alpha: 0.5,
            border_line_width: 1,
            background_fill_color: "#ffffff",
            background_fill_alpha: 0.95,
            label_text_font_size: "13px",
            label_text_baseline: "middle",
            title_text_font_size: "13px",
            title_text_font_style: "italic",
        });
    })();
},
/* models/annotations/dimensional.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const { min } = Math;
    class Dimensional extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        compute(value, unit, exact) {
            const { ticks, basis } = this;
            const found_unit = basis.find(({ short_name: short }) => short == unit);
            (0, assert_1.assert)(found_unit != null);
            const value_in_unit = value * found_unit.factor;
            const [new_unit, new_long_unit, new_value] = (() => {
                const index = (0, arrayable_1.bisect_right_by)(basis, value_in_unit, ({ factor }) => factor);
                if (index > 0) {
                    const { short_name: new_unit, long_name: new_long_unit, factor } = basis[index - 1];
                    const new_value = value_in_unit / factor;
                    return [new_unit, new_long_unit, new_value];
                }
                else {
                    return [unit, found_unit.long_name, value_in_unit];
                }
            })();
            exact = exact !== null && exact !== void 0 ? exact : ticks.length == 0;
            const preferred_value = (() => {
                if (exact) {
                    return new_value;
                }
                else {
                    const index = (0, arrayable_1.bisect_right)(ticks, new_value);
                    return ticks[min(index, ticks.length - 1)];
                }
            })();
            const preferred_value_raw = preferred_value * (value_in_unit / new_value);
            const scale_factor = (preferred_value_raw / value) / found_unit.factor;
            return {
                new_value: preferred_value,
                new_unit,
                new_long_unit,
                scale_factor,
                exact,
            };
        }
    }
    exports.Dimensional = Dimensional;
    _a = Dimensional;
    Dimensional.__name__ = "Dimensional";
    (() => {
        _a.define(({ Nullable, Array, String, Number }) => ({
            ticks: [Array(Number)],
            include: [Nullable(Array(String)), null],
            exclude: [Array(String), []],
        }));
    })();
    class Metric extends Dimensional {
        constructor(attrs) {
            super(attrs);
            this._basis = null;
            this._basis_template = [
                ["Q", 1e30, "quetta", null],
                ["R", 1e27, "ronna", null],
                ["Y", 1e24, "yotta", null],
                ["Z", 1e21, "zetta", null],
                ["E", 1e18, "exa", null],
                ["P", 1e15, "peta", null],
                ["T", 1e12, "tera", null],
                ["G", 1e9, "giga", null],
                ["M", 1e6, "mega", null],
                ["k", 1e3, "kilo", null],
                ["h", 1e2, "hecto", null],
                ["", 1e0, "", null],
                ["d", 1e-1, "deci", null],
                ["c", 1e-2, "centi", null],
                ["m", 1e-3, "milli", null],
                ["µ", 1e-6, "micro", "\\mathrm{\\mu}"],
                ["n", 1e-9, "nano", null],
                ["p", 1e-12, "pico", null],
                ["f", 1e-15, "femto", null],
                ["a", 1e-18, "atto", null],
                ["z", 1e-21, "zepto", null],
                ["y", 1e-24, "yocto", null],
                ["r", 1e-27, "ronto", null],
                ["q", 1e-30, "quecto", null],
            ];
        }
        build_basis() {
            const { _basis_template, _short_name, _long_name, _tex_repr } = this;
            const { include, exclude } = this;
            const basis = _basis_template.map(([short_prefix, factor, long_prefix, tex_prefix]) => {
                return {
                    short_name: `${short_prefix}${_short_name}`,
                    factor,
                    long_name: `${long_prefix}${_long_name}`,
                    tex_repr: `${tex_prefix !== null && tex_prefix !== void 0 ? tex_prefix : short_prefix}${_tex_repr}`,
                };
            }).filter(({ short_name }) => {
                return (include == null || include.includes(short_name)) && !exclude.includes(short_name);
            });
            return (0, arrayable_1.sort_by)(basis, ({ factor }) => factor);
        }
        get basis() {
            if (this._basis == null) {
                this._basis = this.build_basis();
            }
            return this._basis;
        }
    }
    exports.Metric = Metric;
    _b = Metric;
    Metric.__name__ = "Metric";
    (() => {
        _b.override({
            ticks: [1, 2, 5, 10, 15, 20, 25, 50, 75, 100, 125, 150, 200, 250, 500, 750],
        });
    })();
    class MetricLength extends Metric {
        constructor(attrs) {
            super(attrs);
            this._short_name = "m";
            this._long_name = "meter";
            this._tex_repr = "m";
        }
    }
    exports.MetricLength = MetricLength;
    _c = MetricLength;
    MetricLength.__name__ = "MetricLength";
    (() => {
        _c.override({
            exclude: ["dm", "hm"],
        });
    })();
},
/* models/annotations/slope.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    class SlopeView extends annotation_1.AnnotationView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
        }
        _render() {
            const { gradient, y_intercept } = this.model;
            if (gradient == null || y_intercept == null)
                return;
            const { frame } = this.plot_view;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const [sx0, sx1, sy0, sy1] = (() => {
                if (gradient == 0) {
                    const sy_start = yscale.compute(y_intercept);
                    const sy_end = sy_start;
                    const sx_start = frame.bbox.left;
                    const sx_end = frame.bbox.right;
                    return [sx_start, sx_end, sy_start, sy_end];
                }
                else {
                    const sy_start = frame.bbox.top;
                    const sy_end = frame.bbox.bottom;
                    const y_start = yscale.invert(sy_start);
                    const y_end = yscale.invert(sy_end);
                    const x_start = (y_start - y_intercept) / gradient;
                    const x_end = (y_end - y_intercept) / gradient;
                    const sx_start = xscale.compute(x_start);
                    const sx_end = xscale.compute(x_end);
                    if (sx_start <= sx_end)
                        return [sx_start, sx_end, sy_start, sy_end];
                    else
                        return [sx_end, sx_start, sy_end, sy_start];
                }
            })();
            const { ctx } = this.layer;
            ctx.save();
            if (this.visuals.above_fill.doit || this.visuals.above_hatch.doit) {
                const { left, right, top, bottom } = frame.bbox;
                ctx.beginPath();
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
                ctx.lineTo(sx1, sy1);
                if (sy0 <= sy1) {
                    if (sx1 < right)
                        ctx.lineTo(right, bottom);
                    ctx.lineTo(right, top);
                    ctx.lineTo(left, top);
                }
                else {
                    ctx.lineTo(right, top);
                    ctx.lineTo(left, top);
                    if (sx0 > left)
                        ctx.lineTo(left, bottom);
                }
                ctx.closePath();
                this.visuals.above_fill.apply(ctx);
                this.visuals.above_hatch.apply(ctx);
            }
            if (this.visuals.below_fill.doit || this.visuals.below_hatch.doit) {
                const { left, right, top, bottom } = frame.bbox;
                ctx.beginPath();
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
                if (sy0 <= sy1) {
                    ctx.lineTo(right, bottom);
                    ctx.lineTo(left, bottom);
                    if (sx0 > left)
                        ctx.lineTo(left, top);
                }
                else {
                    if (sx1 < right)
                        ctx.lineTo(right, top);
                    ctx.lineTo(right, bottom);
                    ctx.lineTo(left, bottom);
                }
                ctx.closePath();
                this.visuals.below_fill.apply(ctx);
                this.visuals.below_hatch.apply(ctx);
            }
            ctx.beginPath();
            ctx.moveTo(sx0, sy0);
            ctx.lineTo(sx1, sy1);
            this.visuals.line.apply(ctx);
            ctx.restore();
        }
    }
    exports.SlopeView = SlopeView;
    SlopeView.__name__ = "SlopeView";
    class Slope extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Slope = Slope;
    _a = Slope;
    Slope.__name__ = "Slope";
    (() => {
        _a.prototype.default_view = SlopeView;
        _a.mixins([
            mixins.Line,
            ["above_", mixins.Fill],
            ["above_", mixins.Hatch],
            ["below_", mixins.Fill],
            ["below_", mixins.Hatch],
        ]);
        _a.define(({ Number, Nullable }) => ({
            gradient: [Nullable(Number), null],
            y_intercept: [Nullable(Number), null],
        }));
        _a.override({
            line_color: "black",
            above_fill_color: null,
            above_fill_alpha: 0.4,
            below_fill_color: null,
            below_fill_alpha: 0.4,
        });
    })();
},
/* models/annotations/span.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(73) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const hittest_1 = require(212) /* ../../core/hittest */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const EDGE_TOLERANCE = 2.5;
    class Line {
        constructor(p0, p1) {
            this.p0 = p0;
            this.p1 = p1;
        }
        clone() {
            return new Line(Object.assign({}, this.p0), Object.assign({}, this.p1));
        }
        hit_test(pt, tolerance = EDGE_TOLERANCE) {
            return (0, hittest_1.dist_to_segment)(pt, this.p0, this.p1) < tolerance;
        }
        translate(dx, dy) {
            const { p0, p1 } = this;
            const dp0 = { x: p0.x + dx, y: p0.y + dy };
            const dp1 = { x: p1.x + dx, y: p1.y + dy };
            return new Line(dp0, dp1);
        }
    }
    Line.__name__ = "Line";
    class SpanView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._pan_state = null;
            this._is_hovered = false;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.plot_view.request_paint(this));
        }
        _render() {
            const { location, location_units } = this.model;
            if (location == null)
                return;
            function compute(value, units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas.compute(value);
                    case "screen": return view.compute(value);
                    case "data": return scale.compute(value);
                }
            }
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = this.coordinates;
            let height, sleft, stop, width;
            if (this.model.dimension == "width") {
                stop = compute(location, location_units, y_scale, frame.bbox.yview, canvas.bbox.y_screen);
                sleft = frame.bbox.left;
                width = frame.bbox.width;
                height = this.model.line_width;
            }
            else {
                stop = frame.bbox.top;
                sleft = compute(location, location_units, x_scale, frame.bbox.xview, canvas.bbox.y_screen);
                width = this.model.line_width;
                height = frame.bbox.height;
            }
            const p0 = { x: sleft, y: stop };
            const p1 = { x: sleft + width, y: stop + height };
            this.line = new Line(p0, p1);
            const { _is_hovered, visuals } = this;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            const { ctx } = this.layer;
            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);
            }
            line.apply(ctx);
            ctx.restore();
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable)
                return false;
            return this._hit_test(sx, sy) != null;
        }
        _hit_test(sx, sy) {
            const tolerance = Math.max(EDGE_TOLERANCE, this.model.line_width / 2);
            return this.line.hit_test({ x: sx, y: sy }, tolerance) ? "edge" : null;
        }
        _can_hit(_target) {
            return true;
        }
        _pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        line: this.line.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        _pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            function invert(sv, units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas.invert(sv);
                    case "screen": return view.invert(sv);
                    case "data": return scale.invert(sv);
                }
            }
            const sloc = (() => {
                const { dx, dy } = ev;
                const { line } = this._pan_state;
                if (this.model.dimension == "width") {
                    return line.translate(0, dy).p0.y;
                }
                else {
                    return line.translate(dx, 0).p0.x;
                }
            })();
            const loc = (() => {
                const { location_units } = this.model;
                const { frame, canvas } = this.plot_view;
                const { x_scale, y_scale } = this.coordinates;
                if (this.model.dimension == "width") {
                    return invert(sloc, location_units, y_scale, frame.bbox.yview, canvas.bbox.y_screen);
                }
                else {
                    return invert(sloc, location_units, x_scale, frame.bbox.xview, canvas.bbox.y_screen);
                }
            })();
            this.model.location = loc;
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        _pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line } = this.visuals;
            return hover_line.doit;
        }
        _move_start(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        _move(_ev) { }
        _move_end(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            var _b, _c;
            const target = (_c = (_b = this._pan_state) === null || _b === void 0 ? void 0 : _b.target) !== null && _c !== void 0 ? _c : this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            return this.model.dimension == "width" ? "ns-resize" : "ew-resize";
        }
    }
    exports.SpanView = SpanView;
    SpanView.__name__ = "SpanView";
    class Span extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
            this.pan = new signaling_1.Signal(this, "pan");
        }
    }
    exports.Span = Span;
    _a = Span;
    Span.__name__ = "Span";
    (() => {
        _a.prototype.default_view = SpanView;
        _a.mixins([
            mixins.Line,
            ["hover_", mixins.Line],
        ]);
        _a.define(({ Boolean, Number, Nullable }) => ({
            location: [Nullable(Number), null],
            location_units: [enums_1.CoordinateUnits, "data"],
            dimension: [enums_1.Dimension, "width"],
            editable: [Boolean, false],
        }));
        _a.override({
            line_color: "black",
            hover_line_color: null,
            hover_line_alpha: 0.3,
        });
    })();
},
/* models/annotations/toolbar_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const annotation_1 = require(73) /* ./annotation */;
    const toolbar_1 = require(265) /* ../tools/toolbar */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const dom_1 = require(56) /* ../../core/dom */;
    const side_panel_1 = require(146) /* ../../core/layout/side_panel */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    class ToolbarPanelView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this.el = (0, dom_1.div)();
            this._previous_bbox = new bbox_1.BBox();
        }
        update_layout() {
            this.layout = new side_panel_1.SideLayout(this.panel, () => this.get_size(), true);
        }
        has_finished() {
            return super.has_finished() && this.toolbar_view.has_finished();
        }
        *children() {
            yield* super.children();
            yield this.toolbar_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.toolbar_view = await (0, build_views_1.build_view)(this.model.toolbar, { parent: this.canvas });
        }
        connect_signals() {
            super.connect_signals();
            this.plot_view.mouseenter.connect(() => {
                this.toolbar_view.set_visibility(true);
            });
            this.plot_view.mouseleave.connect(() => {
                this.toolbar_view.set_visibility(false);
            });
        }
        remove() {
            this.toolbar_view.remove();
            (0, dom_1.remove)(this.el);
            super.remove();
        }
        _render() {
            (0, dom_1.display)(this.el);
            // TODO: this should be handled by the layout
            const { bbox } = this.layout;
            if (!this._previous_bbox.equals(bbox)) {
                (0, dom_1.position)(this.el, bbox);
                this._previous_bbox = bbox;
                (0, dom_1.empty)(this.el);
                this.el.style.position = "absolute";
                const { style } = this.toolbar_view.el;
                if (this.toolbar_view.model.horizontal) {
                    style.width = "100%";
                    style.height = "unset";
                }
                else {
                    style.width = "unset";
                    style.height = "100%";
                }
                this.toolbar_view.render();
                this.plot_view.canvas_view.add_event(this.el);
                this.el.appendChild(this.toolbar_view.el);
                this.toolbar_view.after_render();
            }
            if (!this.model.visible) {
                (0, dom_1.undisplay)(this.el);
            }
        }
        _get_size() {
            const { tools, logo } = this.model.toolbar;
            return {
                width: tools.length * 30 + (logo != null ? 25 : 0) + 15,
                height: 30,
            };
        }
    }
    exports.ToolbarPanelView = ToolbarPanelView;
    ToolbarPanelView.__name__ = "ToolbarPanelView";
    class ToolbarPanel extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ToolbarPanel = ToolbarPanel;
    _a = ToolbarPanel;
    ToolbarPanel.__name__ = "ToolbarPanel";
    (() => {
        _a.prototype.default_view = ToolbarPanelView;
        _a.define(({ Ref }) => ({
            toolbar: [Ref(toolbar_1.Toolbar)],
        }));
    })();
},
/* models/tools/toolbar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const logging_1 = require(19) /* ../../core/logging */;
    const dom_1 = require(56) /* ../../core/dom */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const tool_1 = require(273) /* ./tool */;
    const tool_proxy_1 = require(274) /* ./tool_proxy */;
    const tool_button_1 = require(275) /* ./tool_button */;
    const gesture_tool_1 = require(280) /* ./gestures/gesture_tool */;
    const inspect_tool_1 = require(282) /* ./inspectors/inspect_tool */;
    const action_tool_1 = require(283) /* ./actions/action_tool */;
    const help_tool_1 = require(285) /* ./actions/help_tool */;
    const menus_1 = require(276) /* ../../core/util/menus */;
    const toolbar_css_1 = tslib_1.__importStar(require(286) /* ../../styles/toolbar.css */), toolbars = toolbar_css_1;
    const logo_css_1 = tslib_1.__importStar(require(287) /* ../../styles/logo.css */), logos = logo_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(278) /* ../../styles/icons.css */);
    class ToolbarView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._tool_button_views = new Map();
            this._items = [];
            this._visible = null;
        }
        get tool_buttons() {
            return this._tool_buttons.flat();
        }
        get overflow_el() {
            return this._overflow_el;
        }
        get visible() {
            var _b;
            return !this.model.visible ? false : (!this.model.autohide || ((_b = this._visible) !== null && _b !== void 0 ? _b : false));
        }
        *children() {
            yield* super.children();
            yield* this._tool_button_views.values();
        }
        has_finished() {
            if (!super.has_finished())
                return false;
            for (const child_view of this._tool_button_views.values()) {
                if (!child_view.has_finished())
                    return false;
            }
            return true;
        }
        initialize() {
            super.initialize();
            const { location } = this.model;
            const reversed = location == "left" || location == "above";
            const orientation = this.model.horizontal ? "vertical" : "horizontal";
            this._overflow_menu = new menus_1.ContextMenu([], {
                target: this.root.el,
                orientation,
                reversed,
                prevent_hide: (event) => {
                    return event.composedPath().includes(this._overflow_el);
                },
            });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_tool_button_views();
        }
        connect_signals() {
            super.connect_signals();
            const { buttons, tools } = this.model.properties;
            this.on_change([buttons, tools], async () => {
                await this._build_tool_button_views();
                this.render();
            });
            this.connect(this.model.properties.autohide.change, () => {
                this._on_visible_change();
            });
        }
        stylesheets() {
            return [...super.stylesheets(), toolbar_css_1.default, logo_css_1.default, icons_css_1.default];
        }
        remove() {
            (0, build_views_1.remove_views)(this._tool_button_views);
            super.remove();
        }
        async _build_tool_button_views() {
            this._tool_buttons = (() => {
                const { buttons } = this.model;
                if (buttons == "auto") {
                    const groups = [
                        ...(0, object_1.values)(this.model.gestures).map((gesture) => gesture.tools),
                        this.model.actions,
                        this.model.inspectors.filter((tool) => tool.toggleable),
                        this.model.auxiliaries,
                    ];
                    return groups.map((group) => group.map((tool) => tool.tool_button()));
                }
                else {
                    return (0, array_1.split)(buttons, null);
                }
            })();
            await (0, build_views_1.build_views)(this._tool_button_views, this._tool_buttons.flat(), { parent: this });
        }
        set_visibility(visible) {
            if (visible != this._visible) {
                this._visible = visible;
                this._on_visible_change();
            }
        }
        _on_visible_change() {
            this.el.classList.toggle(toolbars.hidden, !this.visible);
        }
        _after_resize() {
            super._after_resize();
            this._after_render();
        }
        render() {
            super.render();
            this.el.classList.add(toolbars[this.model.location]);
            this.el.classList.toggle(toolbars.inner, this.model.inner);
            this._on_visible_change();
            const { horizontal } = this.model;
            this._overflow_el = (0, dom_1.div)({ class: toolbars.tool_overflow, tabIndex: 0 }, horizontal ? "⋮" : "⋯");
            const toggle_menu = () => {
                const at = (() => {
                    switch (this.model.location) {
                        case "right": return { left_of: this._overflow_el };
                        case "left": return { right_of: this._overflow_el };
                        case "above": return { below: this._overflow_el };
                        case "below": return { above: this._overflow_el };
                    }
                })();
                this._overflow_menu.toggle(at);
            };
            this._overflow_el.addEventListener("click", () => {
                toggle_menu();
            });
            this._overflow_el.addEventListener("keydown", (event) => {
                if (event.key == "Enter") {
                    toggle_menu();
                }
            });
            this._items = [];
            if (this.model.logo != null) {
                const gray = this.model.logo === "grey" ? logos.grey : null;
                const logo_el = (0, dom_1.a)({ href: "https://bokeh.org/", target: "_blank", class: [logos.logo, logos.logo_small, gray] });
                this._items.push(logo_el);
                this.shadow_el.appendChild(logo_el);
            }
            for (const [, button_view] of this._tool_button_views) {
                button_view.render();
                button_view.after_render();
            }
            const bars = this._tool_buttons.map((group) => group.map((button) => this._tool_button_views.get(button).el));
            const non_empty = bars.filter((bar) => bar.length != 0);
            const divider = () => (0, dom_1.div)({ class: toolbars.divider });
            for (const el of (0, iterator_1.join)(non_empty, divider)) {
                this._items.push(el);
                this.shadow_el.appendChild(el);
            }
        }
        _after_render() {
            super._after_render();
            (0, array_1.clear)(this._overflow_menu.items);
            if (this.shadow_el.contains(this._overflow_el)) {
                this.shadow_el.removeChild(this._overflow_el);
            }
            for (const el of this._items) {
                if (!this.shadow_el.contains(el)) {
                    this.shadow_el.append(el);
                }
            }
            const { horizontal } = this.model;
            const overflow_size = 15;
            const { bbox } = this;
            const overflow_cls = horizontal ? toolbars.right : toolbars.above;
            let size = 0;
            let overflowed = false;
            for (const el of this._items) {
                if (overflowed) {
                    this.shadow_el.removeChild(el);
                    this._overflow_menu.items.push({ custom: el, class: overflow_cls });
                }
                else {
                    const { width, height } = el.getBoundingClientRect();
                    size += horizontal ? width : height;
                    overflowed = horizontal ? size > bbox.width - overflow_size : size > bbox.height - overflow_size;
                    if (overflowed) {
                        this.shadow_el.removeChild(el);
                        this.shadow_el.appendChild(this._overflow_el);
                        this._overflow_menu.items.push({ custom: el, class: overflow_cls });
                    }
                }
            }
        }
    }
    exports.ToolbarView = ToolbarView;
    ToolbarView.__name__ = "ToolbarView";
    exports.Drag = tool_1.Tool;
    exports.Inspection = tool_1.Tool;
    exports.Scroll = tool_1.Tool;
    exports.Tap = tool_1.Tool;
    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 },
        };
    }
    class Toolbar extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        get horizontal() {
            return this.location == "above" || this.location == "below";
        }
        get vertical() {
            return this.location == "left" || this.location == "right";
        }
        connect_signals() {
            super.connect_signals();
            const { tools, active_drag, active_inspect, active_scroll, active_tap, active_multi } = this.properties;
            this.on_change([tools, active_drag, active_inspect, active_scroll, active_tap, active_multi], () => {
                this._init_tools();
                this._activate_tools();
            });
        }
        initialize() {
            super.initialize();
            this._init_tools();
            this._activate_tools();
        }
        _init_tools() {
            const visited = new Set();
            function isa(tool, type) {
                const is = (tool instanceof tool_proxy_1.ToolProxy ? tool.underlying : tool) instanceof type;
                if (is) {
                    visited.add(tool);
                }
                return is;
            }
            const new_inspectors = this.tools.filter(t => isa(t, inspect_tool_1.InspectTool));
            this.inspectors = new_inspectors;
            const new_help = this.tools.filter(t => isa(t, help_tool_1.HelpTool));
            this.help = new_help;
            const new_actions = this.tools.filter(t => isa(t, action_tool_1.ActionTool));
            this.actions = new_actions;
            const new_gestures = create_gesture_map();
            for (const tool of this.tools) {
                if (isa(tool, gesture_tool_1.GestureTool)) {
                    new_gestures[tool.event_role].tools.push(tool);
                }
            }
            for (const et of (0, object_1.typed_keys)(new_gestures)) {
                const gesture = this.gestures[et];
                gesture.tools = (0, array_1.sort_by)(new_gestures[et].tools, (tool) => tool.default_order);
                if (gesture.active != null && (0, array_1.every)(gesture.tools, (tool) => { var _b; return tool.id != ((_b = gesture.active) === null || _b === void 0 ? void 0 : _b.id); })) {
                    gesture.active = null;
                }
            }
            const new_auxiliaries = this.tools.filter((tool) => !visited.has(tool));
            this.auxiliaries = new_auxiliaries;
        }
        _activate_tools() {
            if (this.active_inspect == "auto") {
                // do nothing as all tools are active be default
            }
            else if (this.active_inspect == null) {
                for (const inspector of this.inspectors)
                    inspector.active = false;
            }
            else if ((0, types_1.isArray)(this.active_inspect)) {
                const active_inspect = (0, array_1.intersection)(this.active_inspect, this.inspectors);
                if (active_inspect.length != this.active_inspect.length) {
                    this.active_inspect = active_inspect;
                }
                for (const inspector of this.inspectors) {
                    if (!(0, array_1.includes)(this.active_inspect, inspector))
                        inspector.active = false;
                }
            }
            else {
                let found = false;
                for (const inspector of this.inspectors) {
                    if (inspector != this.active_inspect)
                        inspector.active = false;
                    else
                        found = true;
                }
                if (!found) {
                    this.active_inspect = null;
                }
            }
            const _activate_gesture = (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;
            };
            // Connecting signals has to be done before changing the active state of the tools.
            for (const gesture of (0, object_1.values)(this.gestures)) {
                for (const tool of gesture.tools) {
                    // XXX: connect once
                    this.connect(tool.properties.active.change, () => this._active_change(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";
                    default: return null;
                }
            }
            function _supports_auto(et) {
                return et == "tap" || et == "pan";
            }
            for (const [event_role, gesture] of (0, object_1.entries)(this.gestures)) {
                const et = event_role;
                const active_attr = _get_active_attr(et);
                if (active_attr != null) {
                    const 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) {
                        // TODO: allow to activate a proxy of tools with any child?
                        if ((0, array_1.includes)(this.tools, active_tool)) {
                            _activate_gesture(active_tool); // XXX: remove this cast
                        }
                        else {
                            this[active_attr] = null;
                        }
                    }
                    else {
                        this.gestures[et].active = null;
                        for (const tool of this.gestures[et].tools) {
                            tool.active = false;
                        }
                    }
                }
            }
        }
        _active_change(tool) {
            const { event_types } = tool;
            for (const et of event_types) {
                if (tool.active) {
                    const 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;
            }
        }
    }
    exports.Toolbar = Toolbar;
    _a = Toolbar;
    Toolbar.__name__ = "Toolbar";
    (() => {
        _a.prototype.default_view = ToolbarView;
        _a.define(({ Boolean, Array, Or, Ref, Nullable, Auto }) => ({
            tools: [Array(Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))), []],
            logo: [Nullable(enums_1.Logo), "normal"],
            autohide: [Boolean, false],
            active_drag: [Nullable(Or(Ref(exports.Drag), Auto)), "auto"],
            active_inspect: [Nullable(Or(Ref(exports.Inspection), Array(Ref(exports.Inspection)), Auto)), "auto"],
            active_scroll: [Nullable(Or(Ref(exports.Scroll), Auto)), "auto"],
            active_tap: [Nullable(Or(Ref(exports.Tap), Auto)), "auto"],
            active_multi: [Nullable(Or(Ref(gesture_tool_1.GestureTool), Auto)), "auto"],
        }));
        _a.internal(({ Array, Boolean, Ref, Or, Struct, Nullable, Null, Auto }) => {
            const GestureEntry = Struct({
                tools: Array(Ref(gesture_tool_1.GestureTool)),
                active: Nullable(Ref(gesture_tool_1.GestureTool)),
            });
            const GestureMap = Struct({
                pan: GestureEntry,
                scroll: GestureEntry,
                pinch: GestureEntry,
                tap: GestureEntry,
                doubletap: GestureEntry,
                press: GestureEntry,
                pressup: GestureEntry,
                rotate: GestureEntry,
                move: GestureEntry,
                multi: GestureEntry,
            });
            return {
                buttons: [Or(Array(Or(Ref(tool_button_1.ToolButton), Null)), Auto), "auto"],
                location: [enums_1.Location, "right"],
                inner: [Boolean, false],
                gestures: [GestureMap, create_gesture_map],
                actions: [Array(Or(Ref(action_tool_1.ActionTool), Ref(tool_proxy_1.ToolProxy))), []],
                inspectors: [Array(Or(Ref(inspect_tool_1.InspectTool), Ref(tool_proxy_1.ToolProxy))), []],
                auxiliaries: [Array(Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))), []],
                help: [Array(Or(Ref(help_tool_1.HelpTool), Ref(tool_proxy_1.ToolProxy))), []],
            };
        });
    })();
},
/* models/ui/ui_element.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(50) /* ../../model */;
    const styles_1 = require(267) /* ../dom/styles */;
    const stylesheets_1 = require(268) /* ../dom/stylesheets */;
    const logging_1 = require(19) /* ../../core/logging */;
    const dom_view_1 = require(55) /* ../../core/dom_view */;
    const dom_1 = require(56) /* ../../core/dom */;
    const canvas_1 = require(269) /* ../../core/util/canvas */;
    const object_1 = require(9) /* ../../core/util/object */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const types_1 = require(8) /* ../../core/util/types */;
    const ui_css_1 = tslib_1.__importDefault(require(272) /* ../../styles/ui.css */);
    const { round, floor } = Math;
    function* _iter_styles(styles) {
        if (styles instanceof styles_1.Styles) {
            const model_attrs = new Set((0, object_1.keys)(model_1.Model.prototype._props));
            for (const prop of styles) {
                if (!model_attrs.has(prop.attr)) {
                    yield [prop.attr, prop.get_value()];
                }
            }
        }
        else
            yield* (0, object_1.entries)(styles);
    }
    class UIElementView extends dom_view_1.DOMComponentView {
        constructor() {
            super(...arguments);
            this._display = new dom_1.InlineStyleSheet();
            this.style = new dom_1.InlineStyleSheet();
            this._bbox = new bbox_1.BBox();
            this._is_displayed = false;
        }
        *_css_classes() {
            yield* super._css_classes();
            yield* this.model.css_classes;
        }
        *_stylesheets() {
            yield* super._stylesheets();
            yield this.style;
            yield this._display;
            yield* this._computed_stylesheets();
        }
        *_computed_stylesheets() {
            for (const stylesheet of this.model.stylesheets) {
                if ((0, types_1.isString)(stylesheet)) {
                    yield new dom_1.InlineStyleSheet(stylesheet);
                }
                else if (stylesheet instanceof stylesheets_1.StyleSheet) {
                    yield stylesheet.underlying();
                }
                else {
                    const output = [];
                    for (const [selector, styles] of (0, object_1.entries)(stylesheet)) {
                        output.push(`${selector} {`);
                        for (const [attr, value] of _iter_styles(styles)) {
                            const name = attr.replace(/_/g, "-");
                            if ((0, types_1.isString)(value) && value.length != 0) {
                                output.push(`  ${name}: ${value};`);
                            }
                        }
                        output.push("}");
                    }
                    const css = output.join("\n");
                    yield new dom_1.InlineStyleSheet(css);
                }
            }
        }
        stylesheets() {
            return [...super.stylesheets(), ui_css_1.default];
        }
        update_style() {
            this.style.clear();
        }
        box_sizing() {
            return {
                width_policy: "auto", height_policy: "auto",
                width: null, height: null,
                aspect_ratio: null,
            };
        }
        get bbox() {
            return this._bbox;
        }
        update_bbox() {
            return this._update_bbox();
        }
        _update_bbox() {
            const displayed = (() => {
                // Consider using Element.checkVisibility() in the future.
                // https://w3c.github.io/csswg-drafts/cssom-view-1/#dom-element-checkvisibility
                if (!this.el.isConnected)
                    return false;
                else if (this.el.offsetParent != null)
                    return true;
                else {
                    const { position, display } = getComputedStyle(this.el);
                    return position == "fixed" && display != "none";
                }
            })();
            const bbox = !displayed ? new bbox_1.BBox() : (() => {
                const self = this.el.getBoundingClientRect();
                const { left, top } = (() => {
                    if (this.parent != null) {
                        const parent = this.parent.el.getBoundingClientRect();
                        return {
                            left: self.left - parent.left,
                            top: self.top - parent.top,
                        };
                    }
                    else {
                        return { left: 0, top: 0 };
                    }
                })();
                return new bbox_1.BBox({
                    left: round(left),
                    top: round(top),
                    width: floor(self.width),
                    height: floor(self.height),
                });
            })();
            const changed = !this._bbox.equals(bbox);
            this._bbox = bbox;
            this._is_displayed = displayed;
            return changed;
        }
        initialize() {
            super.initialize();
            this._resize_observer = new ResizeObserver((_entries) => this.after_resize());
            this._resize_observer.observe(this.el, { box: "border-box" });
        }
        connect_signals() {
            super.connect_signals();
            const { visible, styles, css_classes, stylesheets } = this.model.properties;
            this.on_change(visible, () => this._update_visible());
            this.on_change(styles, () => this._update_styles());
            this.on_change(css_classes, () => this._update_css_classes());
            this.on_change(stylesheets, () => this._update_stylesheets());
        }
        remove() {
            this._resize_observer.disconnect();
            super.remove();
        }
        _after_resize() { }
        after_resize() {
            if (this.update_bbox()) {
                this._after_resize();
            }
            this.finish();
        }
        render_to(element) {
            super.render_to(element);
            this.after_render();
        }
        render() {
            super.render();
            this._apply_styles();
            this._apply_visible();
        }
        _after_render() { }
        after_render() {
            this.update_style();
            this.update_bbox();
            this._after_render();
            // If not displayed, then after_resize() will not be called.
            if (!this.is_displayed) {
                this.finish();
            }
        }
        get is_displayed() {
            return this._is_displayed;
        }
        _apply_visible() {
            if (this.model.visible)
                this._display.clear();
            else {
                // in case `display` element style was set, use `!important` to work around this
                this._display.replace(":host { display: none !important; }");
            }
        }
        _apply_styles() {
            const { styles } = this.model;
            const apply = (name, value) => {
                const known = name in this.el.style; // XXX: hasOwnProperty() doesn't work for unknown reasons
                if (known && (0, types_1.isString)(value)) {
                    this.el.style[name] = value; // XXX: setProperty() doesn't support camel-case
                }
                return known;
            };
            for (const [attr, value] of _iter_styles(styles)) {
                const name = attr.replace(/_/g, "-");
                if (!apply(name, value)) {
                    if (!apply(`-webkit-${name}`, value) && !apply(`-moz-${name}`, value))
                        logging_1.logger.trace(`unknown CSS property '${name}'`);
                }
            }
        }
        _update_visible() {
            this._apply_visible();
        }
        _update_styles() {
            this.el.removeAttribute("style"); // TODO: maintain _applied_styles
            this._apply_styles();
        }
        export(type = "auto", hidpi = true) {
            const output_backend = type == "auto" || type == "png" ? "canvas" : "svg";
            const canvas = new canvas_1.CanvasLayer(output_backend, hidpi);
            const { width, height } = this.bbox;
            canvas.resize(width, height);
            return canvas;
        }
        serializable_state() {
            return Object.assign(Object.assign({}, super.serializable_state()), { bbox: this.bbox });
        }
    }
    exports.UIElementView = UIElementView;
    UIElementView.__name__ = "UIElementView";
    class UIElement extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.UIElement = UIElement;
    _a = UIElement;
    UIElement.__name__ = "UIElement";
    (() => {
        _a.define(({ Boolean, Array, Dict, String, Ref, Or, Nullable }) => {
            const StylesLike = Or(Dict(Nullable(String)), Ref(styles_1.Styles)); // TODO: add validation for CSSStyles
            return {
                visible: [Boolean, true],
                css_classes: [Array(String), []],
                styles: [StylesLike, {}],
                stylesheets: [Array(Or(Ref(stylesheets_1.StyleSheet), String, Dict(StylesLike))), []],
            };
        });
    })();
},
/* models/dom/styles.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class Styles extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Styles = Styles;
    _a = Styles;
    Styles.__name__ = "Styles";
    (() => {
        _a.define(({ String, Nullable }) => ({
            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],
            aspect_ratio: [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],
            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/dom/stylesheets.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(50) /* ../../model */;
    const dom = tslib_1.__importStar(require(56) /* ../../core/dom */);
    class StyleSheet extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.StyleSheet = StyleSheet;
    StyleSheet.__name__ = "StyleSheet";
    class InlineStyleSheet extends StyleSheet {
        constructor(attrs) {
            super(attrs);
        }
        underlying() {
            return new dom.InlineStyleSheet(this.css);
        }
    }
    exports.InlineStyleSheet = InlineStyleSheet;
    _a = InlineStyleSheet;
    InlineStyleSheet.__name__ = "InlineStyleSheet";
    (() => {
        _a.define(({ String }) => ({
            css: [String],
        }));
    })();
    class ImportedStyleSheet extends StyleSheet {
        constructor(attrs) {
            super(attrs);
        }
        underlying() {
            return new dom.ImportedStyleSheet(this.url);
        }
    }
    exports.ImportedStyleSheet = ImportedStyleSheet;
    _b = ImportedStyleSheet;
    ImportedStyleSheet.__name__ = "ImportedStyleSheet";
    (() => {
        _b.define(({ String }) => ({
            url: [String],
        }));
    })();
    class GlobalInlineStyleSheet extends InlineStyleSheet {
        constructor(attrs) {
            super(attrs);
            this._underlying = null;
        }
        underlying() {
            if (this._underlying == null)
                this._underlying = new dom.GlobalInlineStyleSheet(this.css);
            return this._underlying;
        }
    }
    exports.GlobalInlineStyleSheet = GlobalInlineStyleSheet;
    GlobalInlineStyleSheet.__name__ = "GlobalInlineStyleSheet";
    class GlobalImportedStyleSheet extends ImportedStyleSheet {
        constructor(attrs) {
            super(attrs);
            this._underlying = null;
        }
        underlying() {
            if (this._underlying == null) {
                this._underlying = new dom.GlobalImportedStyleSheet(this.url);
            }
            return this._underlying;
        }
    }
    exports.GlobalImportedStyleSheet = GlobalImportedStyleSheet;
    GlobalImportedStyleSheet.__name__ = "GlobalImportedStyleSheet";
},
/* core/util/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const svg_1 = require(270) /* ./svg */;
    const bbox_1 = require(57) /* ./bbox */;
    const dom_1 = require(56) /* ../dom */;
    class CanvasLayer {
        get canvas() {
            return this._canvas;
        }
        get ctx() {
            return this._ctx;
        }
        get el() {
            return this._el;
        }
        constructor(backend, hidpi) {
            this.pixel_ratio = 1;
            this.bbox = new bbox_1.BBox();
            this.backend = backend;
            this.hidpi = hidpi;
            switch (backend) {
                case "webgl":
                case "canvas": {
                    this._el = this._canvas = (0, dom_1.canvas)({ class: "bk-layer" });
                    const 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": {
                    const ctx = new svg_1.SVGRenderingContext2D();
                    this._ctx = ctx;
                    this._canvas = ctx.get_svg();
                    this._el = (0, dom_1.div)({ class: "bk-layer" });
                    const shadow_el = this._el.attachShadow({ mode: "open" });
                    shadow_el.appendChild(this._canvas);
                    break;
                }
            }
            this._ctx.layer = this;
        }
        resize(width, height) {
            if (this.bbox.width == width && this.bbox.height == height)
                return;
            this.bbox = new bbox_1.BBox({ left: 0, top: 0, width, height });
            const { target } = this;
            target.width = width * this.pixel_ratio;
            target.height = height * this.pixel_ratio;
        }
        get target() {
            return this._ctx instanceof svg_1.SVGRenderingContext2D ? this._ctx : this.canvas;
        }
        undo_transform(fn) {
            const { ctx } = this;
            const current_transform = ctx.getTransform();
            ctx.resetTransform();
            try {
                fn(ctx);
            }
            finally {
                ctx.setTransform(current_transform);
            }
        }
        prepare() {
            const { ctx, hidpi, pixel_ratio } = this;
            ctx.save();
            if (hidpi) {
                ctx.scale(pixel_ratio, pixel_ratio);
                ctx.translate(0.5, 0.5);
            }
            this.clear();
        }
        clear() {
            const { x, y, width, height } = this.bbox;
            this.ctx.clearRect(x, y, width, height);
        }
        finish() {
            this.ctx.restore();
        }
        to_blob() {
            const { _canvas } = this;
            if (_canvas instanceof HTMLCanvasElement) {
                return new Promise((resolve, reject) => {
                    _canvas.toBlob((blob) => blob != null ? resolve(blob) : reject(), "image/png");
                });
            }
            else {
                const ctx = this._ctx;
                const svg = ctx.get_serialized_svg(true);
                const blob = new Blob([svg], { type: "image/svg+xml" });
                return Promise.resolve(blob);
            }
        }
    }
    exports.CanvasLayer = CanvasLayer;
    CanvasLayer.__name__ = "CanvasLayer";
},
/* core/util/svg.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    /**
     * Based on https://github.com/gliffy/canvas2svg
     */
    const affine_1 = require(155) /* ./affine */;
    const types_1 = require(8) /* ./types */;
    const random_1 = require(271) /* ./random */;
    const math_1 = require(11) /* ./math */;
    const dom_1 = require(56) /* ../dom */;
    // helper function to map named to numbered entities
    function createNamedToNumberedLookup(input, radix) {
        const lookup = new Map();
        const items = input.split(",");
        radix = radix !== null && radix !== void 0 ? radix : 10;
        // Map from named to numbered entities.
        for (let i = 0; i < items.length; i += 2) {
            const entity = `&${items[i + 1]};`;
            const 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) {
        // TODO: support rtl languages
        const mapping = { left: "start", right: "end", center: "middle", start: "start", end: "end" };
        return textAlign in mapping ? mapping[textAlign] : mapping.start;
    }
    // helper function to map canvas-textBaseline to svg-dominantBaseline
    function getDominantBaseline(textBaseline) {
        // INFO: not supported in all browsers
        const mapping = { alphabetic: "alphabetic", hanging: "hanging", top: "text-before-edge", bottom: "text-after-edge", middle: "central" };
        return textBaseline in mapping ? mapping[textBaseline] : mapping.alphabetic;
    }
    // Unpack entities lookup where the numbers are in radix 32 to reduce the size
    // entity mapping courtesy of tinymce
    const 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.
    const 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,
        },
        fontKerning: {
            canvas: "auto",
        },
        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",
        },
    };
    function is_VideoFrame(image) {
        return typeof VideoFrame !== "undefined" && image instanceof VideoFrame;
    }
    function width_height(image) {
        if (is_VideoFrame(image)) {
            return [image.codedWidth, image.codedHeight]; // TODO not sure if this makes any sense
        }
        else {
            function to_number(val) {
                return (0, types_1.isNumber)(val) ? val : val.baseVal.value;
            }
            const { width, height } = image;
            return [to_number(width), to_number(height)];
        }
    }
    class CanvasGradient {
        constructor(gradientNode, ctx) {
            this.__root = gradientNode;
            this.__ctx = ctx;
        }
        /**
         * Adds a color stop to the gradient root
         */
        addColorStop(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;
            const stop = this.__ctx.__createElement("stop");
            stop.setAttribute("offset", `${offset}`);
            if (color.indexOf("rgba") !== -1) {
                // separate alpha value, since webkit can't handle it
                const regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
                const matches = regex.exec(color);
                const [, r, g, b, a] = matches;
                stop.setAttribute("stop-color", `rgb(${r},${g},${b})`);
                stop.setAttribute("stop-opacity", a);
            }
            else {
                stop.setAttribute("stop-color", color);
            }
            this.__root.appendChild(stop);
        }
    }
    CanvasGradient.__name__ = "CanvasGradient";
    class CanvasPattern {
        constructor(pattern, ctx) {
            this.__root = pattern;
            this.__ctx = ctx;
        }
        setTransform(_transform) {
            throw new Error("not implemented");
        }
    }
    CanvasPattern.__name__ = "CanvasPattern";
    class SVGRenderingContext2D {
        get canvas() {
            // XXX: point back to this instance
            return this;
        }
        get width() {
            return this._width;
        }
        set width(width) {
            this._width = width;
            this.__root.setAttribute("width", `${width}`);
        }
        get height() {
            return this._height;
        }
        set height(height) {
            this._height = height;
            this.__root.setAttribute("height", `${height}`);
        }
        constructor(options) {
            var _a, _b, _c;
            this.__currentDefaultPath = "";
            this.__currentPosition = null;
            this.globalAlpha = 1.0;
            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) != null) {
                this.__ctx = options.ctx;
            }
            else {
                this.__canvas = this.__document.createElement("canvas");
                this.__ctx = this.__canvas.getContext("2d");
            }
            this.reset();
            // 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.__currentElement = this.__root;
            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);
        }
        // helper function that generates a random string
        _random_string() {
            const chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
            let str;
            do {
                str = SVGRenderingContext2D.__random.choices(12, chars).join("");
            } while (this.__ids.has(str));
            return str;
        }
        /**
         * Creates the specified svg element
         */
        __createElement(elementName, properties = {}, resetFill = false) {
            const 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");
            }
            const keys = Object.keys(properties);
            for (const key of keys) {
                element.setAttribute(key, `${properties[key]}`);
            }
            return element;
        }
        /**
         * Applies default canvas styles to the context
         */
        __setDefaultStyles() {
            // default 2d canvas context properties see:http://www.w3.org/TR/2dcontext/
            const keys = Object.keys(STYLES);
            const self = this;
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                self[key] = STYLES[key].canvas;
            }
        }
        /**
         * Applies styles on restore
         */
        __applyStyleState(styleState) {
            const keys = Object.keys(styleState);
            const self = this;
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                self[key] = styleState[key];
            }
        }
        /**
         * Gets the current style state
         */
        __getStyleState() {
            const keys = Object.keys(STYLES);
            const styleState = {};
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                styleState[key] = this[key];
            }
            return styleState;
        }
        /**
         * Apples the current styles to the current SVG element. On "ctx.fill" or "ctx.stroke"
         */
        __applyStyleToCurrentElement(type) {
            const 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, "")
              }
            }
            */
            const keys = Object.keys(STYLES);
            for (let i = 0; i < keys.length; i++) {
                const style = STYLES[keys[i]];
                const value = this[keys[i]];
                if (style.apply != null && style.apply.includes(type)) {
                    if (value instanceof CanvasPattern) {
                        for (const def of [...value.__ctx.__defs.childNodes]) {
                            if (def instanceof Element) {
                                const id = def.getAttribute("id");
                                this.__ids.add(id);
                                this.__defs.appendChild(def);
                            }
                        }
                        const id = value.__root.getAttribute("id");
                        currentElement.setAttribute(style.apply, `url(#${id})`);
                    }
                    else if (value instanceof CanvasGradient) {
                        const 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
                            const regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
                            const matches = regex.exec(value);
                            const [, r, g, b, a] = matches;
                            currentElement.setAttribute(style.svgAttr, `rgb(${r},${g},${b})`);
                            const opacity = parseFloat(a) * this.globalAlpha;
                            currentElement.setAttribute(`${style.svgAttr}-opacity`, `${opacity}`);
                        }
                        else {
                            let attr = style.svgAttr;
                            if (keys[i] === "globalAlpha") {
                                attr = `${type}-${style.svgAttr}`;
                                if (currentElement.getAttribute(attr) != null) {
                                    // 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
          */
        get_serialized_svg(fixNamedEntities = false) {
            let serialized = new XMLSerializer().serializeToString(this.__root);
            if (fixNamedEntities) {
                // loop over each named entity and replace with the proper equivalent.
                for (const [key, value] of namedEntities) {
                    const regexp = new RegExp(key, "gi");
                    if (regexp.test(serialized)) {
                        serialized = serialized.replace(regexp, value);
                    }
                }
            }
            return serialized;
        }
        get_svg() {
            return this.__root;
        }
        /**
          * Will generate a group tag.
          */
        save() {
            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
          */
        restore() {
            if (this.__stack.length == 0)
                return;
            const { transform, clip_path, attributes } = this.__stack.pop();
            this._transform = transform;
            this._clip_path = clip_path;
            this.__applyStyleState(attributes);
        }
        reset() {
            this.__setDefaultStyles();
            this.__stack = [];
        }
        _apply_transform(element, transform = this._transform) {
            if (!transform.is_identity) {
                element.setAttribute("transform", transform.toString());
            }
        }
        /**
          *  scales the current element
          */
        scale(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
          */
        rotate(angle) {
            if (!isFinite(angle))
                return;
            this._transform.rotate(angle);
        }
        /**
          * translates the current element
          */
        translate(x, y) {
            if (!isFinite(x + y))
                return;
            this._transform.translate(x, y);
        }
        /**
          * applies a transform to the current element
          */
        transform(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
          */
        beginPath() {
            // 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();
        }
        __init_element() {
            const path = this.__createElement("path", {}, true);
            this.__root.appendChild(path);
            this.__currentElement = path;
        }
        /**
          * Helper function to apply currentDefaultPath to current path element
          */
        __applyCurrentDefaultPath() {
            const 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
          */
        __addPathCommand(x, y, path) {
            const separator = this.__currentDefaultPath == "" ? "" : " ";
            this.__currentDefaultPath += separator + path;
            this.__currentPosition = { x, y };
        }
        get _hasCurrentDefaultPath() {
            return this.__currentDefaultPath != "";
        }
        /**
          * Adds the move command to the current path element,
          * if the currentPathElement is not empty create a new path element
          */
        moveTo(x, y) {
            if (!isFinite(x + y))
                return;
            const currentElement = this.__currentElement;
            if (currentElement.nodeName !== "path") {
                this.beginPath();
            }
            // creates a new subpath with the given point
            const [tx, ty] = this._transform.apply(x, y);
            this.__addPathCommand(tx, ty, `M ${tx} ${ty}`);
        }
        /**
          * Closes the current path
          */
        closePath() {
            if (this._hasCurrentDefaultPath) {
                this.__addPathCommand(NaN, NaN, "Z");
            }
        }
        /**
          * Adds a line to command
          */
        lineTo(x, y) {
            if (!isFinite(x + y))
                return;
            if (!this._hasCurrentDefaultPath)
                this.moveTo(x, y);
            else {
                const [tx, ty] = this._transform.apply(x, y);
                this.__addPathCommand(tx, ty, `L ${tx} ${ty}`);
            }
        }
        /**
          * Add a bezier command
          */
        bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
            if (!isFinite(cp1x + cp1y + cp2x + cp2y + x + y))
                return;
            const [tx, ty] = this._transform.apply(x, y);
            const [tcp1x, tcp1y] = this._transform.apply(cp1x, cp1y);
            const [tcp2x, tcp2y] = this._transform.apply(cp2x, cp2y);
            this.__addPathCommand(tx, ty, `C ${tcp1x} ${tcp1y} ${tcp2x} ${tcp2y} ${tx} ${ty}`);
        }
        /**
          * Adds a quadratic curve to command
          */
        quadraticCurveTo(cpx, cpy, x, y) {
            if (!isFinite(cpx + cpy + x + y))
                return;
            const [tx, ty] = this._transform.apply(x, y);
            const [tcpx, tcpy] = this._transform.apply(cpx, cpy);
            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
          */
        arcTo(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;
            // Issue #12699.
            // this.__currentPosition has already been transformed using this._transform.
            // Arguments to this function have not been transformed, so to compare the two need
            // to inverse transform this.__currentPosition.
            const inverse = this._transform.inverse();
            const [x0, y0] = inverse.apply(this.__currentPosition.x, 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([x, y]) {
                const len = Math.sqrt(x ** 2 + 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.
            const unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]);
            const 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
            const cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]);
            const theta = Math.acos(Math.abs(cos));
            // Calculate origin
            const 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],
            ]);
            const len_p1_origin = radius / Math.sin(theta / 2);
            const x = x1 + len_p1_origin * unit_vec_p1_origin[0];
            const 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)
            const 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)
            const 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)
                const x = vector[0];
                const y = vector[1];
                if (y >= 0) { // note that y axis points to its down
                    return Math.acos(x);
                }
                else {
                    return -Math.acos(x);
                }
            }
            const startAngle = getAngle(unit_vec_origin_start_tangent);
            const 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
          */
        stroke() {
            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);
            }
        }
        fill(path_or_fill_rule, fill_rule) {
            let path = null;
            if (path_or_fill_rule instanceof Path2D)
                path = path_or_fill_rule;
            else if (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.
          */
        rect(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);
            this.closePath();
        }
        /**
          * adds a rectangle element
          */
        fillRect(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
          */
        strokeRect(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
          */
        __clearCanvas() {
            (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.
          */
        clearRect(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;
            }
            const rect = this.__createElement("rect", { x, y, width, height, fill: "#FFFFFF" }, true);
            this._apply_transform(rect);
            this.__root.appendChild(rect);
        }
        roundRect(_x, _y, _w, _h, _radii) {
            throw new Error("not implemented");
        }
        /**
          * Adds a linear gradient to a defs tag.
          * Returns a canvas gradient object that has a reference to it's parent def
          */
        createLinearGradient(x1, y1, x2, y2) {
            if (!isFinite(x1 + y1 + x2 + y2))
                throw new Error("The provided double value is non-finite");
            const [tx1, ty1] = this._transform.apply(x1, y1);
            const [tx2, ty2] = this._transform.apply(x2, y2);
            const 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
          */
        createRadialGradient(x0, y0, r0, x1, y1, r1) {
            if (!isFinite(x0 + y0 + r0 + x1 + y1 + r1))
                throw new Error("The provided double value is non-finite");
            const [tx0, ty0] = this._transform.apply(x0, y0);
            const [tx1, ty1] = this._transform.apply(x1, y1);
            const 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);
        }
        createConicGradient(_start_angle, _x, _y) {
            throw Error("not implemented");
        }
        /**
          * Parses the font string and returns svg mapping
          */
        __parseFont() {
            const 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;
            const [, style, decoration, weight, size, , family] = regex.exec(this.font); // XXX: RegExpExecArray is incorrecdt
            const data = {
                style: style !== null && style !== void 0 ? style : "normal",
                size: size !== null && size !== void 0 ? size : "10px",
                family: family !== null && family !== void 0 ? family : "sans-serif",
                weight: weight !== null && weight !== void 0 ? weight : "normal",
                decoration: decoration !== null && decoration !== void 0 ? decoration : "normal",
            };
            return data;
        }
        /**
          * Fills or strokes text
          */
        __applyText(text, x, y, action) {
            const font = this.__parseFont();
            const 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,
                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);
            const el = (() => {
                if (this._clip_path != null) {
                    const 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
          */
        fillText(text, x, y) {
            if (!isFinite(x + y))
                return;
            this.__applyText(text, x, y, "fill");
        }
        /**
          * Strokes text
          */
        strokeText(text, x, y) {
            if (!isFinite(x + y))
                return;
            this.__applyText(text, x, y, "stroke");
        }
        /**
          * No need to implement this for svg.
          */
        measureText(text) {
            this.__ctx.font = this.font;
            return this.__ctx.measureText(text);
        }
        arc(x, y, radius, start_angle, end_angle, counterclockwise = false) {
            this.ellipse(x, y, radius, radius, 0, start_angle, end_angle, counterclockwise);
        }
        ellipse(x, y, radius_x, radius_y, rotation, start_angle, end_angle, 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");
            const initial_diff = counterclockwise ? end_angle - start_angle : start_angle - end_angle;
            start_angle = start_angle % (2 * Math.PI);
            end_angle = end_angle % (2 * Math.PI);
            const transform = new affine_1.AffineTransform().translate(x, y).rotate(rotation);
            const dx = radius_x * Math.cos(start_angle);
            const dy = radius_y * Math.sin(start_angle);
            const [start_x, start_y] = transform.apply(dx, dy);
            this.lineTo(start_x, start_y);
            // Canvas ellipse defines rotation in radians and SVG elliptical arc is defined in degrees
            const rotation_in_degrees = rotation * 180 / Math.PI;
            const sweep_flag = counterclockwise ? 0 : 1;
            /**
             * Check if need to draw full ellipse (issue #11475). When testing if angular difference is
             * equal to an integer multiple of 2*pi radians, need to account for float64 to float32 rounding
             * error on both the start and end angles, hence the factor of 2. Do not assume full circle if
             * start and end angles are close, but test here depends on combination of sign of angular
             * difference and wedge direction (clockwise/counterclockwise) to obtain the same results as on
             * canvas.
             */
            if (Math.abs(start_angle - end_angle) < 2 * math_1.float32_epsilon &&
                !(Math.abs(initial_diff) < 2 * math_1.float32_epsilon && initial_diff < 0)) {
                // Draw full ellipse. SVG elliptical arc cannot do this, so instead use two semi ellipses.
                const [tstart_x, tstart_y] = this._transform.apply(start_x, start_y);
                const dx = radius_x * Math.cos(start_angle + Math.PI);
                const dy = radius_y * Math.sin(start_angle + Math.PI);
                const [mid_x, mid_y] = transform.apply(dx, dy);
                const [tmid_x, tmid_y] = this._transform.apply(mid_x, mid_y);
                this.__addPathCommand(tstart_x, tstart_y, `A ${radius_x} ${radius_y} ${rotation_in_degrees} 0 ${sweep_flag} ${tmid_x} ${tmid_y} A ${radius_x} ${radius_y} ${rotation_in_degrees} 0 ${sweep_flag} ${tstart_x} ${tstart_y}`);
            }
            else {
                // Draw partial ellipse only.
                const dx = radius_x * Math.cos(end_angle);
                const dy = radius_y * Math.sin(end_angle);
                const [end_x, end_y] = transform.apply(dx, dy);
                let diff = end_angle - start_angle;
                // https://github.com/gliffy/canvas2svg/issues/4
                if (diff < 0) {
                    diff += 2 * Math.PI;
                }
                const large_arc_flag = (counterclockwise !== diff > Math.PI) ? 1 : 0; // imitation xor
                const [tend_x, tend_y] = this._transform.apply(end_x, end_y);
                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.
          */
        clip() {
            const clip_path = this.__createElement("clipPath");
            const 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
          */
        drawImage(image, ...args) {
            let dx, dy;
            let dw, dh;
            let sx, sy;
            let sw, sh;
            if (args.length == 2) {
                [dx, dy] = args;
                if (!isFinite(dx + dy))
                    return;
                sx = 0;
                sy = 0;
                const [w, h] = width_height(image);
                dw = sw = w;
                dh = sh = h;
            }
            else if (args.length == 4) {
                [dx, dy, dw, dh] = args;
                if (!isFinite(dx + dy + dw + dh))
                    return;
                sx = 0;
                sy = 0;
                const [w, h] = width_height(image);
                sw = w;
                sh = h;
            }
            else if (args.length === 8) {
                [sx, sy, sw, sh, dx, dy, dw, dh] = args;
                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
            const parent = this.__root;
            const 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.
                const svg_node = image instanceof SVGSVGElement ? image : image.get_svg();
                const svg = svg_node.cloneNode(true);
                let scope;
                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);
                }
                for (const child of [...svg.childNodes]) {
                    if (child instanceof SVGDefsElement) {
                        for (const def of [...child.childNodes]) {
                            if (def instanceof Element) {
                                const id = def.getAttribute("id");
                                this.__ids.add(id);
                                this.__defs.appendChild(def.cloneNode(true));
                            }
                        }
                    }
                    else {
                        scope.appendChild(child.cloneNode(true));
                    }
                }
            }
            else if (image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                const 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 != 0 || sy != 0 || sw !== image.width || sh !== image.height) {
                    // crop the image using a temporary canvas
                    const canvas = this.__document.createElement("canvas");
                    canvas.width = dw;
                    canvas.height = dh;
                    const context = canvas.getContext("2d");
                    context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh);
                    image = canvas;
                }
                this._apply_transform(svgImage, transform);
                const url = image instanceof HTMLCanvasElement ? image.toDataURL() : image.getAttribute("src");
                svgImage.setAttribute("href", url);
                if (this._clip_path != null) {
                    const 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) {
                const 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
                const canvas = this.__document.createElement("canvas");
                canvas.width = dw;
                canvas.height = dh;
                const 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) {
                    const 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
          */
        createPattern(image, _repetition) {
            const pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern");
            const id = this._random_string();
            const [width, height] = width_height(image);
            pattern.setAttribute("id", id);
            pattern.setAttribute("width", `${width}`);
            pattern.setAttribute("height", `${height}`);
            pattern.setAttribute("patternUnits", "userSpaceOnUse");
            if (image instanceof HTMLCanvasElement || image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                const img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image");
                const 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) {
                for (const child of [...image.__root.childNodes]) {
                    if (!(child instanceof SVGDefsElement)) {
                        pattern.appendChild(child.cloneNode(true));
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else if (image instanceof SVGSVGElement) {
                for (const child of [...image.childNodes]) {
                    if (!(child instanceof SVGDefsElement)) {
                        pattern.appendChild(child.cloneNode(true));
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else {
                throw new Error("unsupported");
            }
            return new CanvasPattern(pattern, this);
        }
        getLineDash() {
            const { lineDash } = this;
            if ((0, types_1.isString)(lineDash))
                return lineDash.split(",").map((v) => parseInt(v));
            else if (lineDash == null)
                return [];
            else
                return lineDash;
        }
        setLineDash(segments) {
            if (segments.length > 0)
                this.lineDash = segments.join(",");
            else
                this.lineDash = null;
        }
        getTransform() {
            return this._transform.to_DOMMatrix();
        }
        setTransform(...args) {
            let 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] == null));
            this._transform = affine_1.AffineTransform.from_DOMMatrix(matrix);
        }
        resetTransform() {
            this._transform = new affine_1.AffineTransform();
        }
        isPointInPath(..._args) {
            throw new Error("not implemented");
        }
        isPointInStroke(..._args) {
            throw new Error("not implemented");
        }
        createImageData(..._args) {
            throw new Error("not implemented");
        }
        getImageData(_sx, _sy, _sw, _sh) {
            throw new Error("not implemented");
        }
        putImageData(..._args) {
            throw new Error("not implemented");
        }
        drawFocusIfNeeded(..._args) {
            throw new Error("not implemented");
        }
        scrollPathIntoView(..._args) {
            throw new Error("not implemented");
        }
    }
    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();
    const { PI, log, sin, cos, sqrt, floor } = Math;
    exports.MAX_INT32 = 2147483647;
    class AbstractRandom {
        float() {
            return (this.integer() - 1) / (exports.MAX_INT32 - 1);
        }
        floats(n, a = 0, b = 1) {
            const result = new Array(n);
            for (let i = 0; i < n; i++) {
                result[i] = a + this.float() * (b - a);
            }
            return result;
        }
        choices(n, items) {
            const k = items.length;
            const result = new Array(n);
            for (let i = 0; i < n; i++) {
                result[i] = items[this.integer() % k];
            }
            return result;
        }
        uniform(loc, scale) {
            return loc + (this.float() - 0.5) * scale;
        }
        uniforms(loc, scale, size) {
            return Float64Array.from({ length: size }, () => this.uniform(loc, scale));
        }
        normal(loc, scale) {
            return this.normals(loc, scale, 1)[0];
        }
        normals(loc, scale, size) {
            const [mu, sigma] = [loc, scale];
            const array = new Float64Array(size);
            for (let i = 0; i < size; i += 2) {
                // Box-Muller transform from uniform to normal distribution.
                const u = this.float();
                const v = this.float();
                const common = sqrt(-2.0 * log(u));
                array[i] = mu + sigma * (common * cos(2.0 * PI * v));
                if (i + 1 < size)
                    array[i + 1] = mu + sigma * (common * sin(2.0 * PI * v));
            }
            return array;
        }
    }
    exports.AbstractRandom = AbstractRandom;
    AbstractRandom.__name__ = "AbstractRandom";
    class SystemRandom extends AbstractRandom {
        integer() {
            return floor(Math.random() * exports.MAX_INT32);
        }
    }
    exports.SystemRandom = SystemRandom;
    SystemRandom.__name__ = "SystemRandom";
    // Park-Miller LCG
    class LCGRandom extends AbstractRandom {
        constructor(seed) {
            super();
            this._seed = seed % exports.MAX_INT32;
            if (this._seed <= 0)
                this._seed += exports.MAX_INT32 - 1;
        }
        integer() {
            this._seed = (48271 * this._seed) % exports.MAX_INT32;
            return this._seed;
        }
    }
    exports.LCGRandom = LCGRandom;
    LCGRandom.__name__ = "LCGRandom";
    class Random extends LCGRandom {
    } // for compatibility
    exports.Random = Random;
    Random.__name__ = "Random";
    exports.random = new Random(Date.now());
},
/* styles/ui.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{position:relative;}`;
},
/* models/tools/tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const view_1 = require(54) /* ../../core/view */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    const model_1 = require(50) /* ../../model */;
    class ToolView extends view_1.View {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.active.change, () => {
                if (this.model.active)
                    this.activate();
                else
                    this.deactivate();
            });
        }
        get overlays() {
            return [];
        }
        // activate is triggered by toolbar ui actions
        activate() { }
        // deactivate is triggered by toolbar ui actions
        deactivate() { }
    }
    exports.ToolView = ToolView;
    ToolView.__name__ = "ToolView";
    class Tool extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get event_role() {
            const { event_type } = this;
            return (0, types_1.isString)(event_type) ? event_type : "multi";
        }
        get event_types() {
            const { event_type } = this;
            return event_type == null ? [] : ((0, types_1.isString)(event_type) ? [event_type] : event_type);
        }
        get tooltip() {
            var _b;
            return (_b = this.description) !== null && _b !== void 0 ? _b : this.tool_name;
        }
        get computed_icon() {
            const { icon, tool_icon } = this;
            return icon !== null && icon !== void 0 ? icon : (tool_icon != null ? `.${tool_icon}` : undefined);
        }
        get menu() {
            return null;
        }
        // utility function to get limits along both dimensions, given
        // optional dimensional constraints
        _get_dim_limits([sx0, sy0], [sx1, sy1], frame, dims) {
            const hr = frame.bbox.h_range;
            let 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];
            const vr = frame.bbox.v_range;
            let 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];
        }
        // utility function to return a tool name, modified
        // by the active dimensions. Used by tools that have dimensions
        _get_dim_tooltip(dims) {
            const { description, tool_name } = this;
            if (description != null)
                return description;
            else if (dims == "both")
                return tool_name;
            else if (dims == "auto")
                return `${tool_name} (either x, y or both dimensions)`;
            else
                return `${tool_name} (${dims == "width" ? "x" : "y"}-axis)`;
        }
        static register_alias(name, fn) {
            this.prototype._known_aliases.set(name, fn);
        }
        static from_string(name) {
            const fn = this.prototype._known_aliases.get(name);
            if (fn != null)
                return fn();
            else {
                const names = [...this.prototype._known_aliases.keys()];
                throw new Error(`unexpected tool name '${name}', possible tools are ${names.join(", ")}`);
            }
        }
    }
    exports.Tool = Tool;
    _a = Tool;
    Tool.__name__ = "Tool";
    (() => {
        _a.prototype._known_aliases = new Map();
        _a.define(({ String, Regex, Nullable, Or }) => ({
            icon: [Nullable(Or(enums_1.ToolIcon, Regex(/^--/), Regex(/^\./), Regex(/^data:image/))), null],
            description: [Nullable(String), null],
        }));
        _a.internal(({ Boolean }) => ({
            active: [Boolean, false],
            disabled: [Boolean, false],
        }));
    })();
},
/* models/tools/tool_proxy.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const signaling_1 = require(15) /* ../../core/signaling */;
    const model_1 = require(50) /* ../../model */;
    const tool_1 = require(273) /* ./tool */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    class ToolProxy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        // Operates all the tools given only one button
        get underlying() {
            return this.tools[0];
        }
        tool_button() {
            const button = this.tools[0].tool_button();
            button.tool = this;
            return button;
        }
        get event_type() {
            return this.tools[0].event_type;
        }
        get event_role() {
            return this.tools[0].event_role;
        }
        get event_types() {
            return this.tools[0].event_types;
        }
        get default_order() {
            return this.tools[0].default_order; // only gestures etc.
        }
        get tooltip() {
            return this.tools[0].tooltip;
        }
        get tool_name() {
            return this.tools[0].tool_name;
        }
        get computed_icon() {
            return this.tools[0].computed_icon;
        }
        get toggleable() {
            const tool = this.tools[0];
            return "toggleable" in tool && tool.toggleable;
        }
        initialize() {
            super.initialize();
            this.do = new signaling_1.Signal0(this, "do");
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.do, () => this.doit());
            this.connect(this.properties.active.change, () => this.set_active());
            for (const tool of this.tools) {
                this.connect(tool.properties.active.change, () => {
                    this.active = tool.active;
                });
            }
        }
        doit() {
            for (const tool of this.tools) {
                tool.do.emit();
            }
        }
        set_active() {
            for (const tool of this.tools) {
                tool.active = this.active;
            }
        }
        get menu() {
            const { menu } = this.tools[0];
            if (menu == null)
                return null;
            const items = [];
            for (const [item, i] of (0, iterator_1.enumerate)(menu)) {
                if (item == null)
                    items.push(null);
                else {
                    const handler = () => {
                        var _b, _c, _d;
                        for (const tool of this.tools) {
                            (_d = (_c = (_b = tool.menu) === null || _b === void 0 ? void 0 : _b[i]) === null || _c === void 0 ? void 0 : _c.handler) === null || _d === void 0 ? void 0 : _d.call(_c);
                        }
                    };
                    items.push(Object.assign(Object.assign({}, item), { handler }));
                }
            }
            return items;
        }
    }
    exports.ToolProxy = ToolProxy;
    _a = ToolProxy;
    ToolProxy.__name__ = "ToolProxy";
    (() => {
        _a.define(({ Boolean, Array, Ref }) => ({
            tools: [Array(Ref(tool_1.Tool)), []],
            active: [Boolean, (self) => (0, iterator_1.some)(self.tools, (tool) => tool.active)],
            disabled: [Boolean, false],
        }));
    })();
},
/* models/tools/tool_button.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const tool_1 = require(273) /* ./tool */;
    const tool_proxy_1 = require(274) /* ./tool_proxy */;
    const dom_1 = require(56) /* ../../core/dom */;
    const enums_1 = require(20) /* ../../core/enums */;
    const menus_1 = require(276) /* ../../core/util/menus */;
    const array_1 = require(10) /* ../../core/util/array */;
    const tool_button_css_1 = tslib_1.__importStar(require(279) /* ../../styles/tool_button.css */), tool_button = tool_button_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(278) /* ../../styles/icons.css */);
    class ToolButtonView extends ui_element_1.UIElementView {
        initialize() {
            var _b;
            super.initialize();
            const { location } = this.parent.model;
            const reverse = location == "left" || location == "above";
            const orientation = this.parent.model.horizontal ? "vertical" : "horizontal";
            const items = (_b = this.model.tool.menu) !== null && _b !== void 0 ? _b : [];
            this._menu = new menus_1.ContextMenu(!reverse ? items : (0, array_1.reversed)(items), {
                target: this.root.el,
                orientation,
                prevent_hide: (event) => event.composedPath().includes(this.el),
            });
            const duration = 250; /*ms*/
            let start = null;
            let timer = null;
            this.el.addEventListener("pointerdown", (e) => {
                if (e.buttons == dom_1.MouseButton.Left) {
                    start = e.timeStamp;
                    timer = setTimeout(() => {
                        start = null;
                        timer = null;
                        this._pressed();
                    }, duration);
                }
            });
            this.el.addEventListener("pointerup", (e) => {
                if (timer != null) {
                    clearTimeout(timer);
                    timer = null;
                }
                if (start != null) {
                    const end = e.timeStamp;
                    if (end - start >= duration) {
                        this._pressed();
                    }
                    else {
                        if (this._menu.is_open) {
                            this._menu.hide();
                            return;
                        }
                        if (e.composedPath().includes(this.el)) {
                            this._clicked();
                        }
                    }
                    start = null;
                }
            });
            this.el.addEventListener("keydown", (event) => {
                switch (event.key) {
                    case "Enter": {
                        this._clicked();
                        break;
                    }
                    case " ": {
                        this._pressed();
                        break;
                    }
                }
            });
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.render());
            this.connect(this.model.tool.change, () => this.render());
        }
        remove() {
            this._menu.remove();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), tool_button_css_1.default, icons_css_1.default];
        }
        render() {
            var _b, _c;
            super.render();
            this.class_list.add(tool_button[this.parent.model.location]);
            if (this.model.tool.disabled)
                this.class_list.add(tool_button.disabled);
            const icon_el = (0, dom_1.div)({ class: tool_button.tool_icon });
            this.shadow_el.appendChild(icon_el);
            const icon = (_b = this.model.icon) !== null && _b !== void 0 ? _b : this.model.tool.computed_icon;
            if (icon != null) {
                if (icon.startsWith("data:image")) {
                    const url = `url("${encodeURI(icon)}")`;
                    icon_el.style.backgroundImage = url;
                }
                else if (icon.startsWith("--")) {
                    icon_el.style.backgroundImage = `var(${icon})`;
                }
                else if (icon.startsWith(".")) {
                    const cls = icon.substring(1);
                    icon_el.classList.add(cls);
                }
                else if (enums_1.ToolIcon.valid(icon)) {
                    const cls = `bk-tool-icon-${icon.replace(/_/g, "-")}`;
                    icon_el.classList.add(cls);
                }
            }
            if (this.model.tool.menu != null) {
                const chevron_el = (0, dom_1.div)({ class: tool_button.tool_chevron });
                this.shadow_el.appendChild(chevron_el);
            }
            const tooltip = (_c = this.model.tooltip) !== null && _c !== void 0 ? _c : this.model.tool.tooltip;
            this.el.title = tooltip;
            this.el.tabIndex = 0;
        }
        _pressed() {
            const at = (() => {
                switch (this.parent.model.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 };
                }
            })();
            this._menu.toggle(at);
        }
    }
    exports.ToolButtonView = ToolButtonView;
    ToolButtonView.__name__ = "ToolButtonView";
    class ToolButton extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ToolButton = ToolButton;
    _a = ToolButton;
    ToolButton.__name__ = "ToolButton";
    (() => {
        _a.define(({ String, Regex, Ref, Nullable, Or }) => ({
            tool: [Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))],
            icon: [Nullable(Or(enums_1.ToolIcon, Regex(/^--/), Regex(/^\./), Regex(/^data:image/))), null],
            tooltip: [Nullable(String), null],
        }));
    })();
},
/* core/util/menus.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const dom_1 = require(56) /* ../dom */;
    const array_1 = require(10) /* ./array */;
    const types_1 = require(8) /* ./types */;
    const iterator_1 = require(34) /* ./iterator */;
    const menus_css_1 = tslib_1.__importStar(require(277) /* ../../styles/menus.css */), menus = menus_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(278) /* ../../styles/icons.css */);
    const base_css_1 = tslib_1.__importDefault(require(58) /* ../../styles/base.css */);
    //import {DOMComponentView} from "../dom_view"
    class ContextMenu {
        get is_open() {
            return this._open;
        }
        get can_open() {
            return this.items.length != 0;
        }
        constructor(items, options) {
            var _a, _b, _c;
            this.el = (0, dom_1.div)();
            this._open = false;
            this._item_click = (entry, i) => {
                var _a, _b;
                (_a = this.entry_handler) === null || _a === void 0 ? void 0 : _a.call(this, entry, i);
                (_b = entry.handler) === null || _b === void 0 ? void 0 : _b.call(entry);
                this.hide();
            };
            this._on_mousedown = (event) => {
                var _a, _b;
                if (event.composedPath().includes(this.el))
                    return;
                if ((_b = (_a = this.prevent_hide) === null || _a === void 0 ? void 0 : _a.call(this, event)) !== null && _b !== void 0 ? _b : false)
                    return;
                this.hide();
            };
            this._on_keydown = (event) => {
                if (event.key == "Escape")
                    this.hide();
            };
            this._on_blur = () => {
                this.hide();
            };
            this.items = items;
            this.target = options.target;
            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;
            this.extra_styles = (_c = options.extra_styles) !== null && _c !== void 0 ? _c : [];
            this.entry_handler = options.entry_handler;
            this.shadow_el = this.el.attachShadow({ mode: "open" });
            this.class_list = new dom_1.ClassList(this.el.classList);
        }
        remove() {
            this._unlisten();
            (0, dom_1.remove)(this.el);
        }
        _listen() {
            document.addEventListener("mousedown", this._on_mousedown);
            document.addEventListener("keydown", this._on_keydown);
            window.addEventListener("blur", this._on_blur);
        }
        _unlisten() {
            document.removeEventListener("mousedown", this._on_mousedown);
            document.removeEventListener("keydown", this._on_keydown);
            window.removeEventListener("blur", this._on_blur);
        }
        _position(at) {
            var _a;
            const pos = (() => {
                if ("left_of" in at) {
                    const { left, top } = at.left_of.getBoundingClientRect();
                    return { right: left, top };
                }
                if ("right_of" in at) {
                    const { top, right } = at.right_of.getBoundingClientRect();
                    return { left: right, top };
                }
                if ("below" in at) {
                    const { left, bottom } = at.below.getBoundingClientRect();
                    return { left, top: bottom };
                }
                if ("above" in at) {
                    const { left, top } = at.above.getBoundingClientRect();
                    return { left, bottom: top };
                }
                return at;
            })();
            const parent_el = (_a = this.el.offsetParent) !== null && _a !== void 0 ? _a : document.body;
            const origin = (() => {
                const rect = parent_el.getBoundingClientRect();
                const style = getComputedStyle(parent_el);
                return {
                    left: rect.left - parseFloat(style.marginLeft),
                    right: rect.right + parseFloat(style.marginRight),
                    top: rect.top - parseFloat(style.marginTop),
                    bottom: rect.bottom + parseFloat(style.marginBottom),
                };
            })();
            const { style } = this.el;
            style.left = pos.left != null ? `${pos.left - origin.left}px` : "auto";
            style.top = pos.top != null ? `${pos.top - origin.top}px` : "auto";
            style.right = pos.right != null ? `${origin.right - pos.right}px` : "auto";
            style.bottom = pos.bottom != null ? `${origin.bottom - pos.bottom}px` : "auto";
        }
        stylesheets() {
            return [base_css_1.default, /*...super.stylesheets(), */ menus_css_1.default, icons_css_1.default, ...this.extra_styles];
        }
        empty() {
            (0, dom_1.empty)(this.shadow_el);
            this.class_list.clear();
        }
        render() {
            var _a, _b;
            this.empty();
            for (const style of this.stylesheets()) {
                const stylesheet = (0, types_1.isString)(style) ? new dom_1.InlineStyleSheet(style) : style;
                stylesheet.install(this.shadow_el);
            }
            this.class_list.add(menus[this.orientation]);
            const items = this.reversed ? (0, array_1.reversed)(this.items) : this.items;
            for (const [item, i] of (0, iterator_1.enumerate)(items)) {
                let el;
                if (item == null) {
                    el = (0, dom_1.div)({ class: menus.divider });
                }
                else if (item.if != null && !item.if()) {
                    continue;
                }
                else if (item.custom != null) {
                    el = item.custom;
                }
                else {
                    const icon = item.icon != null ? (0, dom_1.div)({ class: [menus.menu_icon, item.icon] }) : null;
                    const classes = [((_b = (_a = item.active) === null || _a === void 0 ? void 0 : _a.call(item)) !== null && _b !== void 0 ? _b : false) ? menus.active : null, item.class];
                    el = (0, dom_1.div)({ class: classes, title: item.tooltip, tabIndex: 0 }, icon, item.label, item.content);
                    el.addEventListener("click", () => {
                        this._item_click(item, i);
                    });
                    el.addEventListener("keydown", (event) => {
                        if (event.key == "Enter") {
                            this._item_click(item, i);
                        }
                    });
                }
                this.shadow_el.appendChild(el);
            }
        }
        show(at) {
            var _a;
            if (this.items.length == 0)
                return;
            if (!this._open) {
                this.render();
                if (this.shadow_el.children.length == 0)
                    return;
                ((_a = this.target.shadowRoot) !== null && _a !== void 0 ? _a : this.target).appendChild(this.el);
                this._position(at !== null && at !== void 0 ? at : { left: 0, top: 0 });
                this._listen();
                this._open = true;
            }
        }
        hide() {
            if (this._open) {
                this._open = false;
                this._unlisten();
                (0, dom_1.remove)(this.el);
            }
        }
        toggle(at) {
            this._open ? this.hide() : this.show(at);
        }
    }
    exports.ContextMenu = ContextMenu;
    ContextMenu.__name__ = "ContextMenu";
},
/* styles/menus.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.menu_icon = "bk-menu-icon";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.divider = "bk-divider";
    exports.active = "bk-active";
    exports.default = `.bk-menu-icon{width:28px;height:28px;mask-size:60% 60%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:60% 60%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;background-size:60%;background-color:transparent;background-repeat:no-repeat;background-position:center center;}:host{position:absolute;display:inline-flex;flex-wrap:nowrap;user-select:none;-webkit-user-select:none;width:auto;height:auto;z-index:100;cursor:pointer;font-size:var(--font-size);background-color:#fff;border:1px solid #ccc;border-radius:var(--border-radius);box-shadow:2px 4px 8px rgba(0, 0, 0, 0.175);}:host(.bk-horizontal){flex-direction:row;}:host(.bk-vertical){flex-direction:column;}.bk-divider{cursor:default;overflow:hidden;background-color:#e5e5e5;}:host(.bk-horizontal) > .bk-divider{width:1px;margin:5px 0;}:host(.bk-vertical) > .bk-divider{height:1px;margin:0 5px;}:host > :not(.bk-divider){border:1px solid transparent;--active-tool-highlight:#26aae1;}:host > :not(.bk-divider).bk-active{border-color:var(--active-tool-highlight);}:host > :not(.bk-divider):hover{background-color:#f9f9f9;}:host > :not(.bk-divider):focus,:host > :not(.bk-divider):focus-visible{outline:1px dotted var(--active-tool-highlight);outline-offset:-1px;}:host > :not(.bk-divider)::-moz-focus-inner{border:0;}:host(.bk-horizontal) > :not(.bk-divider):first-child{border-top-left-radius:var(--border-radius);border-bottom-left-radius:var(--border-radius);}:host(.bk-horizontal) > :not(.bk-divider):last-child{border-top-right-radius:var(--border-radius);border-bottom-right-radius:var(--border-radius);}:host(.bk-vertical) > :not(.bk-divider):first-child{border-top-left-radius:var(--border-radius);border-top-right-radius:var(--border-radius);}:host(.bk-vertical) > :not(.bk-divider):last-child{border-bottom-left-radius:var(--border-radius);border-bottom-right-radius:var(--border-radius);}`;
},
/* styles/icons.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.tool_icon_copy = "bk-tool-icon-copy";
    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_x_box_select = "bk-tool-icon-x-box-select";
    exports.tool_icon_y_box_select = "bk-tool-icon-y-box-select";
    exports.tool_icon_box_zoom = "bk-tool-icon-box-zoom";
    exports.tool_icon_x_box_zoom = "bk-tool-icon-x-box-zoom";
    exports.tool_icon_y_box_zoom = "bk-tool-icon-y-box-zoom";
    exports.tool_icon_auto_box_zoom = "bk-tool-icon-auto-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_x_pan = "bk-tool-icon-x-pan";
    exports.tool_icon_y_pan = "bk-tool-icon-y-pan";
    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.tool_icon_settings = "bk-tool-icon-settings";
    exports.tool_icon_unknown = "bk-tool-icon-unknown";
    exports.tool_icon_fullscreen = "bk-tool-icon-fullscreen";
    exports.tool_icon_chevron_up = "bk-tool-icon-chevron-up";
    exports.tool_icon_chevron_down = "bk-tool-icon-chevron-down";
    exports.tool_icon_chevron_left = "bk-tool-icon-chevron-left";
    exports.tool_icon_chevron_right = "bk-tool-icon-chevron-right";
    exports.tool_icon_caret_up = "bk-tool-icon-caret-up";
    exports.tool_icon_caret_down = "bk-tool-icon-caret-down";
    exports.tool_icon_caret_left = "bk-tool-icon-caret-left";
    exports.tool_icon_caret_right = "bk-tool-icon-caret-right";
    exports.tool_icon_see_on = "bk-tool-icon-see-on";
    exports.tool_icon_see_off = "bk-tool-icon-see-off";
    exports.default = `:host{--bokeh-icon-color:#a1a6a9;--bokeh-icon-color-disabled:#d4d9db;}.bk-tool-icon-copy{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-copy);-webkit-mask-image:var(--bokeh-icon-copy);}.bk-tool-icon-replace-mode{background-image:var(--bokeh-icon-replace-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxokK3gniQAAAHpJREFUWMNjXLhsJcNAAiaGAQajDhhwB7DgEP+PxmeksvjgDwFcLmYkUh2hkBj8IcBIZXsYh1w2/I8v3sgAOM0bLYhGc8GgrwuICgldfQO88pcvXvg/aOuCUQeM5oLRuoCFCJcTbOMh5XOiW0JDNhdQS3y0IBp1ABwAAF8KGrhC1Eg6AAAAAElFTkSuQmCC"));}.bk-tool-icon-append-mode{background-image:var(--bokeh-icon-append-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxkZWD04WwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAoUlEQVRYw+1WQQ6AIAwrhO8Y/bIXEz9jIMSDr8ETCUEPQzA4pMeFLKNbu4l5WR0CDOMEALBGIzMuQIBEZQjPgP9JLjwTfBjY9sO9lZsFA9IafZng3BlIyVefgd8XQFZBAWe8jfNxwsDhir6rzoCiPiy1K+J8/FRQemv2XfAdFcQ9znU4Viqg9ta1qYJ+D1BnAIBrkgGVOrXNqUA9rbyZm/AEzFh4jEeY/soAAAAASUVORK5CYII="));}.bk-tool-icon-intersect-mode{background-image:var(--bokeh-icon-intersect-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxkrkOpp2wAAAPhJREFUWMPtV1EKwjAMTUavI3oawR/vtn5srJdREfzwMvHHQlcT2mpdMzFfWxiP5r2+JMN+mAiCOB72CABgR1cln4oOGocJnuMTSxWk8jMm7OggYkYXA9gPE3uyd8NXHONJ+eYMdE/NqCJmEZ5ZqlJJ4sUksKN7cYSaPoCZFWR1QI+Xm1fBACU63Cw22x0AAJxudwrffVwvZ+JmQdAHZkw0d4EpAMCw8k87pMdbnwtizQumJYv3nwV6XOA1qbUT/oQLUJgFRbsiNwFVucBIlyR3p0tdMp+XmFjfLKi1LatyAXtCRjPWBdL3Ke3VuACJKFfDr/xFN2fgAR/Go0qaLlmEAAAAAElFTkSuQmCC"));}.bk-tool-icon-subtract-mode{background-image:var(--bokeh-icon-subtract-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxgsF5XNOQAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAABFUlEQVRYw9VWUQqDMAxNpWfxQxD1MoP97G7zQ5mH2RTZYLtM9lWoMbXtxLXNX4OG9r28l4hrd0PQoqxqAACYpxH25C/nkwCHyCBwSPoS09k1T5Fo+4EiExcC4v584xGFmyIXHBLRISAVZyZufUPVa4rcrwmPDgr93ylo+2GliLRUYHK6th/o/6r7nfLpqaCsagEA8Hh9FmcNKeRmgeYDC+SCq0B6FFi8/BcV6BdR9cL3gCv3ijPKOacsn3rBEcjmaVxpfGcg4wHxzgJJnc6241Hn23DERFRAu1bNcWa3Q0uXi62XR6sCaWoSejbtdLYmU3kTEunNgj0bUbQqYG/IcMaqwPS9jftoVCAQ0ZVDJwf0zQdH4AsyW6fpQu4YegAAAABJRU5ErkJggg=="));}.bk-tool-icon-clear-selection{background-image:var(--bokeh-icon-clear-selection, 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-tool-icon-box-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-box-select);-webkit-mask-image:var(--bokeh-icon-box-select);}.bk-tool-icon-x-box-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-x-box-select);-webkit-mask-image:var(--bokeh-icon-x-box-select);}.bk-tool-icon-y-box-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-box-select);-webkit-mask-image:var(--bokeh-icon-y-box-select);}.bk-tool-icon-box-zoom{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-box-zoom);-webkit-mask-image:var(--bokeh-icon-box-zoom);}.bk-tool-icon-x-box-zoom{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-x-box-zoom);-webkit-mask-image:var(--bokeh-icon-x-box-zoom);}.bk-tool-icon-y-box-zoom{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-box-zoom);-webkit-mask-image:var(--bokeh-icon-y-box-zoom);}.bk-tool-icon-auto-box-zoom{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-auto-box-zoom);-webkit-mask-image:var(--bokeh-icon-auto-box-zoom);}.bk-tool-icon-zoom-in{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-zoom-in);-webkit-mask-image:var(--bokeh-icon-zoom-in);}.bk-tool-icon-zoom-out{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-zoom-out);-webkit-mask-image:var(--bokeh-icon-zoom-out);}.bk-tool-icon-help{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-help);-webkit-mask-image:var(--bokeh-icon-help);}.bk-tool-icon-hover{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-hover);-webkit-mask-image:var(--bokeh-icon-hover);}.bk-tool-icon-crosshair{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-crosshair);-webkit-mask-image:var(--bokeh-icon-crosshair);}.bk-tool-icon-lasso-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-lasso-select);-webkit-mask-image:var(--bokeh-icon-lasso-select);}.bk-tool-icon-pan{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-pan);-webkit-mask-image:var(--bokeh-icon-pan);}.bk-tool-icon-x-pan{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-x-pan);-webkit-mask-image:var(--bokeh-icon-x-pan);}.bk-tool-icon-y-pan{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-pan);-webkit-mask-image:var(--bokeh-icon-y-pan);}.bk-tool-icon-range{background-image:var(--bokeh-icon-range, 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-tool-icon-polygon-select{background-image:var(--bokeh-icon-polygon-select, 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-tool-icon-redo{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-redo);-webkit-mask-image:var(--bokeh-icon-redo);}.bk-tool-icon-reset{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-reset);-webkit-mask-image:var(--bokeh-icon-reset);}.bk-tool-icon-save{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-save);-webkit-mask-image:var(--bokeh-icon-save);}.bk-tool-icon-tap-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-tap-select);-webkit-mask-image:var(--bokeh-icon-tap-select);}.bk-tool-icon-undo{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-undo);-webkit-mask-image:var(--bokeh-icon-undo);}.bk-tool-icon-wheel-pan{background-image:var(--bokeh-icon-wheel-pan, 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-tool-icon-wheel-zoom{background-image:var(--bokeh-icon-wheel-zoom, 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-tool-icon-box-edit{background-image:var(--bokeh-icon-box-edit, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4QfHjM1QAAAGRJREFUWMNjXLhsJcNAAiaGAQYsDAwM/+lsJ+OgCwGsLqMB+D8o08CoA0YdMOqAUQewDFQdMBoFIyoN/B/U7YFRB7DQIc7xyo9GwbBMA4xDqhxgISH1klXbDYk0QOseEeOgDgEAIS0JQleje6IAAAAASUVORK5CYII="));}.bk-tool-icon-freehand-draw{background-image:var(--bokeh-icon-freehand-draw, 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-tool-icon-poly-draw{background-image:var(--bokeh-icon-poly-draw, 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-tool-icon-point-draw{background-image:var(--bokeh-icon-point-draw, 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-tool-icon-poly-edit{background-image:var(--bokeh-icon-poly-edit, 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-tool-icon-line-edit{background-image:var(--bokeh-icon-line-edit, url("data:image/png;base64, "));}.bk-tool-icon-settings{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-settings);-webkit-mask-image:var(--bokeh-icon-settings);}.bk-tool-icon-unknown{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-unknown);-webkit-mask-image:var(--bokeh-icon-unknown);}.bk-tool-icon-fullscreen{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-fullscreen);-webkit-mask-image:var(--bokeh-icon-fullscreen);}.bk-tool-icon-chevron-up{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-up);-webkit-mask-image:var(--bokeh-icon-chevron-up);}.bk-tool-icon-chevron-down{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-down);-webkit-mask-image:var(--bokeh-icon-chevron-down);}.bk-tool-icon-chevron-left{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-left);-webkit-mask-image:var(--bokeh-icon-chevron-left);}.bk-tool-icon-chevron-right{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-right);-webkit-mask-image:var(--bokeh-icon-chevron-right);}.bk-tool-icon-caret-up{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-up);-webkit-mask-image:var(--bokeh-icon-caret-up);}.bk-tool-icon-caret-down{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-down);-webkit-mask-image:var(--bokeh-icon-caret-down);}.bk-tool-icon-caret-left{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-left);-webkit-mask-image:var(--bokeh-icon-caret-left);}.bk-tool-icon-caret-right{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-right);-webkit-mask-image:var(--bokeh-icon-caret-right);}.bk-tool-icon-see-on{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-see-on);-webkit-mask-image:var(--bokeh-icon-see-on);}.bk-tool-icon-see-off{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-see-off);-webkit-mask-image:var(--bokeh-icon-see-off);}:host{--bokeh-icon-question-mark:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M8%208a3.5%203%200%200%201%203.5%20-3h1a3.5%203%200%200%201%203.5%203a3%203%200%200%201%20-2%203a3%204%200%200%200%20-2%204%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%2219%22%20x2%3D%2212%22%20y2%3D%2219.01%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-help:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%229%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%2217%22%20x2%3D%2212%22%20y2%3D%2217.01%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2013.5a1.5%201.5%200%200%201%201%20-1.5a2.6%202.6%200%201%200%20-3%20-4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%206l-12%2012%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%206l12%2012%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-settings:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M10.325%204.317c.426%20-1.756%202.924%20-1.756%203.35%200a1.724%201.724%200%200%200%202.573%201.066c1.543%20-.94%203.31%20.826%202.37%202.37a1.724%201.724%200%200%200%201.065%202.572c1.756%20.426%201.756%202.924%200%203.35a1.724%201.724%200%200%200%20-1.066%202.573c.94%201.543%20-.826%203.31%20-2.37%202.37a1.724%201.724%200%200%200%20-2.572%201.065c-.426%201.756%20-2.924%201.756%20-3.35%200a1.724%201.724%200%200%200%20-2.573%20-1.066c-1.543%20.94%20-3.31%20-.826%20-2.37%20-2.37a1.724%201.724%200%200%200%20-1.065%20-2.572c-1.756%20-.426%20-1.756%20-2.924%200%20-3.35a1.724%201.724%200%200%200%201.066%20-2.573c-.94%20-1.543%20.826%20-3.31%202.37%20-2.37c1%20.608%202.296%20.07%202.572%20-1.065z%22%3E%3C%2Fpath%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%223%22%3E%3C%2Fcircle%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-unknown:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M14%203v4a1%201%200%200%200%201%201h4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M17%2021h-10a2%202%200%200%201%20-2%20-2v-14a2%202%200%200%201%202%20-2h7l5%205v11a2%202%200%200%201%20-2%202z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2017v.01%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2014a1.5%201.5%200%201%200%20-1.14%20-2.474%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-fullscreen:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Crect%20x%3D%223%22%20y%3D%2216%22%20width%3D%225%22%20height%3D%225%22%20rx%3D%221%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2012v-6a2%202%200%200%201%202%20-2h12a2%202%200%200%201%202%202v12a2%202%200%200%201%20-2%202h-6%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%208h4v4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M16%208l-5%205%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-save:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%2017v2a2%202%200%200%200%202%202h12a2%202%200%200%200%202%20-2v-2%22%20%2F%3E%0A%20%20%3Cpolyline%20points%3D%227%2011%2012%2016%2017%2011%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%224%22%20x2%3D%2212%22%20y2%3D%2216%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-copy:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2212%22%20height%3D%2212%22%20rx%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M16%208v-2a2%202%200%200%200%20-2%20-2h-8a2%202%200%200%200%20-2%202v8a2%202%200%200%200%202%202h2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-tap-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cline%20x1%3D%223%22%20y1%3D%2212%22%20x2%3D%226%22%20y2%3D%2212%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%223%22%20x2%3D%2212%22%20y2%3D%226%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227.8%22%20y1%3D%227.8%22%20x2%3D%225.6%22%20y2%3D%225.6%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2216.2%22%20y1%3D%227.8%22%20x2%3D%2218.4%22%20y2%3D%225.6%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227.8%22%20y1%3D%2216.2%22%20x2%3D%225.6%22%20y2%3D%2218.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012l9%203l-4%202l-2%204l-3%20-9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-lasso-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4.028%2013.252c-.657%20-.972%20-1.028%20-2.078%20-1.028%20-3.252c0%20-3.866%204.03%20-7%209%20-7s9%203.134%209%207s-4.03%207%20-9%207c-1.913%200%20-3.686%20-.464%20-5.144%20-1.255%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%225%22%20cy%3D%2215%22%20r%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M5%2017c0%201.42%20.316%202.805%201%204%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%209l3%203l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%209l-3%203l3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2018l3%203l3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%206l-3%20-3l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012v9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%203v9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%209l3%203l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%209l-3%203l3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2012h9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%2018l3%203l3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%206l-3%20-3l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012v9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%203v9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M17%2013l-4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l2%202l2%20-2%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%2015v2.5%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M17%2013l-4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l4%204%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l2%202l2%20-2%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%2015v2.5%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-auto-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-zoom-in:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2210%22%20cy%3D%2210%22%20r%3D%227%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227%22%20y1%3D%2210%22%20x2%3D%2213%22%20y2%3D%2210%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2210%22%20y1%3D%227%22%20x2%3D%2210%22%20y2%3D%2213%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2221%22%20y1%3D%2221%22%20x2%3D%2215%22%20y2%3D%2215%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-zoom-out:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2210%22%20cy%3D%2210%22%20r%3D%227%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227%22%20y1%3D%2210%22%20x2%3D%2213%22%20y2%3D%2210%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2221%22%20y1%3D%2221%22%20x2%3D%2215%22%20y2%3D%2215%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-undo:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%2013l-4%20-4l4%20-4m-4%204h11a4%204%200%200%201%200%208h-1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-redo:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%2013l4%20-4l-4%20-4m4%204h-11a4%204%200%200%200%200%208h1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-reset:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M20%2011a8.1%208.1%200%200%200%20-15.5%20-2m-.5%20-4v4h4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2013a8.1%208.1%200%200%200%2015.5%202m.5%204v-4h-4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-hover:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M12%2020l-3%20-3h-2a3%203%200%200%201%20-3%20-3v-6a3%203%200%200%201%203%20-3h10a3%203%200%200%201%203%203v6a3%203%200%200%201%20-3%203h-2l-3%203%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%228%22%20y1%3D%229%22%20x2%3D%2216%22%20y2%3D%229%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%228%22%20y1%3D%2213%22%20x2%3D%2214%22%20y2%3D%2213%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-crosshair:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%229%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M20%2012h-4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2012h4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2020v-4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%204v4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-up:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%226%2015%2012%209%2018%2015%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-down:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%2215%206%209%2012%2015%2018%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%229%206%2015%2012%209%2018%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-up:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-down:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(180%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(270%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(90%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-see-on:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2012c-2.667%204.667%20-6%207%20-10%207s-7.333%20-2.333%20-10%20-7c2.667%20-4.667%206%20-7%2010%20-7s7.333%202.333%2010%207%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-see-off:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cline%20x1%3D%223%22%20y1%3D%223%22%20x2%3D%2221%22%20y2%3D%2221%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10.584%2010.587a2%202%200%200%200%202.828%202.83%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9.363%205.365a9.466%209.466%200%200%201%202.637%20-.365c4%200%207.333%202.333%2010%207c-.778%201.361%20-1.612%202.524%20-2.503%203.488m-2.14%201.861c-1.631%201.1%20-3.415%201.651%20-5.357%201.651c-4%200%20-7.333%20-2.333%20-10%20-7c1.369%20-2.395%202.913%20-4.175%204.632%20-5.341%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");}`;
},
/* styles/tool_button.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.tool_icon = "bk-tool-icon";
    exports.disabled = "bk-disabled";
    exports.tool_chevron = "bk-tool-chevron";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.active = "bk-active";
    exports.default = `:host{--button-width:30px;--button-height:30px;--button-color:lightgray;--button-border:2px;--active-tool-highlight:#26aae1;--active-tool-border:var(--button-border) solid transparent;}:host{position:relative;width:var(--button-width);height:var(--button-height);cursor:pointer;user-select:none;-webkit-user-select:none;}.bk-tool-icon{position:relative;top:calc(var(--button-border)/2);width:calc(var(--button-width) - var(--button-border));height:calc(var(--button-height) - var(--button-border));mask-size:60% 60%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:60% 60%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;background-size:60% 60%;background-origin:border-box;background-position:center center;background-repeat:no-repeat;}:host(.bk-disabled) .bk-tool-icon{background-color:var(--bokeh-icon-color-disabled);cursor:not-allowed;}.bk-tool-chevron{position:absolute;visibility:hidden;width:8px;height:8px;mask-size:100% 100%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:100% 100%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;}:host(:hover) .bk-tool-chevron{visibility:visible;}:host(.bk-above) .bk-tool-chevron{right:0;bottom:0;background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-down);-webkit-mask-image:var(--bokeh-icon-chevron-down);}:host(.bk-below) .bk-tool-chevron{right:0;top:0;background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-up);-webkit-mask-image:var(--bokeh-icon-chevron-up);}:host(.bk-left) .bk-tool-chevron{right:0;bottom:0;background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-right);-webkit-mask-image:var(--bokeh-icon-chevron-right);}:host(.bk-right) .bk-tool-chevron{left:0;bottom:0;background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-left);-webkit-mask-image:var(--bokeh-icon-chevron-left);}:host(:hover){background-color:rgba(192, 192, 192, 0.15);}:host(:focus),:host(:focus-visible){outline:1px dotted var(--active-tool-highlight);outline-offset:-1px;}:host::-moz-focus-inner{border:0;}:host(.bk-above){border-bottom:var(--active-tool-border);}:host(.bk-above.bk-active){border-bottom-color:var(--active-tool-highlight);}:host(.bk-below){border-top:var(--active-tool-border);}:host(.bk-below.bk-active){border-top-color:var(--active-tool-highlight);}:host(.bk-right){border-left:var(--active-tool-border);}:host(.bk-right.bk-active){border-left-color:var(--active-tool-highlight);}:host(.bk-left){border-right:var(--active-tool-border);}:host(.bk-left.bk-active){border-right-color:var(--active-tool-highlight);}`;
},
/* models/tools/gestures/gesture_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tool_1 = require(273) /* ../tool */;
    const on_off_button_1 = require(281) /* ../on_off_button */;
    class GestureToolView extends tool_1.ToolView {
        get plot_view() {
            return this.parent;
        }
    }
    exports.GestureToolView = GestureToolView;
    GestureToolView.__name__ = "GestureToolView";
    class GestureTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
        }
        tool_button() {
            return new on_off_button_1.OnOffButton({ tool: this });
        }
    }
    exports.GestureTool = GestureTool;
    GestureTool.__name__ = "GestureTool";
},
/* models/tools/on_off_button.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tool_button_1 = require(275) /* ./tool_button */;
    const tools = tslib_1.__importStar(require(279) /* ../../styles/tool_button.css */);
    class OnOffButtonView extends tool_button_1.ToolButtonView {
        _toggle_active() {
            this.class_list.toggle(tools.active, this.model.tool.active);
        }
        connect_signals() {
            super.connect_signals();
            const { active } = this.model.tool.properties;
            this.on_change(active, () => {
                this._toggle_active();
            });
        }
        render() {
            super.render();
            this._toggle_active();
        }
        _clicked() {
            const { active } = this.model.tool;
            this.model.tool.active = !active;
        }
    }
    exports.OnOffButtonView = OnOffButtonView;
    OnOffButtonView.__name__ = "OnOffButtonView";
    class OnOffButton extends tool_button_1.ToolButton {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.OnOffButton = OnOffButton;
    _a = OnOffButton;
    OnOffButton.__name__ = "OnOffButton";
    (() => {
        _a.prototype.default_view = OnOffButtonView;
    })();
},
/* models/tools/inspectors/inspect_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tool_1 = require(273) /* ../tool */;
    const on_off_button_1 = require(281) /* ../on_off_button */;
    class InspectToolView extends tool_1.ToolView {
        get plot_view() {
            return this.parent;
        }
    }
    exports.InspectToolView = InspectToolView;
    InspectToolView.__name__ = "InspectToolView";
    class InspectTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
            this.event_type = "move";
        }
        tool_button() {
            return new on_off_button_1.OnOffButton({ tool: this });
        }
    }
    exports.InspectTool = InspectTool;
    _a = InspectTool;
    InspectTool.__name__ = "InspectTool";
    (() => {
        _a.define(({ Boolean }) => ({
            toggleable: [Boolean, true],
        }));
        _a.override({
            active: true,
        });
    })();
},
/* models/tools/actions/action_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tool_1 = require(273) /* ../tool */;
    const click_button_1 = require(284) /* ../click_button */;
    const signaling_1 = require(15) /* ../../../core/signaling */;
    class ActionToolView extends tool_1.ToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.do, (arg) => this.doit(arg));
        }
    }
    exports.ActionToolView = ActionToolView;
    ActionToolView.__name__ = "ActionToolView";
    class ActionTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
            this.do = new signaling_1.Signal(this, "do");
        }
        tool_button() {
            return new click_button_1.ClickButton({ tool: this });
        }
    }
    exports.ActionTool = ActionTool;
    ActionTool.__name__ = "ActionTool";
},
/* models/tools/click_button.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tool_button_1 = require(275) /* ./tool_button */;
    class ClickButtonView extends tool_button_1.ToolButtonView {
        _clicked() {
            this.model.tool.do.emit(undefined);
        }
    }
    exports.ClickButtonView = ClickButtonView;
    ClickButtonView.__name__ = "ClickButtonView";
    class ClickButton extends tool_button_1.ToolButton {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ClickButton = ClickButton;
    _a = ClickButton;
    ClickButton.__name__ = "ClickButton";
    (() => {
        _a.prototype.default_view = ClickButtonView;
    })();
},
/* models/tools/actions/help_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const action_tool_1 = require(283) /* ./action_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class HelpToolView extends action_tool_1.ActionToolView {
        doit() {
            window.open(this.model.redirect);
        }
    }
    exports.HelpToolView = HelpToolView;
    HelpToolView.__name__ = "HelpToolView";
    class HelpTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Help";
            this.tool_icon = icons_css_1.tool_icon_help;
        }
    }
    exports.HelpTool = HelpTool;
    _a = HelpTool;
    HelpTool.__name__ = "HelpTool";
    (() => {
        _a.prototype.default_view = HelpToolView;
        _a.define(({ String }) => ({
            redirect: [String, "https://docs.bokeh.org/en/latest/docs/user_guide/interaction/tools.html"],
        }));
        _a.override({
            description: "Click the question mark to learn more about Bokeh plot tools.",
        });
        _a.register_alias("help", () => new _a());
    })();
},
/* styles/toolbar.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.inner = "bk-inner";
    exports.hidden = "bk-hidden";
    exports.logo = "bk-logo";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.divider = "bk-divider";
    exports.tool_overflow = "bk-tool-overflow";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.default = `:host{--button-width:30px;--button-height:30px;--button-color:lightgray;}:host{display:flex;flex-wrap:nowrap;align-items:center;user-select:none;-webkit-user-select:none;}:host(.bk-inner){background-color:white;opacity:0.8;}:host(.bk-hidden){visibility:hidden;opacity:0;transition:visibility 0.3s linear, opacity 0.3s linear;}.bk-logo{flex-shrink:0;}:host(.bk-above),:host(.bk-below){flex-direction:row;justify-content:flex-end;}:host(.bk-above) .bk-logo,:host(.bk-below) .bk-logo{order:1;margin-left:5px;margin-right:0px;}:host(.bk-left),:host(.bk-right){flex-direction:column;justify-content:flex-start;}:host(.bk-left) .bk-logo,:host(.bk-right) .bk-logo{order:0;margin-bottom:5px;margin-top:0px;}.bk-divider{content:" ";display:inline-block;background-color:var(--button-color);}:host(.bk-above) .bk-divider,:host(.bk-below) .bk-divider{height:10px;width:1px;}:host(.bk-left) .bk-divider,:host(.bk-right) .bk-divider{height:1px;width:10px;}.bk-tool-overflow{color:gray;display:flex;align-items:center;}.bk-tool-overflow:hover{background-color:rgba(192, 192, 192, 0.15);}.bk-tool-overflow:focus,.bk-tool-overflow:focus-visible{outline:1px dotted var(--active-tool-highlight);outline-offset:-1px;}.bk-tool-overflow::-moz-focus-inner{border:0;}:host(.bk-above) .bk-tool-overflow,:host(.bk-below) .bk-tool-overflow,:host(.bk-horizontal) .bk-tool-overflow{width:calc(var(--button-width)/2);height:var(--button-height);flex-direction:row;}:host(.bk-left) .bk-tool-overflow,:host(.bk-right) .bk-tool-overflow,:host(.bk-vertical) .bk-tool-overflow{width:var(--button-width);height:calc(var(--button-height)/2);flex-direction:column;}`;
},
/* styles/logo.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.logo = "bk-logo";
    exports.grey = "bk-grey";
    exports.logo_small = "bk-logo-small";
    exports.default = `.bk-logo{margin:5px;position:relative;display:block;background-repeat:no-repeat;}.bk-logo.bk-grey{filter:grayscale(100%);}.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==);}`;
},
/* models/annotations/whisker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const upper_lower_1 = require(236) /* ./upper_lower */;
    const arrow_head_1 = require(141) /* ./arrow_head */;
    const types_1 = require(24) /* ../../core/types */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    class WhiskerView extends upper_lower_1.UpperLowerView {
        *children() {
            yield* super.children();
            const { lower_head, upper_head } = this;
            if (lower_head != null)
                yield lower_head;
            if (upper_head != null)
                yield upper_head;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { lower_head, upper_head } = this.model;
            if (lower_head != null)
                this.lower_head = await (0, build_views_1.build_view)(lower_head, { parent: this });
            if (upper_head != null)
                this.upper_head = await (0, build_views_1.build_view)(upper_head, { parent: this });
        }
        set_data(source) {
            var _b, _c;
            super.set_data(source);
            const indices = types_1.Indices.all_set(this._lower.length);
            (_b = this.lower_head) === null || _b === void 0 ? void 0 : _b.set_data(source, indices);
            (_c = this.upper_head) === null || _c === void 0 ? void 0 : _c.set_data(source, indices);
        }
        paint(ctx) {
            if (this.visuals.line.doit) {
                for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                    ctx.beginPath();
                    ctx.moveTo(this._lower_sx[i], this._lower_sy[i]);
                    ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
                    this.visuals.line.apply(ctx, i);
                }
            }
            const angle = this.model.dimension == "height" ? 0 : Math.PI / 2;
            if (this.lower_head != null) {
                for (let 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 (let 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();
                }
            }
        }
    }
    exports.WhiskerView = WhiskerView;
    WhiskerView.__name__ = "WhiskerView";
    class Whisker extends upper_lower_1.UpperLower {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Whisker = Whisker;
    _a = Whisker;
    Whisker.__name__ = "Whisker";
    (() => {
        _a.prototype.default_view = WhiskerView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(({ Ref, Nullable }) => ({
            lower_head: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.TeeHead({ size: 10 })],
            upper_head: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.TeeHead({ size: 10 })],
        }));
        _a.override({
            level: "underlay",
        });
    })();
},
/* models/annotations/html/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var label_1 = require(290) /* ./label */;
    __esExport("HTMLLabel", label_1.HTMLLabel);
    var label_set_1 = require(292) /* ./label_set */;
    __esExport("HTMLLabelSet", label_set_1.HTMLLabelSet);
    var title_1 = require(293) /* ./title */;
    __esExport("HTMLTitle", title_1.HTMLTitle);
},
/* models/annotations/html/label.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(291) /* ./text_annotation */;
    const math_1 = require(11) /* ../../../core/util/math */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const graphics_1 = require(153) /* ../../../core/graphics */;
    const side_panel_1 = require(146) /* ../../../core/layout/side_panel */;
    const mixins = tslib_1.__importStar(require(78) /* ../../../core/property_mixins */);
    class HTMLLabelView extends text_annotation_1.TextAnnotationView {
        update_layout() {
            const { panel } = this;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), false);
            else
                this.layout = undefined;
        }
        // XXX: this needs to use CSS computed styles
        _get_size() {
            const { text } = this.model;
            const graphics = new graphics_1.TextBox({ text });
            const { angle, angle_units } = this.model;
            graphics.angle = (0, math_1.compute_angle)(angle, angle_units);
            graphics.visuals = this.visuals.text.values();
            const { width, height } = graphics.size();
            return { width, height };
        }
        _render() {
            const { angle, angle_units } = this.model;
            const rotation = (0, math_1.compute_angle)(angle, angle_units);
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            let sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return this.model.x;
                    case "screen":
                        return panel.bbox.xview.compute(this.model.x);
                    case "data":
                        return xscale.compute(this.model.x);
                }
            })();
            let sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return this.model.y;
                    case "screen":
                        return panel.bbox.yview.compute(this.model.y);
                    case "data":
                        return yscale.compute(this.model.y);
                }
            })();
            sx += this.model.x_offset;
            sy -= this.model.y_offset;
            this._paint(this.layer.ctx, this.model.text, sx, sy, rotation);
        }
    }
    exports.HTMLLabelView = HTMLLabelView;
    HTMLLabelView.__name__ = "HTMLLabelView";
    class HTMLLabel extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTMLLabel = HTMLLabel;
    _a = HTMLLabel;
    HTMLLabel.__name__ = "HTMLLabel";
    (() => {
        _a.prototype.default_view = HTMLLabelView;
        _a.mixins([
            mixins.Text,
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
        ]);
        _a.define(({ Number, String, Angle }) => ({
            x: [Number],
            x_units: [enums_1.CoordinateUnits, "data"],
            y: [Number],
            y_units: [enums_1.CoordinateUnits, "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/html/text_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const annotation_1 = require(73) /* ../annotation */;
    const dom_1 = require(56) /* ../../../core/dom */;
    const side_panel_1 = require(146) /* ../../../core/layout/side_panel */;
    class TextAnnotationView extends annotation_1.AnnotationView {
        update_layout() {
            const { panel } = this;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), true);
            else
                this.layout = undefined;
        }
        initialize() {
            super.initialize();
            this.el = (0, dom_1.div)();
            this.plot_view.canvas_view.add_overlay(this.el);
        }
        remove() {
            (0, dom_1.remove)(this.el);
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.render());
        }
        render() {
            if (!this.model.visible)
                (0, dom_1.undisplay)(this.el);
            super.render();
        }
        _paint(ctx, text, sx, sy, angle) {
            const { el } = this;
            (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.webkitTextStroke = `1px ${ctx.strokeStyle}`;
            el.style.font = ctx.font;
            el.style.lineHeight = "normal"; // needed to prevent ipynb css override
            el.style.whiteSpace = "pre";
            const [x_anchor, x_t] = (() => {
                switch (this.visuals.text.text_align.get_value()) {
                    case "left": return ["left", "0%"];
                    case "center": return ["center", "-50%"];
                    case "right": return ["right", "-100%"];
                }
            })();
            const [y_anchor, y_t] = (() => {
                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"
                }
            })();
            let transform = `translate(${x_t}, ${y_t})`;
            if (angle != 0) {
                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.getLineDash().length < 2 ? "solid" : "dashed";
                el.style.borderWidth = `${ctx.lineWidth}px`;
                el.style.borderColor = ctx.strokeStyle;
            }
            (0, dom_1.display)(el);
        }
    }
    exports.TextAnnotationView = TextAnnotationView;
    TextAnnotationView.__name__ = "TextAnnotationView";
    class TextAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TextAnnotation = TextAnnotation;
    TextAnnotation.__name__ = "TextAnnotation";
},
/* models/annotations/html/label_set.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(100) /* ../data_annotation */;
    const mixins = tslib_1.__importStar(require(78) /* ../../../core/property_mixins */);
    const enums_1 = require(20) /* ../../../core/enums */;
    const dom_1 = require(56) /* ../../../core/dom */;
    const p = tslib_1.__importStar(require(18) /* ../../../core/properties */);
    const types_1 = require(24) /* ../../../core/types */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    class HTMLLabelSetView extends data_annotation_1.DataAnnotationView {
        constructor() {
            super(...arguments);
            this.els = [];
        }
        set_data(source) {
            super.set_data(source);
            this.els.forEach((el) => (0, dom_1.remove)(el));
            this.els = [];
            for (const _ of this.text) {
                const el = (0, dom_1.div)({ style: { display: "none" } });
                this.plot_view.canvas_view.add_overlay(el);
                this.els.push(el);
            }
        }
        remove() {
            this.els.forEach((el) => (0, dom_1.remove)(el));
            this.els = [];
            super.remove();
        }
        _rerender() {
            this.render();
        }
        map_data() {
            const { x_scale, y_scale } = this.coordinates;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            this.sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._x);
                    case "screen":
                        return panel.bbox.xview.v_compute(this._x);
                    case "data":
                        return x_scale.v_compute(this._x);
                }
            })();
            this.sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._y);
                    case "screen":
                        return panel.bbox.yview.v_compute(this._y);
                    case "data":
                        return y_scale.v_compute(this._y);
                }
            })();
        }
        paint() {
            const { ctx } = this.layer;
            for (let i = 0, end = this.text.length; i < end; i++) {
                const x_offset_i = this.x_offset.get(i);
                const y_offset_i = this.y_offset.get(i);
                const sx_i = this.sx[i] + x_offset_i;
                const sy_i = this.sy[i] - y_offset_i;
                const angle_i = this.angle.get(i);
                const text_i = this.text.get(i);
                if (!isFinite(sx_i + sy_i + angle_i) || text_i == null)
                    continue;
                this._paint(ctx, i, text_i, sx_i, sy_i, angle_i);
            }
        }
        _paint(ctx, i, text, sx, sy, angle) {
            (0, assert_1.assert)(i in this.els);
            const 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.webkitTextStroke = `1px ${ctx.strokeStyle}`;
            el.style.font = ctx.font;
            el.style.lineHeight = "normal"; // needed to prevent ipynb css override
            el.style.whiteSpace = "pre";
            const [x_anchor, x_t] = (() => {
                switch (this.visuals.text.text_align.get(i)) {
                    case "left": return ["left", "0%"];
                    case "center": return ["center", "-50%"];
                    case "right": return ["right", "-100%"];
                }
            })();
            const [y_anchor, y_t] = (() => {
                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"
                }
            })();
            let transform = `translate(${x_t}, ${y_t})`;
            if (angle != 0) {
                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.getLineDash().length < 2 ? "solid" : "dashed";
                el.style.borderWidth = `${ctx.lineWidth}px`;
                el.style.borderColor = ctx.strokeStyle;
            }
            (0, dom_1.display)(el);
        }
    }
    exports.HTMLLabelSetView = HTMLLabelSetView;
    HTMLLabelSetView.__name__ = "HTMLLabelSetView";
    class HTMLLabelSet extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTMLLabelSet = HTMLLabelSet;
    _a = HTMLLabelSet;
    HTMLLabelSet.__name__ = "HTMLLabelSet";
    (() => {
        _a.prototype.default_view = HTMLLabelSetView;
        _a.mixins([
            mixins.TextVector,
            ["border_", mixins.LineVector],
            ["background_", mixins.FillVector],
        ]);
        _a.define(() => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y: [p.YCoordinateSpec, { field: "y" }],
            x_units: [enums_1.CoordinateUnits, "data"],
            y_units: [enums_1.CoordinateUnits, "data"],
            text: [p.NullStringSpec, { field: "text" }],
            angle: [p.AngleSpec, 0],
            x_offset: [p.NumberSpec, { value: 0 }],
            y_offset: [p.NumberSpec, { value: 0 }],
        }));
        _a.override({
            background_fill_color: null,
            border_line_color: null,
        });
    })();
},
/* models/annotations/html/title.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(291) /* ./text_annotation */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const graphics_1 = require(153) /* ../../../core/graphics */;
    const mixins = tslib_1.__importStar(require(78) /* ../../../core/property_mixins */);
    class HTMLTitleView extends text_annotation_1.TextAnnotationView {
        _get_location() {
            const hmargin = this.model.offset;
            const vmargin = this.model.standoff / 2;
            let sx, sy;
            const { bbox } = this.layout;
            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];
        }
        _render() {
            const { text } = this.model;
            if (text.length == 0)
                return;
            this.model.text_baseline = this.model.vertical_align;
            this.model.text_align = this.model.align;
            const [sx, sy] = this._get_location();
            const angle = this.panel.get_label_angle_heuristic("parallel");
            this._paint(this.layer.ctx, text, sx, sy, angle);
        }
        // XXX: this needs to use CSS computed styles
        _get_size() {
            const { text } = this.model;
            const graphics = new graphics_1.TextBox({ text });
            graphics.visuals = this.visuals.text.values();
            const { width, height } = graphics.size();
            // 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, height: height == 0 ? 0 : 2 + height + this.model.standoff };
        }
    }
    exports.HTMLTitleView = HTMLTitleView;
    HTMLTitleView.__name__ = "HTMLTitleView";
    class HTMLTitle extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTMLTitle = HTMLTitle;
    _a = HTMLTitle;
    HTMLTitle.__name__ = "HTMLTitle";
    (() => {
        _a.prototype.default_view = HTMLTitleView;
        _a.mixins([
            mixins.Text,
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
        ]);
        _a.define(({ Number, String }) => ({
            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/callbacks/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_1 = require(295) /* ./customjs */;
    __esExport("CustomJS", customjs_1.CustomJS);
    var open_url_1 = require(297) /* ./open_url */;
    __esExport("OpenURL", open_url_1.OpenURL);
    var set_value_1 = require(298) /* ./set_value */;
    __esExport("SetValue", set_value_1.SetValue);
},
/* models/callbacks/customjs.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(296) /* ./callback */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    const string_1 = require(40) /* ../../core/util/string */;
    const logging_1 = require(19) /* ../../core/logging */;
    const types_1 = require(8) /* ../../core/util/types */;
    const standalone_1 = require(53) /* ../../embed/standalone */;
    class CustomJS extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
            this._state = null;
        }
        connect_signals() {
            super.connect_signals();
            const { args, code, module } = this.properties;
            this.on_change([args, code, module], () => this._state = null);
        }
        async _compile_module() {
            const url = URL.createObjectURL(new Blob([this.code], { type: "text/javascript" }));
            try {
                // XXX: eval() to work around transpilation to require()
                // https://github.com/microsoft/TypeScript/issues/43329
                const module = await eval(`import("${url}")`);
                if ((0, types_1.isFunction)(module.default)) {
                    return module.default;
                }
                else {
                    logging_1.logger.warn("custom ES module didn't export a default function");
                    return () => undefined;
                }
            }
            finally {
                URL.revokeObjectURL(url);
            }
        }
        async _compile_function() {
            const [names = [], values = []] = (0, array_1.unzip)((0, object_1.entries)(this.args));
            const code = (0, string_1.use_strict)(this.code);
            const func = new Function(...names, "cb_obj", "cb_data", "cb_context", code);
            return function (...args) {
                return func.call(this, ...values, ...args);
            };
        }
        _is_es_module(code) {
            return code.split("\n").some((line) => line.trimStart().startsWith("export default"));
        }
        async _compile() {
            const module = (() => {
                if (this.module == "auto") {
                    return this._is_es_module(this.code);
                }
                else {
                    return this.module;
                }
            })();
            if (module) {
                return { func: await this._compile_module(), module };
            }
            else {
                return { func: await this._compile_function(), module };
            }
        }
        async state() {
            if (this._state == null) {
                this._state = await this._compile();
            }
            return this._state;
        }
        async execute(obj, data = {}) {
            const { func, module } = await this.state();
            const context = { index: standalone_1.index };
            if (module) {
                return func(this.args, obj, data, context);
            }
            else {
                return func.call(obj, obj, data, context);
            }
        }
    }
    exports.CustomJS = CustomJS;
    _a = CustomJS;
    CustomJS.__name__ = "CustomJS";
    (() => {
        _a.define(({ Unknown, String, Dict, Auto, Or, Boolean }) => ({
            args: [Dict(Unknown), {}],
            code: [String],
            module: [Or(Auto, Boolean), "auto"],
        }));
    })();
},
/* models/callbacks/callback.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class Callback extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Callback = Callback;
    Callback.__name__ = "Callback";
},
/* models/callbacks/open_url.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(296) /* ./callback */;
    const templating_1 = require(172) /* ../../core/util/templating */;
    const types_1 = require(8) /* ../../core/util/types */;
    class OpenURL extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        navigate(url) {
            if (this.same_tab)
                window.location.href = url;
            else
                window.open(url);
        }
        execute(_cb_obj, { source }) {
            const open_url = (i) => {
                const 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);
            };
            const { selected } = source;
            for (const i of selected.indices)
                open_url(i);
            for (const i of selected.line_indices)
                open_url(i);
            // TODO: multiline_indices: {[key: string]: number[]}
        }
    }
    exports.OpenURL = OpenURL;
    _a = OpenURL;
    OpenURL.__name__ = "OpenURL";
    (() => {
        _a.define(({ Boolean, String }) => ({
            url: [String, "http://"],
            same_tab: [Boolean, false],
        }));
    })();
},
/* models/callbacks/set_value.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(296) /* ./callback */;
    const has_props_1 = require(14) /* ../../core/has_props */;
    const logging_1 = require(19) /* ../../core/logging */;
    class SetValue extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        execute() {
            const { obj, attr, value } = this;
            if (attr in obj.properties)
                obj.setv({ [attr]: value });
            else
                logging_1.logger.error(`${obj.type}.${attr} is not a property`);
        }
    }
    exports.SetValue = SetValue;
    _a = SetValue;
    SetValue.__name__ = "SetValue";
    (() => {
        _a.define(({ String, Unknown, Ref }) => ({
            obj: [Ref(has_props_1.HasProps)],
            attr: [String],
            value: [Unknown],
        }));
    })();
},
/* models/canvas/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var canvas_1 = require(300) /* ./canvas */;
    __esExport("Canvas", canvas_1.Canvas);
    var cartesian_frame_1 = require(159) /* ./cartesian_frame */;
    __esExport("CartesianFrame", cartesian_frame_1.CartesianFrame);
},
/* models/canvas/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const settings_1 = require(29) /* ../../core/settings */;
    const logging_1 = require(19) /* ../../core/logging */;
    const dom_1 = require(56) /* ../../core/dom */;
    const enums_1 = require(20) /* ../../core/enums */;
    const ui_events_1 = require(301) /* ../../core/ui_events */;
    const modules_1 = require(157) /* ../../core/util/modules */;
    const canvas_1 = require(269) /* ../../core/util/canvas */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const dom_2 = require(56) /* ../../core/dom */;
    const canvas_css_1 = tslib_1.__importDefault(require(304) /* ../../styles/canvas.css */);
    async function init_webgl() {
        // We use a global invisible canvas and gl context. By having a global context,
        // we avoid the limitation of max 16 contexts that most browsers have.
        const canvas = document.createElement("canvas");
        const gl = canvas.getContext("webgl", { alpha: true, antialias: false, depth: false, premultipliedAlpha: true });
        // If WebGL is available, we store a reference to the ReGL wrapper on
        // the ctx object, because that's what gets passed everywhere.
        if (gl != null) {
            const webgl = await (0, modules_1.load_module)(Promise.resolve().then(() => tslib_1.__importStar(require(517) /* ../glyphs/webgl */)));
            if (webgl != null) {
                const regl_wrapper = webgl.get_regl(gl);
                if (regl_wrapper.has_webgl) {
                    return { canvas, 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");
            }
        }
        else {
            logging_1.logger.trace("WebGL is not supported");
        }
        return null;
    }
    const global_webgl = (() => {
        let _global_webgl;
        return async () => {
            if (_global_webgl !== undefined)
                return _global_webgl;
            else
                return _global_webgl = await init_webgl();
        };
    })();
    class CanvasView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this.webgl = null;
            this._size = new dom_2.InlineStyleSheet();
            this.plot_views = [];
        }
        initialize() {
            super.initialize();
            this.underlays_el = (0, dom_1.div)({ class: "bk-layer" });
            this.primary = this.create_layer();
            this.overlays = this.create_layer();
            this.overlays_el = (0, dom_1.div)({ class: "bk-layer" });
            this.events_el = (0, dom_1.div)({ class: ["bk-layer", "bk-events"] });
            this.ui_event_bus = new ui_events_1.UIEventBus(this);
        }
        get layers() {
            return [
                this.underlays_el,
                this.primary,
                this.overlays,
                this.overlays_el,
                this.events_el,
            ];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            if (this.model.output_backend == "webgl") {
                this.webgl = await global_webgl();
                if (settings_1.settings.force_webgl && this.webgl == null)
                    throw new Error("webgl is not available");
            }
        }
        remove() {
            this.ui_event_bus.destroy();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), canvas_css_1.default, this._size];
        }
        render() {
            super.render();
            const elements = [
                this.underlays_el,
                this.primary.el,
                this.overlays.el,
                this.overlays_el,
                this.events_el,
            ];
            (0, dom_1.append)(this.shadow_el, ...elements);
        }
        add_underlay(el) {
            this.underlays_el.appendChild(el);
        }
        add_overlay(el) {
            this.overlays_el.appendChild(el);
        }
        add_event(el) {
            this.events_el.appendChild(el);
        }
        get pixel_ratio() {
            return this.primary.pixel_ratio; // XXX: primary
        }
        _update_bbox() {
            const changed = super._update_bbox();
            if (changed) {
                const { width, height } = this.bbox;
                this._size.replace(`
      .bk-layer {
        width: ${width}px;
        height: ${height}px;
      }
      `);
                this.primary.resize(width, height);
                this.overlays.resize(width, height);
            }
            return changed;
        }
        after_resize() {
            if (this.plot_views.length != 0) {
                // Canvas is being managed by a plot, thus it should not attempt
                // self-resize, as it would result in inconsistent state and
                // possibly invalid layout and/or lack of repaint of a plot.
                return;
            }
            else {
                super.after_resize();
            }
        }
        _after_resize() {
            super._after_resize();
            const { width, height } = this.bbox;
            this.primary.resize(width, height);
            this.overlays.resize(width, height);
        }
        resize() {
            this._update_bbox();
            this._after_resize();
        }
        prepare_webgl(frame_box) {
            // Prepare WebGL for a drawing pass
            const { webgl } = this;
            if (webgl != null) {
                // Sync canvas size
                const { width, height } = this.bbox;
                webgl.canvas.width = this.pixel_ratio * width;
                webgl.canvas.height = this.pixel_ratio * height;
                const [sx, sy, w, h] = frame_box;
                const { xview, yview } = this.bbox;
                const vx = xview.compute(sx);
                const vy = yview.compute(sy + h);
                const ratio = this.pixel_ratio;
                webgl.regl_wrapper.set_scissor(ratio * vx, ratio * vy, ratio * w, ratio * h);
                this._clear_webgl();
            }
        }
        blit_webgl(ctx) {
            // This should be called when the ctx has no state except the HIDPI transform
            const { webgl } = this;
            if (webgl != null && webgl.canvas.width * webgl.canvas.height > 0) {
                // 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) {
                    const ratio = this.pixel_ratio;
                    ctx.scale(ratio, ratio);
                    ctx.translate(0.5, 0.5);
                }
                this._clear_webgl();
            }
        }
        _clear_webgl() {
            const { webgl } = this;
            if (webgl != null) {
                // Prepare GL for drawing
                const { regl_wrapper, canvas } = webgl;
                regl_wrapper.clear(canvas.width, canvas.height);
            }
        }
        compose() {
            const composite = this.create_layer();
            const { width, height } = this.bbox;
            composite.resize(width, height);
            composite.ctx.drawImage(this.primary.canvas, 0, 0);
            composite.ctx.drawImage(this.overlays.canvas, 0, 0);
            return composite;
        }
        create_layer() {
            const { output_backend, hidpi } = this.model;
            return new canvas_1.CanvasLayer(output_backend, hidpi);
        }
        to_blob() {
            return this.compose().to_blob();
        }
    }
    exports.CanvasView = CanvasView;
    CanvasView.__name__ = "CanvasView";
    class Canvas extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Canvas = Canvas;
    _a = Canvas;
    Canvas.__name__ = "Canvas";
    (() => {
        _a.prototype.default_view = CanvasView;
        _a.define(({ Boolean }) => ({
            hidpi: [Boolean, true],
            output_backend: [enums_1.OutputBackend, "canvas"],
        }));
    })();
},
/* core/ui_events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const hammerjs_1 = tslib_1.__importDefault(require(302) /* hammerjs */);
    const signaling_1 = require(15) /* ./signaling */;
    const logging_1 = require(19) /* ./logging */;
    const dom_1 = require(56) /* ./dom */;
    const events = tslib_1.__importStar(require(52) /* ./bokeh_events */);
    const wheel_1 = require(303) /* ./util/wheel */;
    const array_1 = require(10) /* ./util/array */;
    const types_1 = require(8) /* ./util/types */;
    const platform_1 = require(27) /* ./util/platform */;
    const tool_proxy_1 = require(274) /* ../models/tools/tool_proxy */;
    function is_Moveable(obj) {
        return (0, types_1.isObject)(obj) && "_move_start" in obj && "_move" in obj && "_move_end" in obj;
    }
    exports.is_Moveable = is_Moveable;
    function is_Pannable(obj) {
        return (0, types_1.isObject)(obj) && "_pan_start" in obj && "_pan" in obj && "_pan_end" in obj;
    }
    exports.is_Pannable = is_Pannable;
    function is_Pinchable(obj) {
        return (0, types_1.isObject)(obj) && "_pinch_start" in obj && "_pinch" in obj && "_pinch_end" in obj;
    }
    exports.is_Pinchable = is_Pinchable;
    function is_Rotatable(obj) {
        return (0, types_1.isObject)(obj) && "_rotate_start" in obj && "_rotate" in obj && "_rotate_end" in obj;
    }
    exports.is_Rotatable = is_Rotatable;
    function is_Scrollable(obj) {
        return (0, types_1.isObject)(obj) && "_scroll" in obj;
    }
    exports.is_Scrollable = is_Scrollable;
    function is_Keyable(obj) {
        return (0, types_1.isObject)(obj) && "_keydown" in obj && "_keyup" in obj;
    }
    exports.is_Keyable = is_Keyable;
    function is_Tapable(obj) {
        return (0, types_1.isObject)(obj) && "_tap" in obj;
    }
    exports.is_Tapable = is_Tapable;
    function is_touch(event) {
        return typeof TouchEvent !== "undefined" && event instanceof TouchEvent;
    }
    class UIEventBus {
        get hit_area() {
            return this.canvas_view.events_el;
        }
        constructor(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._prev_move = null;
            this._curr_pan = null;
            this._curr_pinch = null;
            this._curr_rotate = null;
            this._current_pan_view = null;
            this._current_pinch_view = null;
            this._current_rotate_view = null;
            this._current_move_view = null;
            this.canvas_view = canvas_view;
            this.hammer = new hammerjs_1.default(this.hit_area, {
                cssProps: {},
                touchAction: "auto",
                inputClass: !platform_1.is_mobile ? hammerjs_1.default.PointerEventInput : hammerjs_1.default.TouchMouseInput, // https://github.com/bokeh/bokeh/issues/9187
            });
            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", (e) => this._mouse_move(e));
            this.hit_area.addEventListener("mouseenter", (e) => this._mouse_enter(e));
            this.hit_area.addEventListener("mouseleave", (e) => this._mouse_exit(e));
            this.hit_area.addEventListener("contextmenu", (e) => this._context_menu(e));
            this.hit_area.addEventListener("wheel", (e) => 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);
        }
        destroy() {
            this.hammer.destroy();
            document.removeEventListener("keydown", this);
            document.removeEventListener("keyup", this);
        }
        handleEvent(e) {
            if (e.type == "keydown")
                this._key_down(e);
            else if (e.type == "keyup")
                this._key_up(e);
        }
        _configure_hammerjs() {
            // 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", (e) => this._doubletap(e));
            this.hammer.on("tap", (e) => this._tap(e));
            this.hammer.on("press", (e) => this._press(e));
            this.hammer.on("pressup", (e) => this._pressup(e));
            this.hammer.get("pan").set({ direction: hammerjs_1.default.DIRECTION_ALL });
            this.hammer.on("panstart", (e) => this._pan_start(e));
            this.hammer.on("pan", (e) => this._pan(e));
            this.hammer.on("panend", (e) => this._pan_end(e));
            this.hammer.get("pinch").set({ enable: true });
            this.hammer.on("pinchstart", (e) => this._pinch_start(e));
            this.hammer.on("pinch", (e) => this._pinch(e));
            this.hammer.on("pinchend", (e) => this._pinch_end(e));
            this.hammer.get("rotate").set({ enable: true });
            this.hammer.on("rotatestart", (e) => this._rotate_start(e));
            this.hammer.on("rotate", (e) => this._rotate(e));
            this.hammer.on("rotateend", (e) => this._rotate_end(e));
        }
        register_tool(tool_view) {
            let first = true;
            for (const et of tool_view.model.event_types) {
                this._register_tool(tool_view, et, first);
                first = false;
            }
        }
        _register_tool(tool_view, et, shared = true) {
            const v = tool_view;
            const { id } = v.model;
            const conditionally = (fn) => (arg) => {
                if (arg.id == id)
                    fn(arg.e);
            };
            const unconditionally = (fn) => (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)));
                    // XXX: ultimately this shouldn't fall-throught, but breaking here would fail elsewhere
                }
                case "doubletap": {
                    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)));
                    break;
                }
                case "pressup": {
                    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;
                }
            }
            // 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)));
            }
        }
        hit_test_renderers(plot_view, sx, sy) {
            var _a, _b;
            const views = plot_view.get_renderer_views();
            for (const view of (0, array_1.reversed)(views)) {
                if ((_b = (_a = view.interactive_hit) === null || _a === void 0 ? void 0 : _a.call(view, sx, sy)) !== null && _b !== void 0 ? _b : false)
                    return view;
            }
            return null;
        }
        set_cursor(cursor) {
            this.hit_area.style.cursor = cursor !== null && cursor !== void 0 ? cursor : "default";
        }
        hit_test_frame(plot_view, sx, sy) {
            return plot_view.frame.bbox.contains(sx, sy);
        }
        hit_test_plot(sx, sy) {
            // TODO: z-index
            for (const plot_view of this.canvas_view.plot_views) {
                if (plot_view.bbox.relative() /*XXX*/.contains(sx, sy))
                    return plot_view;
            }
            return null;
        }
        _trigger(signal, e, srcEvent) {
            var _a;
            if (!this.hit_area.isConnected)
                return;
            const { sx, sy } = e;
            const plot_view = this.hit_test_plot(sx, sy);
            const curr_view = plot_view;
            const relativize_event = (_plot_view) => {
                const [rel_sx, rel_sy] = [sx, sy]; // plot_view.layout.bbox.relativize(sx, sy)
                return Object.assign(Object.assign({}, e), { sx: rel_sx, sy: rel_sy });
            };
            if (e.type == "panstart" || e.type == "pan" || e.type == "panend") {
                let pan_view;
                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) {
                    const event = relativize_event(pan_view);
                    this.__trigger(pan_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "pinchstart" || e.type == "pinch" || e.type == "pinchend") {
                let pinch_view;
                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) {
                    const event = relativize_event(pinch_view);
                    this.__trigger(pinch_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "rotatestart" || e.type == "rotate" || e.type == "rotateend") {
                let rotate_view;
                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) {
                    const event = relativize_event(rotate_view);
                    this.__trigger(rotate_view, signal, event, srcEvent);
                }
            }
            else if (e.type == "mouseenter" || e.type == "mousemove" || e.type == "mouseleave") {
                const 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)) {
                    const { sx, sy } = relativize_event(prev_view);
                    this.__trigger(prev_view, this.move_exit, { type: "mouseleave", sx, sy, modifiers: { shift: false, ctrl: false, alt: false } }, srcEvent);
                }
                if (curr_view != null && (e.type == "mouseenter" || prev_view != curr_view)) {
                    const { sx, sy } = relativize_event(curr_view);
                    this.__trigger(curr_view, this.move_enter, { type: "mouseenter", sx, sy, modifiers: { shift: false, ctrl: false, alt: false } }, srcEvent);
                }
                if (curr_view != null && e.type == "mousemove") {
                    const event = relativize_event(curr_view);
                    this.__trigger(curr_view, signal, event, srcEvent);
                }
                this._prev_move = { sx, sy, plot_view: curr_view };
            }
            else {
                if (curr_view != null) {
                    const event = relativize_event(curr_view);
                    this.__trigger(curr_view, signal, event, srcEvent);
                }
            }
        }
        __trigger(plot_view, signal, e, srcEvent) {
            var _a, _b, _c, _d, _f;
            const gestures = plot_view.model.toolbar.gestures;
            const event_type = signal.name;
            const base_type = event_type.split(":")[0];
            const view = this.hit_test_renderers(plot_view, e.sx, e.sy);
            if (base_type == "pan") {
                if (this._current_pan_view == null) {
                    if (view != null) {
                        if (event_type == "pan:start" && is_Pannable(view)) {
                            if (view._pan_start(e)) {
                                this._current_pan_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "pan")
                        this._current_pan_view._pan(e);
                    else if (event_type == "pan:end") {
                        this._current_pan_view._pan_end(e);
                        this._current_pan_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "pinch") {
                if (this._current_pinch_view == null) {
                    if (view != null) {
                        if (event_type == "pinch:start" && is_Pinchable(view)) {
                            if (view._pinch_start(e)) {
                                this._current_pinch_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "pinch")
                        this._current_pinch_view._pinch(e);
                    else if (event_type == "pinch:end") {
                        this._current_pinch_view._pinch_end(e);
                        this._current_pinch_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "rotate") {
                if (this._current_rotate_view == null) {
                    if (view != null) {
                        if (event_type == "rotate:start" && is_Rotatable(view)) {
                            if (view._rotate_start(e)) {
                                this._current_rotate_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "rotate")
                        this._current_rotate_view._rotate(e);
                    else if (event_type == "rotate:end") {
                        this._current_rotate_view._rotate_end(e);
                        this._current_rotate_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "move") {
                if (this._current_move_view == view) {
                    (_a = this._current_move_view) === null || _a === void 0 ? void 0 : _a._move(e);
                }
                else {
                    (_b = this._current_move_view) === null || _b === void 0 ? void 0 : _b._move_end(e);
                    this._current_move_view = null;
                    if (view != null && is_Moveable(view)) {
                        if (view._move_start(e)) {
                            this._current_move_view = view;
                        }
                    }
                }
            }
            function get_tool_view(tool_like) {
                var _a;
                if (tool_like != null) {
                    const tool = tool_like instanceof tool_proxy_1.ToolProxy ? tool_like.tools[0] : tool_like;
                    return (_a = plot_view.tool_views.get(tool)) !== null && _a !== void 0 ? _a : null;
                }
                else {
                    return null;
                }
            }
            switch (base_type) {
                case "move": {
                    const active_gesture = gestures.move.active;
                    if (active_gesture != null) {
                        this.trigger(signal, e, active_gesture.id);
                    }
                    const active_inspectors = plot_view.model.toolbar.inspectors.filter(t => t.active);
                    const cursor = (() => {
                        var _a, _b, _c, _d, _f;
                        const current_view = (_f = (_d = (_c = (_b = (_a = this._current_pan_view) !== null && _a !== void 0 ? _a : this._current_pinch_view) !== null && _b !== void 0 ? _b : this._current_rotate_view) !== null && _c !== void 0 ? _c : this._current_move_view) !== null && _d !== void 0 ? _d : view) !== null && _f !== void 0 ? _f : get_tool_view(active_gesture);
                        if (current_view != null) {
                            const cursor = current_view.cursor(e.sx, e.sy);
                            if (cursor != null) {
                                return cursor;
                            }
                        }
                        if (this.hit_test_frame(plot_view, e.sx, e.sy) && !(0, array_1.is_empty)(active_inspectors)) {
                            // the event happened on the plot frame but off a renderer
                            return "crosshair";
                        }
                        return null;
                    })();
                    this.set_cursor(cursor);
                    if (view != null && !view.model.propagate_hover && !(0, array_1.is_empty)(active_inspectors)) {
                        // override event_type to cause inspectors to clear overlays
                        signal = this.move_exit; // XXX
                    }
                    active_inspectors.map((inspector) => this.trigger(signal, e, inspector.id));
                    break;
                }
                case "tap": {
                    // XXX: hammerjs, why non-standard path?
                    const path = (_c = srcEvent.path) !== null && _c !== void 0 ? _c : srcEvent.composedPath();
                    if (path.length != 0 && path[0] != this.hit_area)
                        return; // don't trigger bokeh events
                    (_d = view === null || view === void 0 ? void 0 : view.on_hit) === null || _d === void 0 ? void 0 : _d.call(view, e.sx, e.sy);
                    if (this.hit_test_frame(plot_view, e.sx, e.sy)) {
                        const active_gesture = gestures.tap.active;
                        if (active_gesture != null)
                            this.trigger(signal, e, active_gesture.id);
                    }
                    break;
                }
                case "doubletap": {
                    if (this.hit_test_frame(plot_view, e.sx, e.sy)) {
                        const active_gesture = (_f = gestures.doubletap.active) !== null && _f !== void 0 ? _f : 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.
                    const base = platform_1.is_mobile ? "pinch" : "scroll";
                    const active_gesture = gestures[base].active;
                    if (active_gesture != null) {
                        srcEvent.preventDefault();
                        srcEvent.stopPropagation();
                        this.trigger(signal, e, active_gesture.id);
                    }
                    break;
                }
                case "pan": {
                    const active_gesture = gestures.pan.active;
                    if (active_gesture != null) {
                        srcEvent.preventDefault();
                        this.trigger(signal, e, active_gesture.id);
                    }
                    /* TODO this requires knowledge of the current interactive
                            tool (similar to _current_pan_view, etc.)
                    const active_pan_view = get_tool_view(active_gesture)
                    if (active_pan_view != null) {
                      const cursor = active_pan_view.cursor(e.sx, e.sy)
                      this.set_cursor(cursor)
                    }
                    */
                    break;
                }
                default: {
                    const active_gesture = gestures[base_type].active;
                    if (active_gesture != null)
                        this.trigger(signal, e, active_gesture.id);
                }
            }
            this._trigger_bokeh_event(plot_view, e);
        }
        trigger(signal, e, id = null) {
            signal.emit({ id, e });
        }
        /*protected*/ _trigger_bokeh_event(plot_view, e) {
            const ev = (() => {
                const { sx, sy, modifiers } = e;
                const x = plot_view.frame.x_scale.invert(sx);
                const y = plot_view.frame.y_scale.invert(sy);
                switch (e.type) {
                    case "wheel":
                        return new events.MouseWheel(sx, sy, x, y, e.delta, modifiers);
                    case "mousemove":
                        return new events.MouseMove(sx, sy, x, y, modifiers);
                    case "mouseenter":
                        return new events.MouseEnter(sx, sy, x, y, modifiers);
                    case "mouseleave":
                        return new events.MouseLeave(sx, sy, x, y, modifiers);
                    case "tap":
                        return new events.Tap(sx, sy, x, y, modifiers);
                    case "doubletap":
                        return new events.DoubleTap(sx, sy, x, y, modifiers);
                    case "press":
                        return new events.Press(sx, sy, x, y, modifiers);
                    case "pressup":
                        return new events.PressUp(sx, sy, x, y, modifiers);
                    case "pan":
                        return new events.Pan(sx, sy, x, y, e.dx, e.dy, modifiers);
                    case "panstart":
                        return new events.PanStart(sx, sy, x, y, modifiers);
                    case "panend":
                        return new events.PanEnd(sx, sy, x, y, modifiers);
                    case "pinch":
                        return new events.Pinch(sx, sy, x, y, e.scale, modifiers);
                    case "pinchstart":
                        return new events.PinchStart(sx, sy, x, y, modifiers);
                    case "pinchend":
                        return new events.PinchEnd(sx, sy, x, y, modifiers);
                    case "rotate":
                        return new events.Rotate(sx, sy, x, y, e.rotation, modifiers);
                    case "rotatestart":
                        return new events.RotateStart(sx, sy, x, y, modifiers);
                    case "rotateend":
                        return new events.RotateEnd(sx, sy, x, y, modifiers);
                    default:
                        return undefined;
                }
            })();
            if (ev != null) {
                plot_view.model.trigger_event(ev);
            }
        }
        /*private*/ _get_sxy(event) {
            const { pageX, pageY } = is_touch(event) ? (event.touches.length != 0 ? event.touches : event.changedTouches)[0] : event;
            const { left, top } = (0, dom_1.offset_bbox)(this.hit_area);
            return {
                sx: pageX - left,
                sy: pageY - top,
            };
        }
        _get_modifiers(event) {
            return {
                shift: event.shiftKey,
                ctrl: event.ctrlKey,
                alt: event.altKey,
            };
        }
        /*private*/ _pan_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e.srcEvent)), { dx: e.deltaX, dy: e.deltaY, modifiers: this._get_modifiers(e.srcEvent) });
        }
        /*private*/ _pinch_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e.srcEvent)), { scale: e.scale, modifiers: this._get_modifiers(e.srcEvent) });
        }
        /*private*/ _rotate_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e.srcEvent)), { rotation: e.rotation, modifiers: this._get_modifiers(e.srcEvent) });
        }
        /*private*/ _tap_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e.srcEvent)), { modifiers: this._get_modifiers(e.srcEvent) });
        }
        /*private*/ _move_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e)), { modifiers: this._get_modifiers(e) });
        }
        /*private*/ _scroll_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e)), { delta: (0, wheel_1.getDeltaY)(e), modifiers: this._get_modifiers(e) });
        }
        /*private*/ _key_event(e) {
            return {
                type: e.type,
                key: e.key,
                modifiers: this._get_modifiers(e),
            };
        }
        /*private*/ _pan_start(e) {
            const 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*/ _pan(e) {
            this._trigger(this.pan, this._pan_event(e), e.srcEvent);
        }
        /*private*/ _pan_end(e) {
            this._trigger(this.pan_end, this._pan_event(e), e.srcEvent);
        }
        /*private*/ _pinch_start(e) {
            this._trigger(this.pinch_start, this._pinch_event(e), e.srcEvent);
        }
        /*private*/ _pinch(e) {
            this._trigger(this.pinch, this._pinch_event(e), e.srcEvent);
        }
        /*private*/ _pinch_end(e) {
            this._trigger(this.pinch_end, this._pinch_event(e), e.srcEvent);
        }
        /*private*/ _rotate_start(e) {
            this._trigger(this.rotate_start, this._rotate_event(e), e.srcEvent);
        }
        /*private*/ _rotate(e) {
            this._trigger(this.rotate, this._rotate_event(e), e.srcEvent);
        }
        /*private*/ _rotate_end(e) {
            this._trigger(this.rotate_end, this._rotate_event(e), e.srcEvent);
        }
        /*private*/ _tap(e) {
            this._trigger(this.tap, this._tap_event(e), e.srcEvent);
        }
        /*private*/ _doubletap(e) {
            this._trigger(this.doubletap, this._tap_event(e), e.srcEvent);
        }
        /*private*/ _press(e) {
            this._trigger(this.press, this._tap_event(e), e.srcEvent);
        }
        /*private*/ _pressup(e) {
            this._trigger(this.pressup, this._tap_event(e), e.srcEvent);
        }
        /*private*/ _mouse_enter(e) {
            this._trigger(this.move_enter, this._move_event(e), e);
        }
        /*private*/ _mouse_move(e) {
            this._trigger(this.move, this._move_event(e), e);
        }
        /*private*/ _mouse_exit(e) {
            this._trigger(this.move_exit, this._move_event(e), e);
        }
        /*private*/ _mouse_wheel(e) {
            this._trigger(this.scroll, this._scroll_event(e), e);
        }
        /*private*/ _context_menu(_e) {
            // TODO
        }
        /*private*/ _key_down(e) {
            // NOTE: keyup event triggered unconditionally
            this.trigger(this.keydown, this._key_event(e));
        }
        /*private*/ _key_up(e) {
            // NOTE: keyup event triggered unconditionally
            this.trigger(this.keyup, this._key_event(e));
        }
    }
    exports.UIEventBus = UIEventBus;
    UIEventBus.__name__ = "UIEventBus";
},
/* 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/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) {
        const value = getComputedStyle(element).fontSize;
        const size = parseInt(value, 10);
        return isNaN(size) ? null : size;
    }
    function lineHeight(element) {
        var _a, _b, _c;
        const 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) {
        let 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;
},
/* styles/canvas.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.layer = "bk-layer";
    exports.events = "bk-events";
    exports.default = `.bk-layer{position:absolute;top:0;left:0;width:100%;height:100%;}.bk-layer.bk-events{user-select:none;-webkit-user-select:none;touch-action:auto;-webkit-user-drag:none;-webkit-tap-highlight-color:rgba(0, 0, 0, 0);}`;
},
/* models/coordinates/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var coordinate_mapping_1 = require(84) /* ./coordinate_mapping */;
    __esExport("CoordinateMapping", coordinate_mapping_1.CoordinateMapping);
    var node_1 = require(241) /* ./node */;
    __esExport("Node", node_1.Node);
},
/* models/expressions/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var expression_1 = require(307) /* ./expression */;
    __esExport("Expression", expression_1.Expression);
    var customjs_expr_1 = require(308) /* ./customjs_expr */;
    __esExport("CustomJSExpr", customjs_expr_1.CustomJSExpr);
    var stack_1 = require(309) /* ./stack */;
    __esExport("Stack", stack_1.Stack);
    var cumsum_1 = require(310) /* ./cumsum */;
    __esExport("CumSum", cumsum_1.CumSum);
    var expression_2 = require(307) /* ./expression */;
    __esExport("ScalarExpression", expression_2.ScalarExpression);
    var minimum_1 = require(311) /* ./minimum */;
    __esExport("Minimum", minimum_1.Minimum);
    var maximum_1 = require(312) /* ./maximum */;
    __esExport("Maximum", maximum_1.Maximum);
    var coordinate_transform_1 = require(313) /* ./coordinate_transform */;
    __esExport("XComponent", coordinate_transform_1.XComponent);
    __esExport("YComponent", coordinate_transform_1.YComponent);
    var polar_1 = require(314) /* ./polar */;
    __esExport("PolarTransform", polar_1.PolarTransform);
},
/* models/expressions/expression.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class Expression extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._result = new Map();
        }
        v_compute(source) {
            let result = this._result.get(source);
            if (result === undefined || source.changed_for(this)) {
                result = this._v_compute(source);
                this._result.set(source, result);
            }
            return result;
        }
    }
    exports.Expression = Expression;
    Expression.__name__ = "Expression";
    class ScalarExpression extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._result = new Map();
        }
        compute(source) {
            let result = this._result.get(source);
            if (result === undefined || source.changed_for(this)) {
                result = this._compute(source);
                this._result.set(source, result);
            }
            return result;
        }
    }
    exports.ScalarExpression = ScalarExpression;
    ScalarExpression.__name__ = "ScalarExpression";
},
/* models/expressions/customjs_expr.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const has_props_1 = require(14) /* ../../core/has_props */;
    const expression_1 = require(307) /* ./expression */;
    const types_1 = require(24) /* ../../core/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    const types_2 = require(8) /* ../../core/util/types */;
    class CustomJSExpr extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        connect_signals() {
            super.connect_signals();
            for (const value of (0, object_1.values)(this.args)) {
                if (value instanceof has_props_1.HasProps) {
                    value.change.connect(() => {
                        this._result.clear();
                        this.change.emit();
                    });
                }
            }
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new types_1.GeneratorFunction(...this.names, code);
        }
        _v_compute(source) {
            var _b, _c;
            const generator = this.func.apply(source, this.values);
            let result = generator.next();
            if (((_b = result.done) !== null && _b !== void 0 ? _b : false) && result.value !== undefined) {
                const { value } = result;
                if ((0, types_2.isArray)(value) || (0, types_2.isTypedArray)(value))
                    return value;
                else if ((0, types_2.isIterable)(value))
                    return [...value];
                else
                    return (0, array_1.repeat)(value, source.length);
            }
            else {
                const array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!((_c = result.done) !== null && _c !== void 0 ? _c : false));
                return array;
            }
        }
    }
    exports.CustomJSExpr = CustomJSExpr;
    _a = CustomJSExpr;
    CustomJSExpr.__name__ = "CustomJSExpr";
    (() => {
        _a.define(({ Unknown, String, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [String, ""],
        }));
    })();
},
/* models/expressions/stack.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(307) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    class Stack extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            var _b;
            const n = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 0;
            const result = new Float64Array(n);
            for (const f of this.fields) {
                const column = (0, object_1.dict)(source.data).get(f);
                if (column != null) {
                    const k = Math.min(n, column.length);
                    for (let i = 0; i < k; i++) {
                        result[i] += column[i];
                    }
                }
            }
            return result;
        }
    }
    exports.Stack = Stack;
    _a = Stack;
    Stack.__name__ = "Stack";
    (() => {
        _a.define(({ String, Array }) => ({
            fields: [Array(String), []],
        }));
    })();
},
/* models/expressions/cumsum.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(307) /* ./expression */;
    class CumSum extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            var _b;
            const result = new Float64Array((_b = source.get_length()) !== null && _b !== void 0 ? _b : 0);
            const col = source.data[this.field];
            const offset = this.include_zero ? 1 : 0;
            result[0] = this.include_zero ? 0 : col[0];
            for (let i = 1; i < result.length; i++) {
                result[i] = result[i - 1] + col[i - offset];
            }
            return result;
        }
    }
    exports.CumSum = CumSum;
    _a = CumSum;
    CumSum.__name__ = "CumSum";
    (() => {
        _a.define(({ Boolean, String }) => ({
            field: [String],
            include_zero: [Boolean, false],
        }));
    })();
},
/* models/expressions/minimum.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(307) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    class Minimum extends expression_1.ScalarExpression {
        constructor(attrs) {
            super(attrs);
        }
        _compute(source) {
            var _b;
            const column = (_b = (0, object_1.dict)(source.data).get(this.field)) !== null && _b !== void 0 ? _b : [];
            return Math.min(this.initial, (0, array_1.min)(column));
        }
    }
    exports.Minimum = Minimum;
    _a = Minimum;
    Minimum.__name__ = "Minimum";
    (() => {
        _a.define(({ Number, String }) => ({
            field: [String],
            initial: [Number, Infinity],
        }));
    })();
},
/* models/expressions/maximum.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(307) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    class Maximum extends expression_1.ScalarExpression {
        constructor(attrs) {
            super(attrs);
        }
        _compute(source) {
            var _b;
            const column = (_b = (0, object_1.dict)(source.data).get(this.field)) !== null && _b !== void 0 ? _b : [];
            return Math.max(this.initial, (0, array_1.max)(column));
        }
    }
    exports.Maximum = Maximum;
    _a = Maximum;
    Maximum.__name__ = "Maximum";
    (() => {
        _a.define(({ Number, String }) => ({
            field: [String],
            initial: [Number, -Infinity],
        }));
    })();
},
/* models/expressions/coordinate_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(307) /* ../expressions/expression */;
    class CoordinateTransform extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        get x() {
            return new XComponent({ transform: this });
        }
        get y() {
            return new YComponent({ transform: this });
        }
    }
    exports.CoordinateTransform = CoordinateTransform;
    CoordinateTransform.__name__ = "CoordinateTransform";
    class XYComponent extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.XYComponent = XYComponent;
    _a = XYComponent;
    XYComponent.__name__ = "XYComponent";
    (() => {
        _a.define(({ Ref }) => ({
            transform: [Ref(CoordinateTransform)],
        }));
    })();
    class XComponent extends XYComponent {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            return this.transform.v_compute(source).x;
        }
    }
    exports.XComponent = XComponent;
    XComponent.__name__ = "XComponent";
    class YComponent extends XYComponent {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            return this.transform.v_compute(source).y;
        }
    }
    exports.YComponent = YComponent;
    YComponent.__name__ = "YComponent";
},
/* models/expressions/polar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const coordinate_transform_1 = require(313) /* ../expressions/coordinate_transform */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class PolarTransform extends coordinate_transform_1.CoordinateTransform {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const radius = this.properties.radius.uniform(source);
            const angle = this.properties.angle.uniform(source);
            const coeff = this.direction == "anticlock" ? -1 : 1;
            const n = Math.min(radius.length, angle.length);
            const x = new Float64Array(n);
            const y = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                const radius_i = radius.get(i);
                const angle_i = angle.get(i) * coeff;
                x[i] = radius_i * Math.cos(angle_i);
                y[i] = radius_i * Math.sin(angle_i);
            }
            return { x, y };
        }
    }
    exports.PolarTransform = PolarTransform;
    _a = PolarTransform;
    PolarTransform.__name__ = "PolarTransform";
    (() => {
        _a.define(({}) => ({
            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(316) /* ./boolean_filter */;
    __esExport("BooleanFilter", boolean_filter_1.BooleanFilter);
    var customjs_filter_1 = require(317) /* ./customjs_filter */;
    __esExport("CustomJSFilter", customjs_filter_1.CustomJSFilter);
    var filter_1 = require(221) /* ./filter */;
    __esExport("Filter", filter_1.Filter);
    var group_filter_1 = require(318) /* ./group_filter */;
    __esExport("GroupFilter", group_filter_1.GroupFilter);
    var index_filter_1 = require(319) /* ./index_filter */;
    __esExport("IndexFilter", index_filter_1.IndexFilter);
    var all_indices_1 = require(222) /* ./all_indices */;
    __esExport("AllIndices", all_indices_1.AllIndices);
    var inversion_filter_1 = require(320) /* ./inversion_filter */;
    __esExport("InversionFilter", inversion_filter_1.InversionFilter);
    var intersection_filter_1 = require(223) /* ./intersection_filter */;
    __esExport("IntersectionFilter", intersection_filter_1.IntersectionFilter);
    var union_filter_1 = require(321) /* ./union_filter */;
    __esExport("UnionFilter", union_filter_1.UnionFilter);
    var difference_filter_1 = require(322) /* ./difference_filter */;
    __esExport("DifferenceFilter", difference_filter_1.DifferenceFilter);
    var symmetric_difference_filter_1 = require(323) /* ./symmetric_difference_filter */;
    __esExport("SymmetricDifferenceFilter", symmetric_difference_filter_1.SymmetricDifferenceFilter);
},
/* models/filters/boolean_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class BooleanFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            var _b;
            const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
            const { booleans } = this;
            if (booleans == null) {
                return types_1.Indices.all_set(size);
            }
            else {
                return types_1.Indices.from_booleans(size, booleans);
            }
        }
    }
    exports.BooleanFilter = BooleanFilter;
    _a = BooleanFilter;
    BooleanFilter.__name__ = "BooleanFilter";
    (() => {
        _a.define(({ Boolean, Iterable, Nullable }) => ({
            booleans: [Nullable(Iterable(Boolean)), null],
        }));
    })();
},
/* models/filters/customjs_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_2 = require(8) /* ../../core/util/types */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CustomJSFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function(...this.names, "source", code);
        }
        compute_indices(source) {
            var _b;
            const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
            const filter = this.func(...this.values, source);
            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}`);
        }
    }
    exports.CustomJSFilter = CustomJSFilter;
    _a = CustomJSFilter;
    CustomJSFilter.__name__ = "CustomJSFilter";
    (() => {
        _a.define(({ Unknown, String, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [String, ""],
        }));
    })();
},
/* models/filters/group_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    const logging_1 = require(19) /* ../../core/logging */;
    class GroupFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            var _b;
            const column = source.get_column(this.column_name);
            const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
            if (column == null) {
                logging_1.logger.warn(`${this}: groupby column '${this.column_name}' not found in the data source`);
                return types_1.Indices.all_set(size);
            }
            else {
                const indices = new types_1.Indices(size, 0);
                for (let i = 0; i < indices.size; i++) {
                    if (column[i] === this.group)
                        indices.set(i);
                }
                return indices;
            }
        }
    }
    exports.GroupFilter = GroupFilter;
    _a = GroupFilter;
    GroupFilter.__name__ = "GroupFilter";
    (() => {
        _a.define(({ String }) => ({
            column_name: [String],
            group: [String],
        }));
    })();
},
/* models/filters/index_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class IndexFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            var _b;
            const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
            const { indices } = this;
            if (indices == null) {
                return types_1.Indices.all_set(size);
            }
            else {
                return types_1.Indices.from_indices(size, indices);
            }
        }
    }
    exports.IndexFilter = IndexFilter;
    _a = IndexFilter;
    IndexFilter.__name__ = "IndexFilter";
    (() => {
        _a.define(({ Int, Iterable, Nullable }) => ({
            indices: [Nullable(Iterable(Int)), null],
        }));
    })();
},
/* models/filters/inversion_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    class InversionFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            const index = this.operand.compute_indices(source);
            index.invert();
            return index;
        }
    }
    exports.InversionFilter = InversionFilter;
    _a = InversionFilter;
    InversionFilter.__name__ = "InversionFilter";
    (() => {
        _a.define(({ Ref }) => ({
            operand: [Ref(filter_1.Filter)],
        }));
    })();
},
/* models/filters/union_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class UnionFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            var _b;
            const { operands } = this;
            if (operands.length == 0) {
                const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
                return types_1.Indices.all_set(size);
            }
            else {
                const [index, ...rest] = operands.map((op) => op.compute_indices(source));
                for (const op of rest) {
                    index.add(op);
                }
                return index;
            }
        }
    }
    exports.UnionFilter = UnionFilter;
    _a = UnionFilter;
    UnionFilter.__name__ = "UnionFilter";
    (() => {
        _a.define(({ Array, Ref }) => ({
            operands: [Array(Ref(filter_1.Filter))],
        }));
    })();
},
/* models/filters/difference_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class DifferenceFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            var _b;
            const { operands } = this;
            if (operands.length == 0) {
                const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
                return types_1.Indices.all_set(size);
            }
            else {
                const [index, ...rest] = operands.map((op) => op.compute_indices(source));
                for (const op of rest) {
                    index.subtract(op);
                }
                return index;
            }
        }
    }
    exports.DifferenceFilter = DifferenceFilter;
    _a = DifferenceFilter;
    DifferenceFilter.__name__ = "DifferenceFilter";
    (() => {
        _a.define(({ Array, Ref }) => ({
            operands: [Array(Ref(filter_1.Filter))],
        }));
    })();
},
/* models/filters/symmetric_difference_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(221) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class SymmetricDifferenceFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            var _b;
            const { operands } = this;
            if (operands.length == 0) {
                const size = (_b = source.get_length()) !== null && _b !== void 0 ? _b : 1;
                return types_1.Indices.all_set(size);
            }
            else {
                const [index, ...rest] = operands.map((op) => op.compute_indices(source));
                for (const op of rest) {
                    index.symmetric_subtract(op);
                }
                return index;
            }
        }
    }
    exports.SymmetricDifferenceFilter = SymmetricDifferenceFilter;
    _a = SymmetricDifferenceFilter;
    SymmetricDifferenceFilter.__name__ = "SymmetricDifferenceFilter";
    (() => {
        _a.define(({ Array, Ref }) => ({
            operands: [Array(Ref(filter_1.Filter))],
        }));
    })();
},
/* models/glyphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var annular_wedge_1 = require(325) /* ./annular_wedge */;
    __esExport("AnnularWedge", annular_wedge_1.AnnularWedge);
    var annulus_1 = require(326) /* ./annulus */;
    __esExport("Annulus", annulus_1.Annulus);
    var arc_1 = require(327) /* ./arc */;
    __esExport("Arc", arc_1.Arc);
    var bezier_1 = require(328) /* ./bezier */;
    __esExport("Bezier", bezier_1.Bezier);
    var block_1 = require(330) /* ./block */;
    __esExport("Block", block_1.Block);
    var circle_1 = require(332) /* ./circle */;
    __esExport("Circle", circle_1.Circle);
    var ellipse_1 = require(333) /* ./ellipse */;
    __esExport("Ellipse", ellipse_1.Ellipse);
    var glyph_1 = require(205) /* ./glyph */;
    __esExport("Glyph", glyph_1.Glyph);
    var harea_1 = require(217) /* ./harea */;
    __esExport("HArea", harea_1.HArea);
    var harea_step_1 = require(214) /* ./harea_step */;
    __esExport("HAreaStep", harea_step_1.HAreaStep);
    var hbar_1 = require(335) /* ./hbar */;
    __esExport("HBar", hbar_1.HBar);
    var hspan_1 = require(336) /* ./hspan */;
    __esExport("HSpan", hspan_1.HSpan);
    var hstrip_1 = require(337) /* ./hstrip */;
    __esExport("HStrip", hstrip_1.HStrip);
    var hex_tile_1 = require(338) /* ./hex_tile */;
    __esExport("HexTile", hex_tile_1.HexTile);
    var image_1 = require(339) /* ./image */;
    __esExport("Image", image_1.Image);
    var image_rgba_1 = require(341) /* ./image_rgba */;
    __esExport("ImageRGBA", image_rgba_1.ImageRGBA);
    var image_stack_1 = require(342) /* ./image_stack */;
    __esExport("ImageStack", image_stack_1.ImageStack);
    var image_url_1 = require(343) /* ./image_url */;
    __esExport("ImageURL", image_url_1.ImageURL);
    var line_1 = require(203) /* ./line */;
    __esExport("Line", line_1.Line);
    var multi_line_1 = require(344) /* ./multi_line */;
    __esExport("MultiLine", multi_line_1.MultiLine);
    var multi_polygons_1 = require(345) /* ./multi_polygons */;
    __esExport("MultiPolygons", multi_polygons_1.MultiPolygons);
    var patch_1 = require(213) /* ./patch */;
    __esExport("Patch", patch_1.Patch);
    var patches_1 = require(346) /* ./patches */;
    __esExport("Patches", patches_1.Patches);
    var quad_1 = require(347) /* ./quad */;
    __esExport("Quad", quad_1.Quad);
    var quadratic_1 = require(348) /* ./quadratic */;
    __esExport("Quadratic", quadratic_1.Quadratic);
    var ray_1 = require(349) /* ./ray */;
    __esExport("Ray", ray_1.Ray);
    var rect_1 = require(350) /* ./rect */;
    __esExport("Rect", rect_1.Rect);
    var scatter_1 = require(351) /* ./scatter */;
    __esExport("Scatter", scatter_1.Scatter);
    var segment_1 = require(354) /* ./segment */;
    __esExport("Segment", segment_1.Segment);
    var spline_1 = require(355) /* ./spline */;
    __esExport("Spline", spline_1.Spline);
    var step_1 = require(357) /* ./step */;
    __esExport("Step", step_1.Step);
    var text_1 = require(358) /* ./text */;
    __esExport("Text", text_1.Text);
    var varea_1 = require(219) /* ./varea */;
    __esExport("VArea", varea_1.VArea);
    var varea_step_1 = require(218) /* ./varea_step */;
    __esExport("VAreaStep", varea_step_1.VAreaStep);
    var vbar_1 = require(359) /* ./vbar */;
    __esExport("VBar", vbar_1.VBar);
    var vspan_1 = require(360) /* ./vspan */;
    __esExport("VSpan", vspan_1.VSpan);
    var vstrip_1 = require(361) /* ./vstrip */;
    __esExport("VStrip", vstrip_1.VStrip);
    var wedge_1 = require(362) /* ./wedge */;
    __esExport("Wedge", wedge_1.Wedge);
},
/* models/glyphs/annular_wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const utils_1 = require(211) /* ./utils */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(11) /* ../../core/util/math */;
    const selection_1 = require(103) /* ../selections/selection */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class AnnularWedgeView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { AnnularWedgeGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(530) /* ./webgl/annular_wedge */));
            return AnnularWedgeGL;
        }
        _map_data() {
            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);
            this.max_souter_radius = (0, arrayable_1.max)(this.souter_radius);
        }
        _render(ctx, indices, data) {
            const { sx, sy, start_angle, end_angle, sinner_radius, souter_radius } = data !== null && data !== void 0 ? data : this;
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sinner_radius_i = sinner_radius[i];
                const souter_radius_i = souter_radius[i];
                const start_angle_i = start_angle.get(i);
                const 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;
                const 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);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            // check radius first
            const sx0 = sx - this.max_souter_radius;
            const sx1 = sx + this.max_souter_radius;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const sy0 = sy - this.max_souter_radius;
            const sy1 = sy + this.max_souter_radius;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const or2 = this.souter_radius[i] ** 2;
                const ir2 = this.sinner_radius[i] ** 2;
                const [sx0, sx1] = this.renderer.xscale.r_compute(x, this._x[i]);
                const [sy0, sy1] = this.renderer.yscale.r_compute(y, this._y[i]);
                const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= or2 && dist >= ir2)
                    candidates.push(i);
            }
            const anticlock = this.model.direction == "anticlock";
            const indices = [];
            for (const i of candidates) {
                // NOTE: minus the angle because JS uses non-mathy convention for angles
                const angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
                const is_full_circle = Math.abs(this.start_angle.get(i) - this.end_angle.get(i)) >= 2 * Math.PI;
                if (is_full_circle || (0, math_1.angle_between)(-angle, -this.start_angle.get(i), -this.end_angle.get(i), anticlock)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy(i) {
            const r = (this.sinner_radius[i] + this.souter_radius[i]) / 2;
            const a = (this.start_angle.get(i) + this.end_angle.get(i)) / 2;
            const scx = this.sx[i] + r * Math.cos(a);
            const scy = this.sy[i] + r * Math.sin(a);
            return [scx, scy];
        }
    }
    exports.AnnularWedgeView = AnnularWedgeView;
    AnnularWedgeView.__name__ = "AnnularWedgeView";
    class AnnularWedge extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.AnnularWedge = AnnularWedge;
    _a = AnnularWedge;
    AnnularWedge.__name__ = "AnnularWedge";
    (() => {
        _a.prototype.default_view = AnnularWedgeView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({}) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const types_1 = require(24) /* ../../core/types */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(103) /* ../selections/selection */;
    class AnnulusView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { AnnulusGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(537) /* ./webgl/annulus */));
            return AnnulusGL;
        }
        _map_data() {
            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);
        }
        _render(ctx, indices, data) {
            const { sx, sy, sinner_radius, souter_radius } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sinner_radius_i = sinner_radius[i];
                const souter_radius_i = souter_radius[i];
                if (!isFinite(sx_i + sy_i + sinner_radius_i + souter_radius_i))
                    continue;
                ctx.beginPath();
                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);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            let x0, y0;
            let 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 {
                const sx0 = sx - this.max_outer_radius;
                const sx1 = sx + this.max_outer_radius;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                const sy0 = sy - this.max_outer_radius;
                const sy1 = sy + this.max_outer_radius;
                [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            }
            const indices = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const or2 = this.souter_radius[i] ** 2;
                const ir2 = this.sinner_radius[i] ** 2;
                const [sx0, sx1] = this.renderer.xscale.r_compute(x, this._x[i]);
                const [sy0, sy1] = this.renderer.yscale.r_compute(y, this._y[i]);
                const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= or2 && dist >= ir2)
                    indices.push(i);
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            const len = index + 1;
            const sx = new Array(len);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(len);
            sy[index] = (y0 + y1) / 2;
            const r = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.5;
            const sinner_radius = new Array(len);
            sinner_radius[index] = r * 0.4;
            const souter_radius = new Array(len);
            souter_radius[index] = r * 0.8;
            this._render(ctx, [index], { sx, sy, sinner_radius, souter_radius }); // XXX
        }
    }
    exports.AnnulusView = AnnulusView;
    AnnulusView.__name__ = "AnnulusView";
    class Annulus extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Annulus = Annulus;
    _a = Annulus;
    Annulus.__name__ = "Annulus";
    (() => {
        _a.prototype.default_view = AnnulusView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({}) => ({
            inner_radius: [p.DistanceSpec, { field: "inner_radius" }],
            outer_radius: [p.DistanceSpec, { field: "outer_radius" }],
        }));
    })();
},
/* models/glyphs/arc.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const utils_1 = require(211) /* ./utils */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class ArcView extends xy_glyph_1.XYGlyphView {
        _map_data() {
            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);
        }
        _render(ctx, indices, data) {
            if (!this.visuals.line.doit)
                return;
            const { sx, sy, sradius, start_angle, end_angle } = data !== null && data !== void 0 ? data : this;
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                const start_angle_i = start_angle.get(i);
                const end_angle_i = end_angle.get(i);
                if (!isFinite(sx_i + sy_i + sradius_i + start_angle_i + end_angle_i))
                    continue;
                this._render_decorations(ctx, i, sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                this.visuals.line.apply(ctx, i);
            }
        }
        _render_decorations(ctx, i, sx, sy, sradius, start_angle, end_angle, _anticlock) {
            const { sin, cos, PI } = Math;
            for (const decoration of this.decorations.values()) {
                ctx.save();
                if (decoration.model.node == "start") {
                    const x = sradius * cos(start_angle) + sx;
                    const y = sradius * sin(start_angle) + sy;
                    ctx.translate(x, y);
                    ctx.rotate(start_angle + PI);
                }
                else if (decoration.model.node == "end") {
                    const x = sradius * Math.cos(end_angle) + sx;
                    const y = sradius * Math.sin(end_angle) + sy;
                    ctx.translate(x, y);
                    ctx.rotate(end_angle);
                }
                decoration.marking.render(ctx, i);
                ctx.restore();
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.ArcView = ArcView;
    ArcView.__name__ = "ArcView";
    class Arc extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Arc = Arc;
    _a = Arc;
    Arc.__name__ = "Arc";
    (() => {
        _a.prototype.default_view = ArcView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(({}) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    const algorithms_1 = require(329) /* ../../core/util/algorithms */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class BezierView extends glyph_1.GlyphView {
        _project_data() {
            projections_1.inplace.project_xy(this._x0, this._y0);
            projections_1.inplace.project_xy(this._x1, this._y1);
        }
        _index_data(index) {
            const { data_size, _x0, _y0, _x1, _y1, _cx0, _cy0, _cx1, _cy1 } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = _x0[i];
                const y0_i = _y0[i];
                const x1_i = _x1[i];
                const y1_i = _y1[i];
                const cx0_i = _cx0[i];
                const cy0_i = _cy0[i];
                const cx1_i = _cx1[i];
                const 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 {
                    const { x0, y0, x1, y1 } = (0, algorithms_1.cbb)(x0_i, y0_i, cx0_i, cy0_i, cx1_i, cy1_i, x1_i, y1_i);
                    index.add_rect(x0, y0, x1, y1);
                }
            }
        }
        _render(ctx, indices, data) {
            if (!this.visuals.line.doit)
                return;
            const { sx0, sy0, sx1, sy1, scx0, scy0, scx1, scy1 } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                const scx0_i = scx0[i];
                const scy0_i = scy0[i];
                const scx1_i = scx1[i];
                const 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.apply(ctx, i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.BezierView = BezierView;
    BezierView.__name__ = "BezierView";
    class Bezier extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Bezier = Bezier;
    _a = Bezier;
    Bezier.__name__ = "Bezier";
    (() => {
        _a.prototype.default_view = BezierView;
        _a.define(({}) => ({
            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);
    })();
},
/* core/util/algorithms.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const arrayable_1 = require(13) /* ./arrayable */;
    const { abs, sqrt, min, max } = Math;
    /**
     * 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(x0, y0, cx, cy, x1, y1) {
        function _qbb(u, v, w) {
            if (v == (u + w) / 2)
                return [u, w];
            else {
                const t = (u - v) / (u - 2 * v + w);
                const bd = u * (1 - t) ** 2 + 2 * v * (1 - t) * t + w * t ** 2;
                return [min(u, w, bd), max(u, w, bd)];
            }
        }
        const [x_min, x_max] = _qbb(x0, cx, x1);
        const [y_min, y_max] = _qbb(y0, cy, y1);
        return {
            x0: x_min, x1: x_max,
            y0: y_min, y1: y_max,
        };
    }
    exports.qbb = qbb;
    // algorithm adapted from http://stackoverflow.com/a/14429749/3406693
    function cbb(x0, y0, cx0, cy0, cx1, cy1, x1, y1) {
        const x3 = x1;
        const y3 = y1;
        x1 = cx0;
        y1 = cy0;
        const x2 = cx1;
        const y2 = cy1;
        const tvalues = [];
        for (let i = 0; i <= 2; i++) {
            let a, b, c;
            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 (abs(a) < 1e-12) { // Numerical robustness
                if (abs(b) < 1e-12) // Numerical robustness
                    continue;
                const t = -c / b;
                if (0 < t && t < 1)
                    tvalues.push(t);
                continue;
            }
            const b2ac = b ** 2 - 4 * c * a;
            const sqrtb2ac = sqrt(b2ac);
            if (b2ac < 0)
                continue;
            const t1 = (-b + sqrtb2ac) / (2 * a);
            if (0 < t1 && t1 < 1)
                tvalues.push(t1);
            const t2 = (-b - sqrtb2ac) / (2 * a);
            if (0 < t2 && t2 < 1)
                tvalues.push(t2);
        }
        const n = tvalues.length;
        let j = n;
        const x_bounds = Array(n + 2);
        const y_bounds = Array(n + 2);
        while (j-- > 0) {
            const t = tvalues[j];
            const mt = 1 - t;
            const x = mt ** 3 * x0 + 3 * mt ** 2 * t * x1 + 3 * mt * t ** 2 * x2 + t ** 3 * x3;
            const y = mt ** 3 * y0 + 3 * mt ** 2 * t * y1 + 3 * mt * t ** 2 * y2 + t ** 3 * y3;
            x_bounds[j] = x;
            y_bounds[j] = y;
        }
        x_bounds[n] = x0;
        y_bounds[n] = y0;
        x_bounds[n + 1] = x3;
        y_bounds[n + 1] = y3;
        const [x_min, x_max, y_min, y_max] = (0, arrayable_1.minmax2)(x_bounds, y_bounds);
        return { x0: x_min, x1: x_max, y0: y_min, y1: y_max };
    }
    exports.cbb = cbb;
},
/* models/glyphs/block.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(331) /* ./lrtb */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class BlockView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sleft[i] / 2 + this.sright[i] / 2;
            const scy = this.stop[i] / 2 + this.sbottom[i] / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const x_i = this._x[i];
            const y_i = this._y[i];
            const width_i = this.width.get(i);
            const height_i = this.height.get(i);
            const l = Math.min(x_i, x_i + width_i);
            const r = Math.max(x_i, x_i + width_i);
            const t = Math.max(y_i, y_i + height_i);
            const b = Math.min(y_i, y_i + height_i);
            return [l, r, t, b];
        }
        _map_data() {
            const sx = this.renderer.xscale.v_compute(this._x);
            const sy = this.renderer.yscale.v_compute(this._y);
            const sw = this.sdist(this.renderer.xscale, this._x, this.width, "edge");
            const sh = this.sdist(this.renderer.yscale, this._y, this.height, "edge");
            const n = sx.length;
            this.stop = new types_1.ScreenArray(n);
            this.sbottom = new types_1.ScreenArray(n);
            this.sleft = new types_1.ScreenArray(n);
            this.sright = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++) {
                this.stop[i] = sy[i] - sh[i];
                this.sbottom[i] = sy[i];
                this.sleft[i] = sx[i];
                this.sright[i] = sx[i] + sw[i];
            }
            this._clamp_viewport();
        }
    }
    exports.BlockView = BlockView;
    BlockView.__name__ = "BlockView";
    class Block extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Block = Block;
    _a = Block;
    Block.__name__ = "Block";
    (() => {
        _a.prototype.default_view = BlockView;
        _a.define(({}) => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y: [p.YCoordinateSpec, { field: "y" }],
            width: [p.NumberSpec, { value: 1 }],
            height: [p.NumberSpec, { value: 1 }],
        }));
    })();
},
/* models/glyphs/lrtb.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const selection_1 = require(103) /* ../selections/selection */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(240) /* ../common/resolve */);
    const painting_1 = require(239) /* ../common/painting */;
    class LRTBView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(544) /* ./webgl/lrtb */));
            return LRTBGL;
        }
        get_anchor_point(anchor, i, _spt) {
            const left = Math.min(this.sleft[i], this.sright[i]);
            const right = Math.max(this.sright[i], this.sleft[i]);
            const top = Math.min(this.stop[i], this.sbottom[i]); // screen coordinates !!!
            const 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 };
            }
        }
        _set_data(indices) {
            super._set_data(indices);
            this.border_radius = resolve.border_radius(this.model.border_radius);
        }
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const [l, r, t, b] = this._lrtb(i);
                index.add_rect(min(l, r), min(t, b), max(r, l), max(t, b));
            }
        }
        _render(ctx, indices, data) {
            const { sleft, sright, stop, sbottom, border_radius } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sleft_i = sleft[i];
                const stop_i = stop[i];
                const sright_i = sright[i];
                const sbottom_i = sbottom[i];
                if (!isFinite(sleft_i + stop_i + sright_i + sbottom_i))
                    continue;
                ctx.beginPath();
                const box = bbox_1.BBox.from_lrtb({ left: sleft_i, right: sright_i, top: stop_i, bottom: sbottom_i });
                (0, painting_1.round_rect)(ctx, box, border_radius);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        // We need to clamp the endpoints inside the viewport, because various browser canvas
        // implementations have issues drawing rects with enpoints far outside the viewport
        _clamp_viewport() {
            const hr = this.renderer.plot_view.frame.bbox.h_range;
            const vr = this.renderer.plot_view.frame.bbox.v_range;
            const n = this.stop.length;
            for (let 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);
            }
        }
        _hit_rect(geometry) {
            return this._hit_rect_against_index(geometry);
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const indices = [...this.index.indices({ x0: x, y0: y, x1: x, y1: y })];
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let indices;
            if (geometry.direction == "v") {
                const y = this.renderer.yscale.invert(sy);
                const hr = this.renderer.plot_view.frame.bbox.h_range;
                const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end);
                indices = [...this.index.indices({ x0, y0: y, x1, y1: y })];
            }
            else {
                const x = this.renderer.xscale.invert(sx);
                const vr = this.renderer.plot_view.frame.bbox.v_range;
                const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end);
                indices = [...this.index.indices({ x0: x, y0, x1: x, y1 })];
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.LRTBView = LRTBView;
    LRTBView.__name__ = "LRTBView";
    class LRTB extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LRTB = LRTB;
    _a = LRTB;
    LRTB.__name__ = "LRTB";
    (() => {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(() => ({
            border_radius: [kinds_1.BorderRadius, 0],
        }));
    })();
},
/* models/glyphs/circle.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const uniforms = tslib_1.__importStar(require(39) /* ../../core/uniforms */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const selection_1 = require(103) /* ../selections/selection */;
    class CircleView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { CircleGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(539) /* ./webgl/circle */));
            return CircleGL;
        }
        get use_radius() {
            return !(this.radius.is_Scalar() && isNaN(this.radius.value));
        }
        _set_data(indices) {
            super._set_data(indices);
            const max_size = this.use_radius ? 2 * this.max_radius : uniforms.max(this.size);
            this._configure("max_size", { value: max_size });
        }
        _index_data(index) {
            if (this.use_radius) {
                const { _x, _y, radius, data_size } = this;
                for (let i = 0; i < data_size; i++) {
                    const x = _x[i];
                    const y = _y[i];
                    const r = radius.get(i);
                    index.add_rect(x - r, y - r, x + r, y + r);
                }
            }
            else {
                super._index_data(index);
            }
        }
        _map_data() {
            // 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": {
                            const sradius_x = this.sdist(this.renderer.xscale, this._x, this.radius);
                            const sradius_y = this.sdist(this.renderer.yscale, this._y, this.radius);
                            this.sradius = (0, arrayable_1.map)(sradius_x, (s, i) => Math.max(s, sradius_y[i]));
                            break;
                        }
                        case "min": {
                            const sradius_x = this.sdist(this.renderer.xscale, this._x, this.radius);
                            const sradius_y = this.sdist(this.renderer.yscale, this._y, this.radius);
                            this.sradius = (0, arrayable_1.map)(sradius_x, (s, i) => Math.min(s, sradius_y[i]));
                            break;
                        }
                    }
                }
                else
                    this.sradius = (0, types_1.to_screen)(this.radius);
            }
            else {
                const ssize = types_1.ScreenArray.from(this.size);
                this.sradius = (0, arrayable_1.map)(ssize, (s) => s / 2);
            }
        }
        _mask_data() {
            const { frame } = this.renderer.plot_view;
            const shr = frame.x_target;
            const svr = frame.y_target;
            let hr;
            let vr;
            if (this.use_radius && this.model.properties.radius.units == "data") {
                hr = shr.map((x) => this.renderer.xscale.invert(x)).widen(this.max_radius);
                vr = svr.map((y) => this.renderer.yscale.invert(y)).widen(this.max_radius);
            }
            else {
                hr = shr.widen(this.max_size).map((x) => this.renderer.xscale.invert(x));
                vr = svr.widen(this.max_size).map((y) => this.renderer.yscale.invert(y));
            }
            return this.index.indices({
                x0: hr.start, x1: hr.end,
                y0: vr.start, y1: vr.end,
            });
        }
        _render(ctx, indices, data) {
            const { sx, sy, sradius } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const 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);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const { hit_dilation } = this.model;
            const [x0, x1, y0, y1] = (() => {
                if (this.use_radius && this.model.properties.radius.units == "data") {
                    const dr = this.max_radius * hit_dilation;
                    const x0 = x - dr;
                    const x1 = x + dr;
                    const y0 = y - dr;
                    const y1 = y + dr;
                    return [x0, x1, y0, y1];
                }
                else {
                    const ds = this.max_size * hit_dilation;
                    const sx0 = sx - ds;
                    const sx1 = sx + ds;
                    const sy0 = sy - ds;
                    const sy1 = sy + ds;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            if (this.use_radius && this.model.properties.radius.units == "data") {
                for (const i of candidates) {
                    const r2 = (this.sradius[i] * hit_dilation) ** 2;
                    const [sx0, sx1] = this.renderer.xscale.r_compute(x, this._x[i]);
                    const [sy0, sy1] = this.renderer.yscale.r_compute(y, this._y[i]);
                    const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                    if (dist <= r2) {
                        indices.push(i);
                    }
                }
            }
            else {
                for (const i of candidates) {
                    const r2 = (this.sradius[i] * hit_dilation) ** 2;
                    const dist = (this.sx[i] - sx) ** 2 + (this.sy[i] - sy) ** 2;
                    if (dist <= r2) {
                        indices.push(i);
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            const bounds = this.bounds();
            const [x0, x1, y0, y1] = (() => {
                const use_radius = this.use_radius && this.model.properties.radius.units == "data";
                const dr = use_radius ? this.max_radius : this.max_size / 2;
                if (geometry.direction == "h") {
                    // use circle bounds instead of current pointer y coordinates
                    const sx0 = sx - dr;
                    const sx1 = sx + dr;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    const { y0, y1 } = bounds;
                    return [x0, x1, y0, y1];
                }
                else {
                    // use circle bounds instead of current pointer x coordinates
                    const sy0 = sy - dr;
                    const sy1 = sy + dr;
                    const { x0, x1 } = bounds;
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            for (const i of candidates) {
                const sx_i = this.sx[i];
                const sy_i = this.sy[i];
                if (sx0 <= sx_i && sx_i <= sx1 && sy0 <= sy_i && sy_i <= sy1) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys } = geometry;
            const candidates = (() => {
                const [sx0, sx1, sy0, sy1] = (0, arrayable_1.minmax2)(sxs, sys);
                const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sxs, sys)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        // circle does not inherit from marker (since it also accepts radius) so we
        // must supply a draw_legend for it  here
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            // using objects like this seems a little wonky, since the keys are coerced to
            // stings, but it works
            const len = index + 1;
            const sx = new Array(len);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(len);
            sy[index] = (y0 + y1) / 2;
            const sradius = new Array(len);
            sradius[index] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.2;
            this._render(ctx, [index], { sx, sy, sradius }); // XXX
        }
    }
    exports.CircleView = CircleView;
    CircleView.__name__ = "CircleView";
    class Circle extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Circle = Circle;
    _a = Circle;
    Circle.__name__ = "Circle";
    (() => {
        _a.prototype.default_view = CircleView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({ Number }) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const center_rotatable_1 = require(334) /* ./center_rotatable */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const types_1 = require(24) /* ../../core/types */;
    const selection_1 = require(103) /* ../selections/selection */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class EllipseView extends center_rotatable_1.CenterRotatableView {
        _map_data() {
            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);
        }
        _render(ctx, indices, data) {
            const { sx, sy, sw, sh, angle } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sw_i = sw[i];
                const sh_i = sh[i];
                const 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);
            }
        }
        _hit_point(geometry) {
            let x0, x1, y0, y1, cond, sx0, sx1, sy0, sy1;
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const 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;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            }
            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;
                [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            }
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            for (const i of candidates) {
                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);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            const n = index + 1;
            const sx = new Array(n);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(n);
            sy[index] = (y0 + y1) / 2;
            const scale = this.sw[index] / this.sh[index];
            const d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
            const sw = new Array(n);
            const sh = new Array(n);
            if (scale > 1) {
                sw[index] = d;
                sh[index] = d / scale;
            }
            else {
                sw[index] = d * scale;
                sh[index] = d;
            }
            const angle = new p.UniformScalar(0, n); // don't attempt to match glyph angle
            this._render(ctx, [index], { sx, sy, sw, sh, angle }); // XXX
        }
    }
    exports.EllipseView = EllipseView;
    EllipseView.__name__ = "EllipseView";
    class Ellipse extends center_rotatable_1.CenterRotatable {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ellipse = Ellipse;
    _a = Ellipse;
    Ellipse.__name__ = "Ellipse";
    (() => {
        _a.prototype.default_view = EllipseView;
    })();
},
/* models/glyphs/center_rotatable.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class CenterRotatableView extends xy_glyph_1.XYGlyphView {
        get max_w2() {
            return this.model.properties.width.units == "data" ? this.max_width / 2 : 0;
        }
        get max_h2() {
            return this.model.properties.height.units == "data" ? this.max_height / 2 : 0;
        }
        _bounds({ x0, x1, y0, y1 }) {
            const { max_w2, max_h2 } = this;
            return {
                x0: x0 - max_w2,
                x1: x1 + max_w2,
                y0: y0 - max_h2,
                y1: y1 + max_h2,
            };
        }
    }
    exports.CenterRotatableView = CenterRotatableView;
    CenterRotatableView.__name__ = "CenterRotatableView";
    class CenterRotatable extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CenterRotatable = CenterRotatable;
    _a = CenterRotatable;
    CenterRotatable.__name__ = "CenterRotatable";
    (() => {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({}) => ({
            angle: [p.AngleSpec, 0],
            width: [p.DistanceSpec, { field: "width" }],
            height: [p.DistanceSpec, { field: "height" }],
        }));
    })();
},
/* models/glyphs/hbar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(331) /* ./lrtb */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class HBarView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = (this.sleft[i] + this.sright[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
        _lrtb(i) {
            const left_i = this._left[i];
            const right_i = this._right[i];
            const y_i = this._y[i];
            const half_height_i = this.height.get(i) / 2;
            const l = Math.min(left_i, right_i);
            const r = Math.max(left_i, right_i);
            const t = y_i + half_height_i;
            const b = y_i - half_height_i;
            return [l, r, t, b];
        }
        _map_data() {
            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);
            const n = this.sy.length;
            this.stop = new types_1.ScreenArray(n);
            this.sbottom = new types_1.ScreenArray(n);
            for (let 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();
        }
    }
    exports.HBarView = HBarView;
    HBarView.__name__ = "HBarView";
    class HBar extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HBar = HBar;
    _a = HBar;
    HBar.__name__ = "HBar";
    (() => {
        _a.prototype.default_view = HBarView;
        _a.define(({}) => ({
            left: [p.XCoordinateSpec, { value: 0 }],
            y: [p.YCoordinateSpec, { field: "y" }],
            height: [p.NumberSpec, { value: 1 }],
            right: [p.XCoordinateSpec, { field: "right" }],
        }));
    })();
},
/* models/glyphs/hspan.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const selection_1 = require(103) /* ../selections/selection */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const uniforms = tslib_1.__importStar(require(39) /* ../../core/uniforms */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const { abs, max } = Math;
    const UNUSED = 0;
    class HSpanView extends glyph_1.GlyphView {
        after_visuals() {
            super.after_visuals();
            this.max_line_width = uniforms.max(this.line_width);
        }
        _index_data(index) {
            for (const y_i of this._y) {
                index.add_point(UNUSED, y_i);
            }
        }
        _bounds(bounds) {
            const { y0, y1 } = bounds;
            return { x0: NaN, x1: NaN, y0, y1 };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            this.sy = (0, arrayable_1.map)(this.sy, (yi) => round(yi));
        }
        scenterxy(i) {
            const { hcenter } = this.renderer.plot_view.frame.bbox;
            return [hcenter, this.sy[i]];
        }
        _render(ctx, indices, data) {
            const { sy } = data !== null && data !== void 0 ? data : this;
            const { left, right } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sy_i = sy[i];
                if (!isFinite(sy_i))
                    continue;
                ctx.beginPath();
                ctx.moveTo(left, sy_i);
                ctx.lineTo(right, sy_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sy0, sy1) {
            const { max_line_width } = this;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0 - max_line_width, (sy1 !== null && sy1 !== void 0 ? sy1 : sy0) + max_line_width);
            return this.index.indices({ x0: 0, x1: 0, y0, y1 });
        }
        _find_spans(candidates, fn) {
            const { sy, line_width } = this;
            const indices = [];
            for (const i of candidates) {
                const sy_i = sy[i];
                const line_width_i = line_width.get(i);
                if (fn(sy_i, line_width_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sy: gsy } = geometry;
            const candidates = this._get_candidates(gsy);
            const indices = this._find_spans(candidates, (sy, line_width) => {
                return abs(sy - gsy) <= max(line_width / 2, 2 /*px*/);
            });
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "v") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sy: gsy } = geometry;
                    const candidates = this._get_candidates(gsy);
                    return this._find_spans(candidates, (sy, line_width) => {
                        return abs(sy - gsy) <= max(line_width / 2, 2 /*px*/);
                    });
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sy0: gsy0, sy1: gsy1 } = geometry;
                const candidates = this._get_candidates(gsy0, gsy1);
                return this._find_spans(candidates, (sy, line_width) => {
                    return gsy0 - line_width / 2 <= sy && sy <= gsy1 + line_width / 2;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HSpanView = HSpanView;
    HSpanView.__name__ = "HSpanView";
    class HSpan extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HSpan = HSpan;
    _a = HSpan;
    HSpan.__name__ = "HSpan";
    (() => {
        _a.prototype.default_view = HSpanView;
        _a.mixins([property_mixins_1.LineVector]);
        _a.define(() => ({
            y: [p.YCoordinateSpec, { field: "y" }],
        }));
    })();
},
/* models/glyphs/hstrip.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const selection_1 = require(103) /* ../selections/selection */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const iter = tslib_1.__importStar(require(34) /* ../../core/util/iterator */);
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const UNUSED = 0;
    class HStripView extends glyph_1.GlyphView {
        async lazy_initialize() {
            await super.lazy_initialize();
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null && webgl.regl_wrapper.has_webgl) {
                const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(544) /* ./webgl/lrtb */));
                this.glglyph = new LRTBGL(webgl.regl_wrapper, this);
            }
        }
        get sleft() {
            const { left } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sleft = new types_1.ScreenArray(n);
            sleft.fill(left);
            return sleft;
        }
        get sright() {
            const { right } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sright = new types_1.ScreenArray(n);
            sright.fill(right);
            return sright;
        }
        get stop() {
            return this.sy0;
        }
        get sbottom() {
            return this.sy1;
        }
        _set_data(indices) {
            super._set_data(indices);
            const { abs } = Math;
            const { max, map, zip } = iter;
            const { _y0, _y1 } = this;
            this.max_height = max(map(zip(_y0, _y1), ([y0_i, y1_i]) => abs(y0_i - y1_i)));
        }
        _index_data(index) {
            const { _y0, _y1, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const y0_i = _y0[i];
                const y1_i = _y1[i];
                index.add_rect(UNUSED, y0_i, UNUSED, y1_i);
            }
        }
        _bounds(bounds) {
            const { y0, y1 } = bounds;
            return { x0: NaN, x1: NaN, y0, y1 };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            this.sy0 = (0, arrayable_1.map)(this.sy0, (yi) => round(yi));
            this.sy1 = (0, arrayable_1.map)(this.sy1, (yi) => round(yi));
        }
        scenterxy(i) {
            const { hcenter } = this.renderer.plot_view.frame.bbox;
            return [hcenter, (this.sy0[i] + this.sy1[i]) / 2];
        }
        _render(ctx, indices, data) {
            const { sy0, sy1 } = data !== null && data !== void 0 ? data : this;
            const { left, right, width } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sy0_i = sy0[i];
                const sy1_i = sy1[i];
                if (!isFinite(sy0_i + sy1_i))
                    continue;
                ctx.beginPath();
                ctx.rect(left, sy0_i, width, sy1_i - sy0_i);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                ctx.beginPath();
                ctx.moveTo(left, sy0_i);
                ctx.lineTo(right, sy0_i);
                ctx.moveTo(left, sy1_i);
                ctx.lineTo(right, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sy0, sy1) {
            const { max_height } = this;
            const [dy0, dy1] = this.renderer.yscale.r_invert(sy0, sy1 !== null && sy1 !== void 0 ? sy1 : sy0);
            const y0 = dy0 - max_height;
            const y1 = dy1 + max_height;
            return this.index.indices({ x0: 0, x1: 0, y0, y1 });
        }
        _find_strips(candidates, fn) {
            function contains(sy0, sy1) {
                return sy0 <= sy1 ? fn(sy0, sy1) : fn(sy1, sy0);
            }
            const { sy0, sy1 } = this;
            const indices = [];
            for (const i of candidates) {
                const sy0_i = sy0[i];
                const sy1_i = sy1[i];
                if (contains(sy0_i, sy1_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sy } = geometry;
            const candidates = this._get_candidates(sy);
            const indices = this._find_strips(candidates, (sy0, sy1) => sy0 <= sy && sy <= sy1);
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "v") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sy } = geometry;
                    const candidates = this._get_candidates(sy);
                    return this._find_strips(candidates, (sy0, sy1) => sy0 <= sy && sy <= sy1);
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sy0: gsy0, sy1: gsy1 } = geometry;
                const candidates = this._get_candidates(gsy0, gsy1);
                return this._find_strips(candidates, (sy0, sy1) => {
                    return gsy0 <= sy0 && sy0 <= gsy1 && gsy0 <= sy1 && sy1 <= gsy1;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HStripView = HStripView;
    HStripView.__name__ = "HStripView";
    class HStrip extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HStrip = HStrip;
    _a = HStrip;
    HStrip.__name__ = "HStrip";
    (() => {
        _a.prototype.default_view = HStripView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(() => ({
            y0: [p.YCoordinateSpec, { field: "y0" }],
            y1: [p.YCoordinateSpec, { field: "y1" }],
        }));
    })();
},
/* models/glyphs/hex_tile.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(205) /* ./glyph */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const enums_1 = require(20) /* ../../core/enums */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    const utils_1 = require(211) /* ./utils */;
    const selection_1 = require(103) /* ../selections/selection */;
    class HexTileView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { HexTileGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(540) /* ./webgl/hex_tile */));
            return HexTileGL;
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = this.sy[i];
            return [scx, scy];
        }
        _set_data() {
            const { orientation, size, aspect_scale } = this.model;
            const { q, r } = this;
            const n = this.q.length;
            this._x = new Float64Array(n);
            this._y = new Float64Array(n);
            const { _x, _y } = this;
            const sqrt3 = Math.sqrt(3);
            if (orientation == "pointytop") {
                for (let i = 0; i < n; i++) {
                    const q_i = q.get(i);
                    const r2_i = r.get(i) / 2;
                    _x[i] = size * sqrt3 * (q_i + r2_i) / aspect_scale;
                    _y[i] = -3 * size * r2_i;
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    const q2_i = q.get(i) / 2;
                    const r_i = r.get(i);
                    _x[i] = 3 * size * q2_i;
                    _y[i] = -size * sqrt3 * (r_i + q2_i) * aspect_scale;
                }
            }
        }
        _project_data() {
            projections_1.inplace.project_xy(this._x, this._y);
        }
        _index_data(index) {
            let ysize = this.model.size;
            let xsize = Math.sqrt(3) * ysize / 2;
            if (this.model.orientation == "flattop") {
                [xsize, ysize] = [ysize, xsize];
                ysize *= this.model.aspect_scale;
            }
            else
                xsize /= this.model.aspect_scale;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x = this._x[i];
                const 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
        map_data() {
            var _b;
            [this.sx, this.sy] = this.renderer.coordinates.map_to_screen(this._x, this._y);
            [this.svx, this.svy] = this._get_unscaled_vertices();
            // From overridden GlyphView.map_data()
            (_b = this.glglyph) === null || _b === void 0 ? void 0 : _b.set_data_mapped();
        }
        _get_unscaled_vertices() {
            const size = this.model.size;
            const aspect_scale = this.model.aspect_scale;
            if (this.model.orientation == "pointytop") {
                const rscale = this.renderer.yscale;
                const hscale = this.renderer.xscale;
                const r = Math.abs(rscale.compute(0) - rscale.compute(size)); // assumes linear scale
                const h = Math.sqrt(3) / 2 * Math.abs(hscale.compute(0) - hscale.compute(size)) / aspect_scale; // assumes linear scale
                const r2 = r / 2.0;
                const svx = [0, -h, -h, 0, h, h];
                const svy = [r, r2, -r2, -r, -r2, r2];
                return [svx, svy];
            }
            else {
                const rscale = this.renderer.xscale;
                const hscale = this.renderer.yscale;
                const r = Math.abs(rscale.compute(0) - rscale.compute(size)); // assumes linear scale
                const h = Math.sqrt(3) / 2 * Math.abs(hscale.compute(0) - hscale.compute(size)) * aspect_scale; // assumes linear scale
                const r2 = r / 2.0;
                const svx = [r, r2, -r2, -r, -r2, r2];
                const svy = [0, -h, -h, 0, h, h];
                return [svx, svy];
            }
        }
        _render(ctx, indices, data) {
            const { sx, sy, svx, svy, scale } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const scale_i = scale.get(i);
                if (!isFinite(sx_i + sy_i + scale_i))
                    continue;
                ctx.translate(sx_i, sy_i);
                ctx.beginPath();
                for (let 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);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(sx - this.sx[i], sy - this.sy[i], this.svx, this.svy)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let indices;
            if (geometry.direction == "v") {
                const y = this.renderer.yscale.invert(sy);
                const hr = this.renderer.plot_view.frame.bbox.h_range;
                const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end);
                indices = [...this.index.indices({ x0, y0: y, x1, y1: y })];
            }
            else {
                const x = this.renderer.xscale.invert(sx);
                const vr = this.renderer.plot_view.frame.bbox.v_range;
                const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end);
                indices = [...this.index.indices({ x0: x, y0, x1: x, y1 })];
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HexTileView = HexTileView;
    HexTileView.__name__ = "HexTileView";
    class HexTile extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HexTile = HexTile;
    _a = HexTile;
    HexTile.__name__ = "HexTile";
    (() => {
        _a.prototype.default_view = HexTileView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({ Number }) => ({
            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) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (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))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    var _a;
    __esModule();
    const image_base_1 = require(340) /* ./image_base */;
    const color_mapper_1 = require(199) /* ../mappers/color_mapper */;
    const linear_color_mapper_1 = require(249) /* ../mappers/linear_color_mapper */;
    class ImageView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(541) /* ./webgl/image */));
            return ImageGL;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.color_mapper.change, () => this._update_image());
        }
        _update_image() {
            if (this.glglyph != null) {
                this.glglyph.set_image_changed();
            }
            // Only reset image_data if already initialized
            if (this._image_data != null) {
                this._set_data(null);
                this.renderer.request_render();
            }
        }
        _flat_img_to_buf8(img) {
            const cmap = this.model.color_mapper.rgba_mapper;
            return cmap.v_compute(img);
        }
    }
    exports.ImageView = ImageView;
    ImageView.__name__ = "ImageView";
    // NOTE: this needs to be redefined here, because palettes are located in bokeh-api.js bundle
    const Greys9 = () => ["#000000", "#252525", "#525252", "#737373", "#969696", "#bdbdbd", "#d9d9d9", "#f0f0f0", "#ffffff"];
    class Image extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Image = Image;
    _a = Image;
    Image.__name__ = "Image";
    (() => {
        _a.prototype.default_view = ImageView;
        _a.define(({ Ref }) => ({
            color_mapper: [Ref(color_mapper_1.ColorMapper), () => new linear_color_mapper_1.LinearColorMapper({ palette: Greys9() })],
        }));
    })();
},
/* models/glyphs/image_base.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const selection_1 = require(103) /* ../selections/selection */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const resolve_1 = require(240) /* ../common/resolve */;
    class ImageBaseView extends xy_glyph_1.XYGlyphView {
        constructor() {
            super(...arguments);
            this._image_data = null;
        }
        get image_data() {
            (0, assert_1.assert)(this._image_data != null, "data not set");
            return this._image_data;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.global_alpha.change, () => this.renderer.request_render());
        }
        get image_dimension() {
            return 2;
        }
        get xy_scale() {
            switch (this.model.origin) {
                case "bottom_left": return { x: 1, y: -1 };
                case "top_left": return { x: 1, y: 1 };
                case "bottom_right": return { x: -1, y: -1 };
                case "top_right": return { x: -1, y: 1 };
            }
        }
        get xy_offset() {
            switch (this.model.origin) {
                case "bottom_left": return { x: 0.0, y: 1.0 };
                case "top_left": return { x: 0.0, y: 0.0 };
                case "bottom_right": return { x: 1.0, y: 1.0 };
                case "top_right": return { x: 1.0, y: 0.0 };
            }
        }
        get xy_anchor() {
            return (0, resolve_1.anchor)(this.model.anchor);
        }
        get xy_sign() {
            const xr = this.renderer.xscale.source_range;
            const yr = this.renderer.yscale.source_range;
            return {
                x: xr.is_reversed ? -1 : 1,
                y: yr.is_reversed ? -1 : 1,
            };
        }
        _render(ctx, indices, data) {
            const { image_data, sx, sy, sw, sh } = data !== null && data !== void 0 ? data : this;
            const { xy_sign, xy_scale, xy_offset, xy_anchor } = this;
            ctx.save();
            ctx.imageSmoothingEnabled = false;
            if (this.visuals.image.doit) {
                for (const i of indices) {
                    const image_data_i = image_data[i];
                    const sx_i = sx[i];
                    const sy_i = sy[i];
                    const sw_i = sw[i];
                    const sh_i = sh[i];
                    if (image_data_i == null || !isFinite(sx_i + sy_i + sw_i + sh_i))
                        continue;
                    const tx_i = xy_sign.x * xy_anchor.x * sw_i;
                    const ty_i = xy_sign.y * xy_anchor.y * sh_i;
                    ctx.save();
                    ctx.translate(sx_i - tx_i, sy_i - ty_i);
                    ctx.scale(xy_sign.x * xy_scale.x, xy_sign.y * xy_scale.y);
                    this.visuals.image.set_vectorize(ctx, i);
                    ctx.drawImage(image_data_i, -xy_offset.x * sw_i, -xy_offset.y * sh_i, sw_i, sh_i);
                    ctx.restore();
                }
            }
            ctx.restore();
        }
        _set_data(indices) {
            const n = this.data_size;
            if (this._image_data == null || this._image_data.length != n) {
                this._image_data = new Array(n).fill(null);
                this._width = new Uint32Array(n);
                this._height = new Uint32Array(n);
            }
            const { image_dimension } = this;
            for (let i = 0; i < n; i++) {
                if (indices != null && !indices.includes(i))
                    continue;
                const img = this.image.get(i);
                (0, assert_1.assert)(img.dimension == image_dimension, `expected a ${image_dimension}D array, not ${img.dimension}D`);
                const [width, height] = img.shape;
                this._height[i] = width;
                this._width[i] = height;
                const buf8 = this._flat_img_to_buf8(img);
                this._set_image_data_from_buffer(i, buf8);
            }
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const [l, r, t, b] = this._lrtb(i);
                index.add_rect(l, b, r, t);
            }
        }
        _lrtb(i) {
            const dw_i = this.dw.get(i);
            const dh_i = this.dh.get(i);
            const x_i = this._x[i];
            const y_i = this._y[i];
            const { xy_anchor } = this;
            const [x0, x1] = [x_i - xy_anchor.x * dw_i, x_i + (1 - xy_anchor.x) * dw_i];
            const [y0, y1] = [y_i + xy_anchor.y * dh_i, y_i - (1 - xy_anchor.y) * dh_i];
            const [l, r] = x0 <= x1 ? [x0, x1] : [x1, x0];
            const [b, t] = y0 <= y1 ? [y0, y1] : [y1, y0];
            return [l, r, t, b];
        }
        _get_or_create_canvas(i) {
            const image_data_i = this.image_data[i];
            if (image_data_i != null && image_data_i.width == this._width[i]
                && image_data_i.height == this._height[i])
                return image_data_i;
            else {
                const canvas = document.createElement("canvas");
                canvas.width = this._width[i];
                canvas.height = this._height[i];
                return canvas;
            }
        }
        _set_image_data_from_buffer(i, buf8) {
            const canvas = this._get_or_create_canvas(i);
            const ctx = canvas.getContext("2d");
            const 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;
        }
        _map_data() {
            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);
        }
        _image_index(index, x, y) {
            const [l, r, t, b] = this._lrtb(index);
            const width = this._width[index];
            const height = this._height[index];
            const dx = (r - l) / width;
            const dy = (t - b) / height;
            let i = Math.floor((x - l) / dx);
            let j = Math.floor((y - b) / dy);
            if (this.renderer.xscale.source_range.is_reversed)
                i = width - i - 1;
            if (this.renderer.yscale.source_range.is_reversed)
                j = height - j - 1;
            return { index, i, j, flat_index: j * width + i };
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, x1: x, y0: y, y1: y });
            const result = new selection_1.Selection();
            const indices = [];
            for (const index of candidates) {
                if (sx != Infinity && sy != Infinity) {
                    indices.push(index);
                    result.image_indices.push(this._image_index(index, x, y));
                }
            }
            result.indices = indices;
            return result;
        }
    }
    exports.ImageBaseView = ImageBaseView;
    ImageBaseView.__name__ = "ImageBaseView";
    class ImageBase extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImageBase = ImageBase;
    _a = ImageBase;
    ImageBase.__name__ = "ImageBase";
    (() => {
        _a.mixins(mixins.ImageVector);
        _a.define(({ Boolean }) => ({
            image: [p.NDArraySpec, { field: "image" }],
            dw: [p.DistanceSpec, { field: "dw" }],
            dh: [p.DistanceSpec, { field: "dh" }],
            dilate: [Boolean, false],
            origin: [enums_1.ImageOrigin, "bottom_left"],
            anchor: [kinds_1.Anchor, "bottom_left"],
        }));
    })();
},
/* models/glyphs/image_rgba.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (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))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    var _a;
    __esModule();
    const image_base_1 = require(340) /* ./image_base */;
    const types_1 = require(8) /* ../../core/util/types */;
    class ImageRGBAView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(541) /* ./webgl/image */));
            return ImageGL;
        }
        _flat_img_to_buf8(img) {
            const array = (0, types_1.isTypedArray)(img) ? img : new Uint32Array(img);
            return new Uint8ClampedArray(array.buffer);
        }
    }
    exports.ImageRGBAView = ImageRGBAView;
    ImageRGBAView.__name__ = "ImageRGBAView";
    class ImageRGBA extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImageRGBA = ImageRGBA;
    _a = ImageRGBA;
    ImageRGBA.__name__ = "ImageRGBA";
    (() => {
        _a.prototype.default_view = ImageRGBAView;
    })();
},
/* models/glyphs/image_stack.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (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))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    var _a;
    __esModule();
    const image_base_1 = require(340) /* ./image_base */;
    const stack_color_mapper_1 = require(252) /* ../mappers/stack_color_mapper */;
    class ImageStackView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(541) /* ./webgl/image */));
            return ImageGL;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.color_mapper.change, () => this._update_image());
        }
        get image_dimension() {
            return 3;
        }
        _update_image() {
            if (this.glglyph != null) {
                this.glglyph.set_image_changed();
            }
            // Only reset image_data if already initialized
            if (this._image_data != null) {
                this._set_data(null);
                this.renderer.request_render();
            }
        }
        _flat_img_to_buf8(img) {
            const cmap = this.model.color_mapper.rgba_mapper;
            return cmap.v_compute(img);
        }
    }
    exports.ImageStackView = ImageStackView;
    ImageStackView.__name__ = "ImageStackView";
    class ImageStack extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImageStack = ImageStack;
    _a = ImageStack;
    ImageStack.__name__ = "ImageStack";
    (() => {
        _a.prototype.default_view = ImageStackView;
        _a.define(({ Ref }) => ({
            color_mapper: [Ref(stack_color_mapper_1.StackColorMapper)],
        }));
    })();
},
/* models/glyphs/image_url.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const image_1 = require(152) /* ../../core/util/image */;
    const resolve = tslib_1.__importStar(require(240) /* ../common/resolve */);
    class ImageURLView extends xy_glyph_1.XYGlyphView {
        constructor() {
            super(...arguments);
            this._images_rendered = false;
            this._set_data_iteration = 0;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.global_alpha.change, () => this.renderer.request_render());
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                // TODO: add a proper implementation (same as ImageBase?)
                index.add_empty();
            }
        }
        _set_data() {
            // TODO: cache by url, to reuse images between iterations
            this._set_data_iteration++;
            const n_urls = this.url.length;
            this.image = new Array(n_urls);
            this.rendered = new types_1.Indices(n_urls);
            const { retry_attempts, retry_timeout } = this.model;
            const { _set_data_iteration } = this;
            for (let i = 0; i < n_urls; i++) {
                const url = this.url.get(i);
                if (url == "")
                    continue;
                const loader = new image_1.ImageLoader(url, {
                    loaded: () => {
                        if (this._set_data_iteration == _set_data_iteration && !this.rendered.get(i)) {
                            this.renderer.request_render();
                        }
                    },
                    failed: () => {
                        if (this._set_data_iteration == _set_data_iteration) {
                            this.image[i] = undefined;
                        }
                    },
                    attempts: retry_attempts + 1,
                    timeout: retry_timeout,
                });
                this.image[i] = loader.image;
            }
            const w_data = this.model.properties.w.units == "data";
            const h_data = this.model.properties.h.units == "data";
            const n = this.data_size;
            const xs = new types_1.ScreenArray(w_data ? 2 * n : n);
            const ys = new types_1.ScreenArray(h_data ? 2 * n : n);
            this.anchor = resolve.anchor(this.model.anchor);
            const { x: x_anchor, y: y_anchor } = this.anchor;
            function x0x1(x, w) {
                const x0 = x - x_anchor * w;
                return [x0, x0 + w];
            }
            function y0y1(y, h) {
                const y0 = y + y_anchor * h;
                return [y0, y0 - h];
            }
            // if the width/height are in screen units, don't try to include them in bounds
            if (w_data) {
                for (let i = 0; i < n; i++) {
                    [xs[i], xs[n + i]] = x0x1(this._x[i], this.w.get(i));
                }
            }
            else
                xs.set(this._x, 0);
            if (h_data) {
                for (let i = 0; i < n; i++) {
                    [ys[i], ys[n + i]] = y0y1(this._y[i], this.h.get(i));
                }
            }
            else
                ys.set(this._y, 0);
            const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
            this._bounds_rect = { x0, x1, y0, y1 };
        }
        has_finished() {
            return super.has_finished() && this._images_rendered;
        }
        _map_data() {
            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);
        }
        _render(ctx, indices, data) {
            const { image, sx, sy, sw, sh, angle, global_alpha } = data !== null && data !== void 0 ? data : this;
            // TODO (bev): take actual border width into account when clipping
            const { frame } = this.renderer.plot_view;
            const { left, top, width, height } = frame.bbox;
            ctx.beginPath();
            ctx.rect(left + 1, top + 1, width - 2, height - 2);
            ctx.clip();
            let finished = true;
            for (const i of indices) {
                const img = image[i];
                if (!isFinite(sx[i] + sy[i] + angle.get(i) + global_alpha.get(i)) || img == null)
                    continue;
                if (!img.complete) {
                    finished = false;
                    continue;
                }
                else if (img.naturalWidth == 0 && img.naturalHeight == 0) { // dumb way of detecting broken images
                    continue;
                }
                this._render_image(ctx, i, img, sx, sy, sw, sh, angle, global_alpha);
            }
            if (finished && !this._images_rendered) {
                this._images_rendered = true;
                this.notify_finished();
            }
        }
        _render_image(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;
            const sw_i = sw[i];
            const sh_i = sh[i];
            const { anchor } = this;
            const dx_i = anchor.x * sw_i;
            const dy_i = anchor.y * sh_i;
            const sx_i = sx[i] - dx_i;
            const sy_i = sy[i] - dy_i;
            const angle_i = angle.get(i);
            const alpha_i = alpha.get(i);
            ctx.save();
            ctx.globalAlpha = alpha_i;
            const sw2 = sw_i / 2;
            const sh2 = sh_i / 2;
            if (angle_i != 0) {
                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();
            this.rendered.set(i);
        }
        bounds() {
            return this._bounds_rect;
        }
    }
    exports.ImageURLView = ImageURLView;
    ImageURLView.__name__ = "ImageURLView";
    class ImageURL extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImageURL = ImageURL;
    _a = ImageURL;
    ImageURL.__name__ = "ImageURL";
    (() => {
        _a.prototype.default_view = ImageURLView;
        _a.define(({ Boolean, Int }) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const object_1 = require(9) /* ../../core/util/object */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const selection_1 = require(103) /* ../selections/selection */;
    class MultiLineView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { MultiLineGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(545) /* ./webgl/multi_line */));
            return MultiLineGL;
        }
        _project_data() {
            projections_1.inplace.project_xy(this._xs.array, this._ys.array);
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this._xs.get(i);
                const ysi = this._ys.get(i);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xsi, ysi);
                index.add_rect(x0, y0, x1, y1);
            }
        }
        _render(ctx, indices, data) {
            const { sxs, sys } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx = sxs.get(i);
                const sy = sys.get(i);
                const n = Math.min(sx.length, sy.length);
                let move = true;
                ctx.beginPath();
                for (let j = 0; j < n; j++) {
                    const sx_j = sx[j];
                    const 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();
            }
        }
        _hit_point(geometry) {
            const point = { x: geometry.sx, y: geometry.sy };
            let shortest = 9999;
            const hits = new Map();
            for (let i = 0, end = this.sxs.length; i < end; i++) {
                const threshold = Math.max(2, this.line_width.get(i) / 2);
                const sxsi = this.sxs.get(i);
                const sysi = this.sys.get(i);
                let points = null;
                for (let j = 0, endj = sxsi.length - 1; j < endj; j++) {
                    const p0 = { x: sxsi[j], y: sysi[j] };
                    const p1 = { x: sxsi[j + 1], y: sysi[j + 1] };
                    const 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: [...hits.keys()],
                multiline_indices: (0, object_1.to_object)(hits), // TODO: remove to_object()
            });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let val;
            let vs;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                vs = this._ys;
            }
            else {
                val = this.renderer.xscale.invert(sx);
                vs = this._xs;
            }
            const hits = new Map();
            for (let i = 0, end = vs.length; i < end; i++) {
                const vsi = vs.get(i);
                const points = [];
                for (let 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: [...hits.keys()],
                multiline_indices: (0, object_1.to_object)(hits), // TODO: remove to_object()
            });
        }
        get_interpolation_hit(i, point_i, geometry) {
            const xsi = this._xs.get(i);
            const ysi = this._ys.get(i);
            const x2 = xsi[point_i];
            const y2 = ysi[point_i];
            const x3 = xsi[point_i + 1];
            const y3 = ysi[point_i + 1];
            return (0, utils_1.line_interpolation)(this.renderer, geometry, x2, y2, x3, y3);
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.MultiLineView = MultiLineView;
    MultiLineView.__name__ = "MultiLineView";
    class MultiLine extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MultiLine = MultiLine;
    _a = MultiLine;
    MultiLine.__name__ = "MultiLine";
    (() => {
        _a.prototype.default_view = MultiLineView;
        _a.define(({}) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const spatial_1 = require(207) /* ../../core/util/spatial */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const arrayable_2 = require(13) /* ../../core/util/arrayable */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(103) /* ../selections/selection */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class MultiPolygonsView extends glyph_1.GlyphView {
        _project_data() {
            // TODO
        }
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this._xs[i];
                const ysi = this._ys[i];
                if (xsi.length == 0 || ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                let xi0 = +Infinity;
                let xi1 = -Infinity;
                let yi0 = +Infinity;
                let yi1 = -Infinity;
                for (let j = 0, endj = xsi.length; j < endj; j++) {
                    const xsij = xsi[j][0]; // do not use holes
                    const ysij = ysi[j][0]; // do not use holes
                    if (xsij.length != 0 && ysij.length != 0) {
                        const [xij0, xij1, yij0, yij1] = (0, arrayable_1.minmax2)(xsij, ysij);
                        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();
        }
        _index_hole_data() {
            const { min, max } = Math;
            const { data_size } = this;
            const index = new spatial_1.SpatialIndex(data_size);
            for (let i = 0; i < data_size; i++) {
                const xsi = this._xs[i];
                const ysi = this._ys[i];
                if (xsi.length == 0 || ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                let xi0 = +Infinity;
                let xi1 = -Infinity;
                let yi0 = +Infinity;
                let yi1 = -Infinity;
                for (let j = 0, endj = xsi.length; j < endj; j++) {
                    const xsij = xsi[j];
                    const ysij = ysi[j];
                    if (xsij.length > 1 && ysij.length > 1) {
                        for (let k = 1, endk = xsij.length; k < endk; k++) {
                            const [xij0, xij1, yij0, yij1] = (0, arrayable_1.minmax2)(xsij[k], ysij[k]);
                            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;
        }
        _mask_data() {
            const { x_range, y_range } = this.renderer.plot_view.frame;
            return this.index.indices({
                x0: x_range.min, x1: x_range.max,
                y0: y_range.min, y1: y_range.max,
            });
        }
        _render(ctx, indices, data) {
            if (!this.visuals.fill.doit && !this.visuals.line.doit)
                return;
            const { sxs, sys } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                ctx.beginPath();
                const sx_i = sxs[i];
                const sy_i = sys[i];
                const nj = Math.min(sx_i.length, sy_i.length);
                for (let j = 0; j < nj; j++) {
                    const sx_ij = sx_i[j];
                    const sy_ij = sy_i[j];
                    const nk = Math.min(sx_ij.length, sy_ij.length);
                    for (let k = 0; k < nk; k++) {
                        const sx_ijk = sx_ij[k];
                        const sy_ijk = sy_ij[k];
                        const nl = Math.min(sx_ijk.length, sy_ijk.length);
                        for (let l = 0; l < nl; l++) {
                            const sx_ijkl = sx_ijk[l];
                            const 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);
            }
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys, greedy = false } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                const sxs_i = this.sxs[i];
                const sys_i = this.sys[i];
                let hit = !greedy;
                const nj = sxs_i.length;
                for (let j = 0; j < nj; j++) {
                    const sxs_ij0 = sxs_i[j][0];
                    const sys_ij0 = sys_i[j][0];
                    const nk = sxs_ij0.length;
                    for (let k = 0; k < nk; k++) {
                        const sxs_ij0k = sxs_ij0[k];
                        const sys_ij0k = sys_ij0[k];
                        if (!hittest.point_in_poly(sxs_ij0k, sys_ij0k, sxs, sys)) {
                            if (!greedy) {
                                hit = false;
                                break;
                            }
                        }
                        else {
                            if (greedy) {
                                hit = true;
                                break;
                            }
                        }
                    }
                    if (!greedy) {
                        if (!hit) {
                            break;
                        }
                    }
                    else {
                        if (hit) {
                            break;
                        }
                    }
                }
                if (hit) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1, greedy } = geometry;
            const sxs = [sx0, sx1, sx1, sx0];
            const sys = [sy0, sy0, sy1, sy1];
            return this._hit_poly({ type: "poly", sx: sxs, sy: sys, greedy });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const hole_candidates = this._hole_index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const index of candidates) {
                const sxs = this.sxs[index];
                const sys = this.sys[index];
                for (let j = 0, endj = sxs.length; j < endj; j++) {
                    const 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) {
                            let in_a_hole = false;
                            for (let k = 1; k < nk; k++) {
                                const sxs_k = sxs[j][k];
                                const 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);
                            }
                        }
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _get_snap_coord(array) {
            return (0, arrayable_2.sum)(array) / array.length;
        }
        scenterxy(i, sx, sy) {
            if (this.sxs[i].length == 1) {
                // We don't have discontinuous objects so we're ok
                const scx = this._get_snap_coord(this.sxs[i][0][0]);
                const 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
                const sxs = this.sxs[i];
                const sys = this.sys[i];
                for (let j = 0, end = sxs.length; j < end; j++) {
                    if (hittest.point_in_poly(sx, sy, sxs[j][0], sys[j][0])) {
                        const scx = this._get_snap_coord(sxs[j][0]);
                        const scy = this._get_snap_coord(sys[j][0]);
                        return [scx, scy];
                    }
                }
            }
            (0, assert_1.unreachable)();
        }
        map_data() {
            const n_i = this._xs.length;
            this.sxs = new Array(n_i);
            this.sys = new Array(n_i);
            for (let i = 0; i < n_i; i++) {
                const n_j = this._xs[i].length;
                this.sxs[i] = new Array(n_j);
                this.sys[i] = new Array(n_j);
                for (let j = 0; j < n_j; j++) {
                    const n_k = this._xs[i][j].length;
                    this.sxs[i][j] = new Array(n_k);
                    this.sys[i][j] = new Array(n_k);
                    for (let k = 0; k < n_k; k++) {
                        const [sx, sy] = this.renderer.coordinates.map_to_screen(this._xs[i][j][k], this._ys[i][j][k]);
                        this.sxs[i][j][k] = sx;
                        this.sys[i][j][k] = sy;
                    }
                }
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.MultiPolygonsView = MultiPolygonsView;
    MultiPolygonsView.__name__ = "MultiPolygonsView";
    class MultiPolygons extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MultiPolygons = MultiPolygons;
    _a = MultiPolygons;
    MultiPolygons.__name__ = "MultiPolygons";
    (() => {
        _a.prototype.default_view = MultiPolygonsView;
        _a.define(({}) => ({
            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/patches.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(103) /* ../selections/selection */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    class PatchesView extends glyph_1.GlyphView {
        _project_data() {
            projections_1.inplace.project_xy(this._xs.array, this._ys.array);
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this._xs.get(i);
                const ysi = this._ys.get(i);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xsi, ysi);
                index.add_rect(x0, y0, x1, y1);
            }
        }
        _mask_data() {
            const { x_range, y_range } = this.renderer.plot_view.frame;
            return this.index.indices({
                x0: x_range.min, x1: x_range.max,
                y0: y_range.min, y1: y_range.max,
            });
        }
        _render(ctx, indices, data) {
            const { sxs, sys } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sxs.get(i);
                const sy_i = sys.get(i);
                let move = true;
                ctx.beginPath();
                const n = Math.min(sx_i.length, sy_i.length);
                for (let j = 0; j < n; j++) {
                    const sx_j = sx_i[j];
                    const 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);
            }
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys, greedy = false } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                const sxs_i = this.sxs.get(i);
                const sys_i = this.sys.get(i);
                const n = sxs_i.length;
                if (n == 0) {
                    continue;
                }
                let hit = !greedy;
                for (let j = 0; j < n; j++) {
                    const sx = sxs_i[j];
                    const sy = sys_i[j];
                    if (!hittest.point_in_poly(sx, sy, sxs, sys)) {
                        if (!greedy) {
                            hit = false;
                            break;
                        }
                    }
                    else {
                        if (greedy) {
                            hit = true;
                            break;
                        }
                    }
                }
                if (hit) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1, greedy } = geometry;
            const sxs = [sx0, sx1, sx1, sx0];
            const sys = [sy0, sy0, sy1, sy1];
            return this._hit_poly({ type: "poly", sx: sxs, sy: sys, greedy });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const index of candidates) {
                const sxsi = this.sxs.get(index);
                const sysi = this.sys.get(index);
                const n = sxsi.length;
                for (let k = 0, j = 0;; j++) {
                    if (isNaN(sxsi[j]) || j == n) {
                        const sxsi_kj = sxsi.subarray(k, j);
                        const 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;
                }
            }
            return new selection_1.Selection({ indices });
        }
        _get_snap_coord(array) {
            return (0, arrayable_1.sum)(array) / array.length;
        }
        scenterxy(i, sx, sy) {
            const sxsi = this.sxs.get(i);
            const sysi = this.sys.get(i);
            const n = sxsi.length;
            let has_nan = false;
            for (let k = 0, j = 0;; j++) {
                const this_nan = isNaN(sxsi[j]);
                has_nan = has_nan || this_nan;
                if (j == n && !has_nan) {
                    const scx = this._get_snap_coord(sxsi);
                    const scy = this._get_snap_coord(sysi);
                    return [scx, scy];
                }
                if (this_nan || j == n) {
                    const sxsi_kj = sxsi.subarray(k, j);
                    const sysi_kj = sysi.subarray(k, j);
                    if (hittest.point_in_poly(sx, sy, sxsi_kj, sysi_kj)) {
                        const scx = this._get_snap_coord(sxsi_kj);
                        const scy = this._get_snap_coord(sysi_kj);
                        return [scx, scy];
                    }
                    k = j + 1;
                }
                if (j == n)
                    break;
            }
            (0, assert_1.unreachable)();
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.PatchesView = PatchesView;
    PatchesView.__name__ = "PatchesView";
    class Patches extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Patches = Patches;
    _a = Patches;
    Patches.__name__ = "Patches";
    (() => {
        _a.prototype.default_view = PatchesView;
        _a.define(({}) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(331) /* ./lrtb */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class QuadView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sleft[i] / 2 + this.sright[i] / 2;
            const scy = this.stop[i] / 2 + this.sbottom[i] / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const l = this._left[i];
            const r = this._right[i];
            const t = this._top[i];
            const b = this._bottom[i];
            return [l, r, t, b];
        }
    }
    exports.QuadView = QuadView;
    QuadView.__name__ = "QuadView";
    class Quad extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Quad = Quad;
    _a = Quad;
    Quad.__name__ = "Quad";
    (() => {
        _a.prototype.default_view = QuadView;
        _a.define(({}) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const algorithms_1 = require(329) /* ../../core/util/algorithms */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class QuadraticView extends glyph_1.GlyphView {
        _project_data() {
            projections_1.inplace.project_xy(this._x0, this._y0);
            projections_1.inplace.project_xy(this._x1, this._y1);
        }
        _index_data(index) {
            const { _x0, _x1, _y0, _y1, _cx, _cy, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = _x0[i];
                const x1_i = _x1[i];
                const y0_i = _y0[i];
                const y1_i = _y1[i];
                const cx_i = _cx[i];
                const cy_i = _cy[i];
                if (!isFinite(x0_i + x1_i + y0_i + y1_i + cx_i + cy_i))
                    index.add_empty();
                else {
                    const { x0, y0, x1, y1 } = (0, algorithms_1.qbb)(x0_i, y0_i, cx_i, cy_i, x1_i, y1_i);
                    index.add_rect(x0, y0, x1, y1);
                }
            }
        }
        _render(ctx, indices, data) {
            if (!this.visuals.line.doit)
                return;
            const { sx0, sy0, sx1, sy1, scx, scy } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                const scx_i = scx[i];
                const 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.apply(ctx, i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.QuadraticView = QuadraticView;
    QuadraticView.__name__ = "QuadraticView";
    class Quadratic extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Quadratic = Quadratic;
    _a = Quadratic;
    Quadratic.__name__ = "Quadratic";
    (() => {
        _a.prototype.default_view = QuadraticView;
        _a.define(({}) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const utils_1 = require(211) /* ./utils */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class RayView extends xy_glyph_1.XYGlyphView {
        _map_data() {
            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);
            const { width, height } = this.renderer.plot_view.frame.bbox;
            const inf_len = 2 * (width + height);
            const { slength } = this;
            for (let i = 0, end = slength.length; i < end; i++) {
                if (slength[i] == 0)
                    slength[i] = inf_len;
            }
        }
        _render(ctx, indices, data) {
            if (!this.visuals.line.doit)
                return;
            const { sx, sy, slength, angle } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const angle_i = angle.get(i);
                const 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.apply(ctx, i);
                ctx.rotate(-angle_i);
                ctx.translate(-sx_i, -sy_i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.RayView = RayView;
    RayView.__name__ = "RayView";
    class Ray extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ray = Ray;
    _a = Ray;
    Ray.__name__ = "Ray";
    (() => {
        _a.prototype.default_view = RayView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(({}) => ({
            length: [p.DistanceSpec, 0],
            angle: [p.AngleSpec, 0],
        }));
    })();
},
/* models/glyphs/rect.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const center_rotatable_1 = require(334) /* ./center_rotatable */;
    const utils_1 = require(211) /* ./utils */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const selection_1 = require(103) /* ../selections/selection */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const affine_1 = require(155) /* ../../core/util/affine */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(240) /* ../common/resolve */);
    const painting_1 = require(239) /* ../common/painting */;
    const { abs, sqrt } = Math;
    class RectView extends center_rotatable_1.CenterRotatableView {
        async load_glglyph() {
            const { RectGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(547) /* ./webgl/rect */));
            return RectGL;
        }
        _set_data(indices) {
            super._set_data(indices);
            this.border_radius = resolve.border_radius(this.model.border_radius);
        }
        _map_data() {
            const n = this.data_size;
            if (this.model.properties.width.units == "data")
                [this.sw, this.sx0] = this._map_dist_corner_for_data_side_length(this._x, this.width, this.renderer.xscale);
            else {
                this.sw = (0, types_1.to_screen)(this.width);
                this.sx0 = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    this.sx0[i] = this.sx[i] - this.sw[i] / 2;
                }
            }
            if (this.model.properties.height.units == "data")
                [this.sh, this.sy1] = this._map_dist_corner_for_data_side_length(this._y, this.height, this.renderer.yscale);
            else {
                this.sh = (0, types_1.to_screen)(this.height);
                this.sy1 = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    this.sy1[i] = this.sy[i] - this.sh[i] / 2;
                }
            }
            const { sw, sh } = this;
            this.ssemi_diag = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++) {
                const sw_i = sw[i];
                const sh_i = sh[i];
                this.ssemi_diag[i] = sqrt(sw_i ** 2 + sh_i ** 2) / 2;
            }
            const scenter_x = new types_1.ScreenArray(n);
            const scenter_y = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++) {
                scenter_x[i] = this.sx0[i] + this.sw[i] / 2;
                scenter_y[i] = this.sy1[i] + this.sh[i] / 2;
            }
            this.max_x2_ddist = (0, arrayable_1.max)(this._ddist(0, scenter_x, this.ssemi_diag));
            this.max_y2_ddist = (0, arrayable_1.max)(this._ddist(1, scenter_y, this.ssemi_diag));
        }
        _render(ctx, indices, data) {
            const { sx, sy, sx0, sy1, sw, sh, angle, border_radius } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sx0_i = sx0[i];
                const sy1_i = sy1[i];
                const sw_i = sw[i];
                const sh_i = sh[i];
                const 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 != 0) {
                    ctx.translate(sx_i, sy_i);
                    ctx.rotate(angle_i);
                    const box = new bbox_1.BBox({ x: -sw_i / 2, y: -sh_i / 2, width: sw_i, height: sh_i });
                    (0, painting_1.round_rect)(ctx, box, border_radius);
                    ctx.rotate(-angle_i);
                    ctx.translate(-sx_i, -sy_i);
                }
                else {
                    const box = new bbox_1.BBox({ x: sx0_i, y: sy1_i, width: sw_i, height: sh_i });
                    (0, painting_1.round_rect)(ctx, box, border_radius);
                }
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_rect(geometry) {
            return this._hit_rect_against_index(geometry);
        }
        _hit_point(geometry) {
            const hit_xy = { x: geometry.sx, y: geometry.sy };
            const x = this.renderer.xscale.invert(hit_xy.x);
            const y = this.renderer.yscale.invert(hit_xy.y);
            const candidates = this.index.indices({
                x0: x - this.max_x2_ddist,
                x1: x + this.max_x2_ddist,
                y0: y - this.max_y2_ddist,
                y1: y + this.max_y2_ddist,
            });
            const { sx, sy, sx0, sy1, sw, sh, angle } = this;
            const indices = [];
            for (const i of candidates) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sx0_i = sx0[i];
                const sy1_i = sy1[i];
                const sw_i = sw[i];
                const sh_i = sh[i];
                const angle_i = angle.get(i);
                const hit_rxy = (0, affine_1.rotate_around)(hit_xy, { x: sx_i, y: sy_i }, -angle_i);
                const x = hit_rxy.x - sx0_i;
                const y = hit_rxy.y - sy1_i;
                // TODO: consider round corners
                if (0 <= x && x <= sw_i && 0 <= y && y <= sh_i) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _map_dist_corner_for_data_side_length(coord, side_length, scale) {
            const n = coord.length;
            const pt0 = new Float64Array(n);
            const pt1 = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                const coord_i = coord[i];
                const 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;
            }
            const spt0 = scale.v_compute(pt0);
            const spt1 = scale.v_compute(pt1);
            const sside_length = this.sdist(scale, pt0, side_length, "edge", this.model.dilate);
            let spt_corner = spt0;
            for (let i = 0; i < n; i++) {
                const spt0i = spt0[i];
                const spt1i = spt1[i];
                if (!isNaN(spt0i + spt1i) && spt0i != spt1i) {
                    spt_corner = spt0i < spt1i ? spt0 : spt1;
                    break;
                }
            }
            return [sside_length, spt_corner];
        }
        _ddist(dim, spts, spans) {
            const ArrayType = (0, types_1.infer_type)(spts, spans);
            const scale = dim == 0 ? this.renderer.xscale : this.renderer.yscale;
            const spt0 = spts;
            const m = spt0.length;
            const spt1 = new ArrayType(m);
            for (let i = 0; i < m; i++)
                spt1[i] = spt0[i] + spans[i];
            const pt0 = scale.v_invert(spt0);
            const pt1 = scale.v_invert(spt1);
            const n = pt0.length;
            const ddist = new ArrayType(n);
            for (let i = 0; i < n; i++)
                ddist[i] = abs(pt1[i] - pt0[i]);
            return ddist;
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.RectView = RectView;
    RectView.__name__ = "RectView";
    class Rect extends center_rotatable_1.CenterRotatable {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Rect = Rect;
    _a = Rect;
    Rect.__name__ = "Rect";
    (() => {
        _a.prototype.default_view = RectView;
        _a.define(({ Boolean }) => ({
            border_radius: [kinds_1.BorderRadius, 0],
            dilate: [Boolean, false],
        }));
    })();
},
/* models/glyphs/scatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const marker_1 = require(352) /* ./marker */;
    const defs_1 = require(353) /* ./defs */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class ScatterView extends marker_1.MarkerView {
        async load_glglyph() {
            const { MultiMarkerGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(546) /* ./webgl/multi_marker */));
            return MultiMarkerGL;
        }
        _render(ctx, indices, data) {
            const { sx, sy, size, angle, marker } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const size_i = size.get(i);
                const angle_i = angle.get(i);
                const marker_i = marker.get(i);
                if (!isFinite(sx_i + sy_i + size_i + angle_i) || marker_i == null)
                    continue;
                const r = size_i / 2;
                ctx.beginPath();
                ctx.translate(sx_i, sy_i);
                if (angle_i != 0) {
                    ctx.rotate(angle_i);
                }
                defs_1.marker_funcs[marker_i](ctx, i, r, this.visuals);
                if (angle_i != 0) {
                    ctx.rotate(-angle_i);
                }
                ctx.translate(-sx_i, -sy_i);
            }
        }
        draw_legend_for_index(ctx, { x0, x1, y0, y1 }, index) {
            const n = index + 1;
            const marker = this.marker.get(index);
            const args = Object.assign(Object.assign({}, this._get_legend_args({ x0, x1, y0, y1 }, index)), { marker: new p.UniformScalar(marker, n) });
            this._render(ctx, [index], args);
        }
    }
    exports.ScatterView = ScatterView;
    ScatterView.__name__ = "ScatterView";
    class Scatter extends marker_1.Marker {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Scatter = Scatter;
    _a = Scatter;
    Scatter.__name__ = "Scatter";
    (() => {
        _a.prototype.default_view = ScatterView;
        _a.define(() => ({
            marker: [p.MarkerSpec, { value: "circle" }],
        }));
    })();
},
/* models/glyphs/marker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const uniforms = tslib_1.__importStar(require(39) /* ../../core/uniforms */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const selection_1 = require(103) /* ../selections/selection */;
    class MarkerView extends xy_glyph_1.XYGlyphView {
        _render(ctx, indices, data) {
            const { sx, sy, size, angle } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const size_i = size.get(i);
                const angle_i = angle.get(i);
                if (!isFinite(sx_i + sy_i + size_i + angle_i))
                    continue;
                const r = size_i / 2;
                ctx.beginPath();
                ctx.translate(sx_i, sy_i);
                if (angle_i != 0) {
                    ctx.rotate(angle_i);
                }
                this._render_one(ctx, i, r, this.visuals);
                if (angle_i != 0) {
                    ctx.rotate(-angle_i);
                }
                ctx.translate(-sx_i, -sy_i);
            }
        }
        _mask_data() {
            // dilate the inner screen region by max_size and map back to data space for use in spatial query
            const { x_target, y_target } = this.renderer.plot_view.frame;
            const hr = x_target.widen(this.max_size).map((x) => this.renderer.xscale.invert(x));
            const vr = y_target.widen(this.max_size).map((y) => this.renderer.yscale.invert(y));
            return this.index.indices({
                x0: hr.start, x1: hr.end,
                y0: vr.start, y1: vr.end,
            });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const { max_size } = this;
            const { hit_dilation } = this.model;
            const sx0 = sx - max_size * hit_dilation;
            const sx1 = sx + max_size * hit_dilation;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const sy0 = sy - max_size * hit_dilation;
            const sy1 = sy + max_size * hit_dilation;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            for (const i of candidates) {
                const 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);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            const bounds = this.bounds();
            const half_size = this.max_size / 2;
            const [x0, x1, y0, y1] = (() => {
                if (geometry.direction == "h") {
                    const { y0, y1 } = bounds;
                    const sx0 = sx - half_size;
                    const sx1 = sx + half_size;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    return [x0, x1, y0, y1];
                }
                else {
                    const { x0, x1 } = bounds;
                    const sy0 = sy - half_size;
                    const sy1 = sy + half_size;
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sxs, sys)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _set_data(indices) {
            super._set_data(indices);
            const max_size = uniforms.max(this.size);
            this._configure("max_size", { value: max_size });
        }
        _get_legend_args({ x0, x1, y0, y1 }, index) {
            // using objects like this seems a little wonky, since the keys are coerced to strings, but it works
            const n = index + 1;
            const sx = new Array(n);
            const sy = new Array(n);
            sx[index] = (x0 + x1) / 2;
            sy[index] = (y0 + y1) / 2;
            const vsize = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.4;
            const size = new p.UniformScalar(vsize, n);
            const angle = new p.UniformScalar(0, n); // don't attempt to match glyph angle
            return { sx, sy, size, angle };
        }
        draw_legend_for_index(ctx, { x0, x1, y0, y1 }, index) {
            const args = this._get_legend_args({ x0, x1, y0, y1 }, index);
            this._render(ctx, [index], args); // XXX
        }
    }
    exports.MarkerView = MarkerView;
    MarkerView.__name__ = "MarkerView";
    class Marker extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Marker = Marker;
    _a = Marker;
    Marker.__name__ = "Marker";
    (() => {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({ Number }) => ({
            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();
    const SQ3 = Math.sqrt(3);
    const SQ5 = Math.sqrt(5);
    const c36 = (SQ5 + 1) / 4;
    const s36 = Math.sqrt((5 - SQ5) / 8);
    const c72 = (SQ5 - 1) / 4;
    const 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) {
        const h = r * SQ3;
        const 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) {
        const r2 = r / 2;
        const 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) {
        const 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) {
        const h = r * SQ3;
        const 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);
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    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);
        _one_y(ctx, r);
        visuals.line.apply(ctx, i);
    }
    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);
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    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);
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r / 1.5, 0);
        ctx.lineTo(r / 1.5, 0);
        visuals.line.apply(ctx, i);
    }
    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) {
        const a = 3 * r / 8;
        const b = r;
        const xs = [a, a, b, b, a, a, -a, -a, -b, -b, -a, -a];
        const ys = [b, a, a, -a, -a, -b, -b, -a, -a, a, a, b];
        ctx.beginPath();
        for (let 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) {
        const 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) {
        const 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) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function square_dot(ctx, i, r, visuals) {
        square(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function square_x(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        ctx.moveTo(-r, r);
        ctx.lineTo(r, -r);
        ctx.moveTo(-r, -r);
        ctx.lineTo(r, r);
        visuals.line.apply(ctx, i);
    }
    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) {
        const h = r * SQ3;
        const a = h / 3;
        const 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,
        circle,
        circle_cross,
        circle_dot,
        circle_y,
        circle_x,
        cross,
        diamond,
        diamond_dot,
        diamond_cross,
        dot,
        hex,
        hex_dot,
        inverted_triangle,
        plus,
        square,
        square_cross,
        square_dot,
        square_pin,
        square_x,
        star,
        star_dot,
        triangle,
        triangle_dot,
        triangle_pin,
        dash,
        x,
        y,
    };
},
/* models/glyphs/segment.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const hittest = tslib_1.__importStar(require(212) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    const math_1 = require(11) /* ../../core/util/math */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const selection_1 = require(103) /* ../selections/selection */;
    class SegmentView extends glyph_1.GlyphView {
        _project_data() {
            projections_1.inplace.project_xy(this._x0, this._y0);
            projections_1.inplace.project_xy(this._x1, this._y1);
        }
        _index_data(index) {
            const { min, max } = Math;
            const { _x0, _x1, _y0, _y1, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x0 = _x0[i];
                const x1 = _x1[i];
                const y0 = _y0[i];
                const y1 = _y1[i];
                index.add_rect(min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1));
            }
        }
        _render(ctx, indices, data) {
            if (!this.visuals.line.doit)
                return;
            const { sx0, sy0, sx1, sy1 } = data !== null && data !== void 0 ? data : this;
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i))
                    continue;
                this._render_decorations(ctx, i, sx0_i, sy0_i, sx1_i, sy1_i);
                ctx.beginPath();
                ctx.moveTo(sx0_i, sy0_i);
                ctx.lineTo(sx1_i, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _render_decorations(ctx, i, sx0, sy0, sx1, sy1) {
            const { PI } = Math;
            const angle = (0, math_1.atan2)([sx0, sy0], [sx1, sy1]) + PI / 2;
            for (const decoration of this.decorations.values()) {
                ctx.save();
                if (decoration.model.node == "start") {
                    ctx.translate(sx0, sy0);
                    ctx.rotate(angle + PI);
                }
                else if (decoration.model.node == "end") {
                    ctx.translate(sx1, sy1);
                    ctx.rotate(angle);
                }
                decoration.marking.render(ctx, i);
                ctx.restore();
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const point = { x: sx, y: sy };
            const lw_voffset = 2; // FIXME: Use maximum of segments line_width/2 instead of magic constant 2
            const [x0, x1] = this.renderer.xscale.r_invert(sx - lw_voffset, sx + lw_voffset);
            const [y0, y1] = this.renderer.yscale.r_invert(sy - lw_voffset, sy + lw_voffset);
            const candidates = this.index.indices({ x0, y0, x1, y1 });
            const indices = [];
            for (const i of candidates) {
                const threshold2 = Math.max(2, this.line_width.get(i) / 2) ** 2;
                const p0 = { x: this.sx0[i], y: this.sy0[i] };
                const p1 = { x: this.sx1[i], y: this.sy1[i] };
                const dist2 = hittest.dist_to_segment_squared(point, p0, p1);
                if (dist2 < threshold2) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const [hr, vr] = this.renderer.plot_view.frame.bbox.ranges;
            const { sx, sy } = geometry;
            let v0;
            let v1;
            let val;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                [v0, v1] = [this._y0, this._y1];
            }
            else {
                val = this.renderer.xscale.invert(sx);
                [v0, v1] = [this._x0, this._x1];
            }
            const indices = [];
            const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end);
            const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end);
            const candidates = this.index.indices({ x0, y0, x1, y1 });
            for (const i of candidates) {
                if ((v0[i] <= val && val <= v1[i]) || (v1[i] <= val && val <= v0[i]))
                    indices.push(i);
                const 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);
                        }
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        scenterxy(i) {
            const scx = this.sx0[i] / 2 + this.sx1[i] / 2;
            const scy = this.sy0[i] / 2 + this.sy1[i] / 2;
            return [scx, scy];
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.SegmentView = SegmentView;
    SegmentView.__name__ = "SegmentView";
    class Segment extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Segment = Segment;
    _a = Segment;
    Segment.__name__ = "Segment";
    (() => {
        _a.prototype.default_view = SegmentView;
        _a.define(({}) => ({
            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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const interpolation_1 = require(356) /* ../../core/util/interpolation */;
    class SplineView extends xy_glyph_1.XYGlyphView {
        _set_data() {
            const { tension, closed } = this.model;
            [this._xt, this._yt] = (0, interpolation_1.catmullrom_spline)(this._x, this._y, 20, tension, closed);
        }
        _map_data() {
            const { x_scale, y_scale } = this.renderer.coordinates;
            this.sxt = x_scale.v_compute(this._xt);
            this.syt = y_scale.v_compute(this._yt);
        }
        _render(ctx, _indices, data) {
            const { sxt: sx, syt: sy } = data !== null && data !== void 0 ? data : this;
            let move = true;
            ctx.beginPath();
            const n = sx.length;
            for (let j = 0; j < n; j++) {
                const sx_i = sx[j];
                const 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();
        }
    }
    exports.SplineView = SplineView;
    SplineView.__name__ = "SplineView";
    class Spline extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Spline = Spline;
    _a = Spline;
    Spline.__name__ = "Spline";
    (() => {
        _a.prototype.default_view = SplineView;
        _a.mixins(mixins.LineScalar);
        _a.define(({ Boolean, Number }) => ({
            tension: [Number, 0.5],
            closed: [Boolean, false],
        }));
    })();
},
/* core/util/interpolation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(24) /* ../types */;
    const assert_1 = require(12) /* ./assert */;
    function catmullrom_spline(x, y, T = 10, tension = 0.5, closed = false) {
        /** Centripetal Catmull-Rom spline. */
        (0, assert_1.assert)(x.length == y.length);
        const n = x.length;
        const N = closed ? n + 1 : n;
        const ArrayType = (0, types_1.infer_type)(x, y);
        const xx = new ArrayType(N + 2);
        const 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];
        }
        const basis = new ArrayType(4 * (T + 1));
        for (let j = 0, k = 0; j <= T; j++) {
            const t = j / T;
            const t_2 = t ** 2;
            const 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
        }
        const xt = new ArrayType((N - 1) * (T + 1));
        const yt = new ArrayType((N - 1) * (T + 1));
        for (let i = 1, k = 0; i < N; i++) {
            const t0x = (xx[i + 1] - xx[i - 1]) * tension;
            const t0y = (yy[i + 1] - yy[i - 1]) * tension;
            const t1x = (xx[i + 2] - xx[i]) * tension;
            const t1y = (yy[i + 2] - yy[i]) * tension;
            for (let j = 0; j <= 4 * T; k++) {
                const h00 = basis[j++];
                const h01 = basis[j++];
                const h10 = basis[j++];
                const 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) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const utils_1 = require(211) /* ./utils */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class StepView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { StepGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(548) /* ./webgl/step */));
            return StepGL;
        }
        _render(ctx, indices, data) {
            const npoints = indices.length;
            if (npoints < 2)
                return;
            const { sx, sy } = data !== null && data !== void 0 ? data : this;
            const mode = this.model.mode;
            this.visuals.line.set_value(ctx);
            let drawing = false;
            let prev_finite = false;
            const i = indices[0];
            let is_finite = isFinite(sx[i] + sy[i]);
            if (mode == "center")
                drawing = this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]);
            for (const i of indices) {
                const next_finite = isFinite(sx[i + 1] + sy[i + 1]);
                switch (mode) {
                    case "before":
                        drawing = this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]);
                        if (i < sx.length - 1)
                            drawing = this._render_xy(ctx, drawing, is_finite && next_finite ? sx[i] : NaN, sy[i + 1]);
                        break;
                    case "after":
                        drawing = this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]);
                        if (i < sx.length - 1)
                            drawing = this._render_xy(ctx, drawing, is_finite && next_finite ? sx[i + 1] : NaN, sy[i]);
                        break;
                    case "center":
                        if (is_finite && next_finite) {
                            const midx = (sx[i] + sx[i + 1]) / 2;
                            drawing = this._render_xy(ctx, drawing, midx, sy[i]);
                            drawing = this._render_xy(ctx, drawing, midx, sy[i + 1]);
                        }
                        else {
                            if (prev_finite)
                                drawing = this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]);
                            drawing = this._render_xy(ctx, drawing, next_finite ? sx[i + 1] : NaN, sy[i + 1]);
                        }
                        break;
                    default:
                        (0, assert_1.unreachable)();
                }
                prev_finite = is_finite;
                is_finite = next_finite;
            }
            if (drawing) {
                const i = indices[npoints - 1];
                if (this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]))
                    ctx.stroke();
            }
        }
        _render_xy(ctx, drawing, x, y) {
            if (isFinite(x + y)) {
                if (drawing) {
                    // Continue with current line
                    ctx.lineTo(x, y);
                }
                else {
                    // Start new line
                    ctx.beginPath();
                    ctx.moveTo(x, y);
                    drawing = true;
                }
            }
            else if (drawing) {
                // End current line
                ctx.stroke();
                drawing = false;
            }
            return drawing;
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_line_scalar_legend)(this.visuals, ctx, bbox);
        }
    }
    exports.StepView = StepView;
    StepView.__name__ = "StepView";
    class Step extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Step = Step;
    _a = Step;
    Step.__name__ = "Step";
    (() => {
        _a.prototype.default_view = StepView;
        _a.mixins(mixins.LineScalar);
        _a.define(() => ({
            mode: [enums_1.StepMode, "before"],
        }));
    })();
},
/* models/glyphs/text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const uniforms_1 = require(39) /* ../../core/uniforms */;
    const selection_1 = require(103) /* ../selections/selection */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const affine_1 = require(155) /* ../../core/util/affine */;
    const graphics_1 = require(153) /* ../../core/graphics */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(240) /* ../common/resolve */);
    const painting_1 = require(239) /* ../common/painting */;
    class TextAnchorSpec extends p.DataSpec {
    }
    TextAnchorSpec.__name__ = "TextAnchorSpec";
    class TextView extends xy_glyph_1.XYGlyphView {
        after_visuals() {
            var _b, _c;
            super.after_visuals();
            const { text } = (_b = this.base) !== null && _b !== void 0 ? _b : this;
            this.labels = Array.from(text, (value) => {
                if (value == null) {
                    return null;
                }
                else {
                    const text = `${value}`; // TODO: guarantee correct types earlier
                    return new graphics_1.TextBox({ text });
                }
            });
            const n = this.data_size;
            const { anchor } = (_c = this.base) !== null && _c !== void 0 ? _c : this;
            const { padding, border_radius } = this.model;
            const { text_align, text_baseline } = this.visuals.text;
            if (anchor.is_Scalar() && anchor.value != "auto") {
                this.anchor_ = new uniforms_1.UniformScalar(resolve.anchor(anchor.value), n);
            }
            else if (anchor.is_Scalar() && text_align.is_Scalar() && text_baseline.is_Scalar()) {
                this.anchor_ = new uniforms_1.UniformScalar(resolve.text_anchor(anchor.value, text_align.value, text_baseline.value), n);
            }
            else {
                const anchors = new Array(n);
                for (let i = 0; i < n; i++) {
                    const anchor_i = anchor.get(i);
                    const align_i = text_align.get(i);
                    const baseline_i = text_baseline.get(i);
                    anchors[i] = resolve.text_anchor(anchor_i, align_i, baseline_i);
                }
                this.anchor_ = new uniforms_1.UniformVector(anchors);
            }
            this.padding = resolve.padding(padding);
            this.border_radius = resolve.border_radius(border_radius);
            this.swidth = new Float32Array(n);
            this.sheight = new Float32Array(n);
            const { left, right, top, bottom } = this.padding;
            for (const [label, i] of (0, iterator_1.enumerate)(this.labels)) {
                if (label == null)
                    continue;
                label.visuals = this.visuals.text.values(i);
                label.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "top" };
                label.align = "auto";
                const size = label.size();
                const width = left + size.width + right;
                const height = top + size.height + bottom;
                this.swidth[i] = width;
                this.sheight[i] = height;
            }
        }
        _render(ctx, indices, data) {
            const { sx, sy, x_offset, y_offset, angle } = data !== null && data !== void 0 ? data : this;
            const { text, background_fill, background_hatch, border_line } = this.visuals;
            const { anchor_: anchor, border_radius, padding } = this;
            const { labels, swidth, sheight } = this;
            for (const i of indices) {
                const sx_i = sx[i] + x_offset.get(i);
                const sy_i = sy[i] + y_offset.get(i);
                const angle_i = angle.get(i);
                const label_i = labels[i];
                if (!isFinite(sx_i + sy_i + angle_i) || label_i == null)
                    continue;
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const anchor_i = anchor.get(i);
                const dx_i = anchor_i.x * swidth_i;
                const dy_i = anchor_i.y * sheight_i;
                ctx.translate(sx_i, sy_i);
                ctx.rotate(angle_i);
                ctx.translate(-dx_i, -dy_i);
                if (background_fill.v_doit(i) || background_hatch.v_doit(i) || border_line.v_doit(i)) {
                    ctx.beginPath();
                    const bbox = new bbox_1.BBox({ x: 0, y: 0, width: swidth_i, height: sheight_i });
                    (0, painting_1.round_rect)(ctx, bbox, border_radius);
                    background_fill.apply(ctx, i);
                    background_hatch.apply(ctx, i);
                    border_line.apply(ctx, i);
                }
                if (text.v_doit(i)) {
                    const { left, top } = padding;
                    ctx.translate(left, top);
                    label_i.paint(ctx);
                    ctx.translate(-left, -top);
                }
                ctx.translate(dx_i, dy_i);
                ctx.rotate(-angle_i);
                ctx.translate(-sx_i, -sy_i);
            }
        }
        _hit_point(geometry) {
            const hit_xy = { x: geometry.sx, y: geometry.sy };
            const { sx, sy, x_offset, y_offset, angle, labels } = this;
            const { anchor_: anchor } = this;
            const { swidth, sheight } = this;
            const n = this.data_size;
            const indices = [];
            for (let i = 0; i < n; i++) {
                const sx_i = sx[i] + x_offset.get(i);
                const sy_i = sy[i] + y_offset.get(i);
                const angle_i = angle.get(i);
                const label_i = labels[i];
                if (!isFinite(sx_i + sy_i + angle_i) || label_i == null)
                    continue;
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const anchor_i = anchor.get(i);
                const dx_i = anchor_i.x * swidth_i;
                const dy_i = anchor_i.y * sheight_i;
                const { x, y } = (0, affine_1.rotate_around)(hit_xy, { x: sx_i, y: sy_i }, -angle_i);
                const left = sx_i - dx_i;
                const top = sy_i - dy_i;
                const right = left + swidth_i;
                const bottom = top + sheight_i;
                // TODO: consider round corners
                if (left <= x && x <= right && top <= y && y <= bottom) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        rect_i(i) {
            const { sx, sy, x_offset, y_offset, angle, labels } = this;
            const { anchor_: anchor } = this;
            const { swidth, sheight } = this;
            const sx_i = sx[i] + x_offset.get(i);
            const sy_i = sy[i] + y_offset.get(i);
            const angle_i = angle.get(i);
            const label_i = labels[i];
            if (!isFinite(sx_i + sy_i + angle_i) || label_i == null) {
                return {
                    p0: { x: NaN, y: NaN },
                    p1: { x: NaN, y: NaN },
                    p2: { x: NaN, y: NaN },
                    p3: { x: NaN, y: NaN },
                };
            }
            const swidth_i = swidth[i];
            const sheight_i = sheight[i];
            const anchor_i = anchor.get(i);
            const dx_i = anchor_i.x * swidth_i;
            const dy_i = anchor_i.y * sheight_i;
            const bbox = new bbox_1.BBox({
                x: sx_i - dx_i,
                y: sy_i - dy_i,
                width: swidth_i,
                height: sheight_i,
            });
            const { rect } = bbox;
            if (angle_i == 0) {
                return rect;
            }
            else {
                const tr = new affine_1.AffineTransform();
                tr.rotate_around(sx_i, sy_i, angle_i);
                return tr.apply_rect(rect);
            }
        }
        scenterxy(i) {
            const { p0, p1, p2, p3 } = this.rect_i(i);
            const sx = (p0.x + p1.x + p2.x + p3.x) / 4;
            const sy = (p0.y + p1.y + p2.y + p3.y) / 4;
            return [sx, sy];
        }
    }
    exports.TextView = TextView;
    TextView.__name__ = "TextView";
    class Text extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Text = Text;
    _a = Text;
    Text.__name__ = "Text";
    (() => {
        _a.prototype.default_view = TextView;
        _a.mixins([
            mixins.TextVector,
            ["border_", mixins.LineVector],
            ["background_", mixins.FillVector],
            ["background_", mixins.HatchVector],
        ]);
        _a.define(() => ({
            text: [p.NullStringSpec, { field: "text" }],
            angle: [p.AngleSpec, 0],
            x_offset: [p.NumberSpec, 0],
            y_offset: [p.NumberSpec, 0],
            anchor: [TextAnchorSpec, { value: "auto" }],
            padding: [kinds_1.Padding, 0],
            border_radius: [kinds_1.BorderRadius, 0],
        }));
        _a.override({
            border_line_color: null,
            background_fill_color: null,
            background_hatch_color: null,
        });
    })();
},
/* models/glyphs/vbar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(331) /* ./lrtb */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class VBarView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.stop[i] + this.sbottom[i]) / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const half_width_i = this.width.get(i) / 2;
            const x_i = this._x[i];
            const top_i = this._top[i];
            const bottom_i = this._bottom[i];
            const l = x_i - half_width_i;
            const r = x_i + half_width_i;
            const t = Math.max(top_i, bottom_i);
            const b = Math.min(top_i, bottom_i);
            return [l, r, t, b];
        }
        _map_data() {
            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);
            const n = this.sx.length;
            this.sleft = new types_1.ScreenArray(n);
            this.sright = new types_1.ScreenArray(n);
            for (let 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();
        }
    }
    exports.VBarView = VBarView;
    VBarView.__name__ = "VBarView";
    class VBar extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VBar = VBar;
    _a = VBar;
    VBar.__name__ = "VBar";
    (() => {
        _a.prototype.default_view = VBarView;
        _a.define(({}) => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            bottom: [p.YCoordinateSpec, { value: 0 }],
            width: [p.NumberSpec, { value: 1 }],
            top: [p.YCoordinateSpec, { field: "top" }],
        }));
    })();
},
/* models/glyphs/vspan.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const selection_1 = require(103) /* ../selections/selection */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const uniforms = tslib_1.__importStar(require(39) /* ../../core/uniforms */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const { abs, max } = Math;
    const UNUSED = 0;
    class VSpanView extends glyph_1.GlyphView {
        after_visuals() {
            super.after_visuals();
            this.max_line_width = uniforms.max(this.line_width);
        }
        _index_data(index) {
            for (const x_i of this._x) {
                index.add_point(x_i, UNUSED);
            }
        }
        _bounds(bounds) {
            const { x0, x1 } = bounds;
            return { x0, x1, y0: NaN, y1: NaN };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            this.sx = (0, arrayable_1.map)(this.sx, (xi) => round(xi));
        }
        scenterxy(i) {
            const { vcenter } = this.renderer.plot_view.frame.bbox;
            return [this.sx[i], vcenter];
        }
        _render(ctx, indices, data) {
            const { sx } = data !== null && data !== void 0 ? data : this;
            const { top, bottom } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sx_i = sx[i];
                if (!isFinite(sx_i))
                    continue;
                ctx.beginPath();
                ctx.moveTo(sx_i, top);
                ctx.lineTo(sx_i, bottom);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sx0, sx1) {
            const { max_line_width } = this;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0 - max_line_width, (sx1 !== null && sx1 !== void 0 ? sx1 : sx0) + max_line_width);
            return this.index.indices({ x0, x1, y0: 0, y1: 0 });
        }
        _find_spans(candidates, fn) {
            const { sx, line_width } = this;
            const indices = [];
            for (const i of candidates) {
                const sx_i = sx[i];
                const line_width_i = line_width.get(i);
                if (fn(sx_i, line_width_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sx: gsx } = geometry;
            const candidates = this._get_candidates(gsx);
            const indices = this._find_spans(candidates, (sx, line_width) => {
                return abs(sx - gsx) <= max(line_width, 2 /*px*/);
            });
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "h") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sx: gsx } = geometry;
                    const candidates = this._get_candidates(gsx);
                    return this._find_spans(candidates, (sx, line_width) => {
                        return abs(sx - gsx) <= max(line_width / 2, 2 /*px*/);
                    });
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sx0: gsx0, sx1: gsx1 } = geometry;
                const candidates = this._get_candidates(gsx0, gsx1);
                return this._find_spans(candidates, (sx, line_width) => {
                    return gsx0 - line_width / 2 <= sx && sx <= gsx1 + line_width / 2;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.VSpanView = VSpanView;
    VSpanView.__name__ = "VSpanView";
    class VSpan extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VSpan = VSpan;
    _a = VSpan;
    VSpan.__name__ = "VSpan";
    (() => {
        _a.prototype.default_view = VSpanView;
        _a.mixins([property_mixins_1.LineVector]);
        _a.define(() => ({
            x: [p.XCoordinateSpec, { field: "x" }],
        }));
    })();
},
/* models/glyphs/vstrip.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(205) /* ./glyph */;
    const utils_1 = require(211) /* ./utils */;
    const selection_1 = require(103) /* ../selections/selection */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const iter = tslib_1.__importStar(require(34) /* ../../core/util/iterator */);
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const UNUSED = 0;
    class VStripView extends glyph_1.GlyphView {
        async lazy_initialize() {
            await super.lazy_initialize();
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null && webgl.regl_wrapper.has_webgl) {
                const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(544) /* ./webgl/lrtb */));
                this.glglyph = new LRTBGL(webgl.regl_wrapper, this);
            }
        }
        get sleft() {
            return this.sx0;
        }
        get sright() {
            return this.sx1;
        }
        get stop() {
            const { top } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const stop = new types_1.ScreenArray(n);
            stop.fill(top);
            return stop;
        }
        get sbottom() {
            const { bottom } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sbottom = new types_1.ScreenArray(n);
            sbottom.fill(bottom);
            return sbottom;
        }
        _set_data(indices) {
            super._set_data(indices);
            const { abs } = Math;
            const { max, map, zip } = iter;
            const { _x0, _x1 } = this;
            this.max_width = max(map(zip(_x0, _x1), ([x0_i, x1_i]) => abs(x0_i - x1_i)));
        }
        _index_data(index) {
            const { _x0, _x1, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = _x0[i];
                const x1_i = _x1[i];
                index.add_rect(x0_i, UNUSED, x1_i, UNUSED);
            }
        }
        _bounds(bounds) {
            const { x0, x1 } = bounds;
            return { x0, x1, y0: NaN, y1: NaN };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            this.sx0 = (0, arrayable_1.map)(this.sx0, (xi) => round(xi));
            this.sx1 = (0, arrayable_1.map)(this.sx1, (xi) => round(xi));
        }
        scenterxy(i) {
            const { vcenter } = this.renderer.plot_view.frame.bbox;
            return [(this.sx0[i] + this.sx1[i]) / 2, vcenter];
        }
        _render(ctx, indices, data) {
            const { sx0, sx1 } = data !== null && data !== void 0 ? data : this;
            const { top, bottom, height } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sx1_i = sx1[i];
                if (!isFinite(sx0_i + sx1_i))
                    continue;
                ctx.beginPath();
                ctx.rect(sx0_i, top, sx1_i - sx0_i, height);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                ctx.beginPath();
                ctx.moveTo(sx0_i, top);
                ctx.lineTo(sx0_i, bottom);
                ctx.moveTo(sx1_i, top);
                ctx.lineTo(sx1_i, bottom);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sx0, sx1) {
            const { max_width } = this;
            const [dx0, dx1] = this.renderer.xscale.r_invert(sx0, sx1 !== null && sx1 !== void 0 ? sx1 : sx0);
            const x0 = dx0 - max_width;
            const x1 = dx1 + max_width;
            return this.index.indices({ x0, x1, y0: 0, y1: 0 });
        }
        _find_strips(candidates, fn) {
            function contains(sx0, sx1) {
                return sx0 <= sx1 ? fn(sx0, sx1) : fn(sx1, sx0);
            }
            const { sx0, sx1 } = this;
            const indices = [];
            for (const i of candidates) {
                const sx0_i = sx0[i];
                const sx1_i = sx1[i];
                if (contains(sx0_i, sx1_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sx } = geometry;
            const candidates = this._get_candidates(sx);
            const indices = this._find_strips(candidates, (sx0, sx1) => sx0 <= sx && sx <= sx1);
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "h") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sx } = geometry;
                    const candidates = this._get_candidates(sx);
                    return this._find_strips(candidates, (sx0, sx1) => sx0 <= sx && sx <= sx1);
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sx0: gsx0, sx1: gsx1 } = geometry;
                const candidates = this._get_candidates(gsx0, gsx1);
                return this._find_strips(candidates, (sx0, sx1) => {
                    return gsx0 <= sx0 && sx0 <= gsx1 && gsx0 <= sx1 && sx1 <= gsx1;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.VStripView = VStripView;
    VStripView.__name__ = "VStripView";
    class VStrip extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VStrip = VStrip;
    _a = VStrip;
    VStrip.__name__ = "VStrip";
    (() => {
        _a.prototype.default_view = VStripView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(() => ({
            x0: [p.XCoordinateSpec, { field: "x0" }],
            x1: [p.XCoordinateSpec, { field: "x1" }],
        }));
    })();
},
/* models/glyphs/wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(204) /* ./xy_glyph */;
    const utils_1 = require(211) /* ./utils */;
    const property_mixins_1 = require(78) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(11) /* ../../core/util/math */;
    const selection_1 = require(103) /* ../selections/selection */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class WedgeView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { WedgeGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(549) /* ./webgl/wedge */));
            return WedgeGL;
        }
        _map_data() {
            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);
            this.max_sradius = (0, arrayable_1.max)(this.sradius);
        }
        _render(ctx, indices, data) {
            const { sx, sy, sradius, start_angle, end_angle } = data !== null && data !== void 0 ? data : this;
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                const start_angle_i = start_angle.get(i);
                const 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);
            }
        }
        _hit_point(geometry) {
            let dist, sx0, sx1, sy0, sy1;
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            // check diameter first
            sx0 = sx - this.max_sradius;
            sx1 = sx + this.max_sradius;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            sy0 = sy - this.max_sradius;
            sy1 = sy + this.max_sradius;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const r2 = this.sradius[i] ** 2;
                [sx0, sx1] = this.renderer.xscale.r_compute(x, this._x[i]);
                [sy0, sy1] = this.renderer.yscale.r_compute(y, this._y[i]);
                dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= r2) {
                    candidates.push(i);
                }
            }
            const anticlock = this.model.direction == "anticlock";
            const indices = [];
            for (const i of candidates) {
                // NOTE: minus the angle because JS uses non-mathy convention for angles
                const angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
                const is_full_circle = Math.abs(this.start_angle.get(i) - this.end_angle.get(i)) >= 2 * Math.PI;
                if (is_full_circle || (0, math_1.angle_between)(-angle, -this.start_angle.get(i), -this.end_angle.get(i), anticlock)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy(i) {
            const r = this.sradius[i] / 2;
            const a = (this.start_angle.get(i) + this.end_angle.get(i)) / 2;
            const scx = this.sx[i] + r * Math.cos(a);
            const scy = this.sy[i] + r * Math.sin(a);
            return [scx, scy];
        }
    }
    exports.WedgeView = WedgeView;
    WedgeView.__name__ = "WedgeView";
    class Wedge extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Wedge = Wedge;
    _a = Wedge;
    Wedge.__name__ = "Wedge";
    (() => {
        _a.prototype.default_view = WedgeView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({}) => ({
            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/graphics/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var decoration_1 = require(210) /* ./decoration */;
    __esExport("Decoration", decoration_1.Decoration);
    var marking_1 = require(142) /* ./marking */;
    __esExport("Marking", marking_1.Marking);
},
/* models/graphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(365) /* ./graph_hit_test_policy */, exports);
    tslib_1.__exportStar(require(366) /* ./layout_provider */, exports);
    tslib_1.__exportStar(require(367) /* ./static_layout_provider */, exports);
},
/* models/graphs/graph_hit_test_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const selection_1 = require(103) /* ../selections/selection */;
    class GraphHitTestPolicy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        _hit_test(geometry, graph_view, renderer_view) {
            if (!graph_view.model.visible)
                return null;
            const 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);
        }
    }
    exports.GraphHitTestPolicy = GraphHitTestPolicy;
    GraphHitTestPolicy.__name__ = "GraphHitTestPolicy";
    class EdgesOnly extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.edge_view);
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            const 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();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            const { edge_renderer } = graph_view.model;
            const 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 }]);
            return !edge_inspection.is_empty();
        }
    }
    exports.EdgesOnly = EdgesOnly;
    EdgesOnly.__name__ = "EdgesOnly";
    class NodesOnly extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            const 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();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            const { node_renderer } = graph_view.model;
            const 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 }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesOnly = NodesOnly;
    NodesOnly.__name__ = "NodesOnly";
    class NodesAndLinkedEdges extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        get_linked_edges(node_source, edge_source, mode) {
            const node_indices = (() => {
                switch (mode) {
                    case "selection": return (0, arrayable_1.map)(node_source.selected.indices, (i) => node_source.data.index[i]);
                    case "inspection": return (0, arrayable_1.map)(node_source.inspected.indices, (i) => node_source.data.index[i]);
                }
            })();
            const edge_indices = [];
            for (let 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);
            }
            const linked_edges = new selection_1.Selection();
            for (const i of edge_indices) {
                linked_edges.multiline_indices[i] = [0]; //currently only supports 2-element multilines, so this is all of it
            }
            linked_edges.indices = edge_indices;
            return linked_edges;
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            const node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            const edge_selection = graph.edge_renderer.data_source.selected;
            const 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();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            const 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 });
            const edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model);
            const 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 }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesAndLinkedEdges = NodesAndLinkedEdges;
    NodesAndLinkedEdges.__name__ = "NodesAndLinkedEdges";
    class EdgesAndLinkedNodes extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.edge_view);
        }
        get_linked_nodes(node_source, edge_source, mode) {
            const edge_indices = (() => {
                switch (mode) {
                    case "selection": return edge_source.selected.indices;
                    case "inspection": return edge_source.inspected.indices;
                }
            })();
            const nodes = [];
            for (const i of edge_indices) {
                nodes.push(edge_source.data.start[i]);
                nodes.push(edge_source.data.end[i]);
            }
            const node_indices = (0, array_1.uniq)(nodes).map((i) => (0, arrayable_1.index_of)(node_source.data.index, i));
            return new selection_1.Selection({ indices: node_indices });
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            const edge_selection = graph.edge_renderer.data_source.selected;
            edge_selection.update(hit_test_result, final, mode);
            const node_selection = graph.node_renderer.data_source.selected;
            const 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();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            const 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 });
            const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            const 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 }]);
            return !edge_inspection.is_empty();
        }
    }
    exports.EdgesAndLinkedNodes = EdgesAndLinkedNodes;
    EdgesAndLinkedNodes.__name__ = "EdgesAndLinkedNodes";
    class NodesAndAdjacentNodes extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        get_adjacent_nodes(node_source, edge_source, mode) {
            const selected_node_indices = (() => {
                switch (mode) {
                    case "selection": return (0, arrayable_1.map)(node_source.selected.indices, (i) => node_source.data.index[i]);
                    case "inspection": return (0, arrayable_1.map)(node_source.inspected.indices, (i) => node_source.data.index[i]);
                }
            })();
            const adjacent_nodes = [];
            const selected_nodes = [];
            for (let i = 0; i < edge_source.data.start.length; i++) {
                if ((0, array_1.contains)(selected_node_indices, edge_source.data.start[i])) {
                    adjacent_nodes.push(edge_source.data.end[i]);
                    selected_nodes.push(edge_source.data.start[i]);
                }
                if ((0, array_1.contains)(selected_node_indices, edge_source.data.end[i])) {
                    adjacent_nodes.push(edge_source.data.start[i]);
                    selected_nodes.push(edge_source.data.end[i]);
                }
            }
            for (let i = 0; i < selected_nodes.length; i++) {
                adjacent_nodes.push(selected_nodes[i]);
            }
            const adjacent_node_indices = (0, array_1.uniq)(adjacent_nodes).map((i) => (0, arrayable_1.index_of)(node_source.data.index, i));
            return new selection_1.Selection({ indices: adjacent_node_indices });
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null)
                return false;
            const node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            const adjacent_nodes_selection = this.get_adjacent_nodes(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            if (!adjacent_nodes_selection.is_empty())
                node_selection.update(adjacent_nodes_selection, final, mode);
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null)
                return false;
            const 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 });
            const adjacent_nodes_inspection = this.get_adjacent_nodes(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            if (!adjacent_nodes_inspection.is_empty()) {
                node_inspection.update(adjacent_nodes_inspection, final, mode);
                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 }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesAndAdjacentNodes = NodesAndAdjacentNodes;
    NodesAndAdjacentNodes.__name__ = "NodesAndAdjacentNodes";
},
/* models/graphs/layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const coordinate_transform_1 = require(313) /* ../expressions/coordinate_transform */;
    class LayoutProvider extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get node_coordinates() {
            return new NodeCoordinates({ layout: this });
        }
        get edge_coordinates() {
            return new EdgeCoordinates({ layout: this });
        }
    }
    exports.LayoutProvider = LayoutProvider;
    LayoutProvider.__name__ = "LayoutProvider";
    class GraphCoordinates extends coordinate_transform_1.CoordinateTransform {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GraphCoordinates = GraphCoordinates;
    _a = GraphCoordinates;
    GraphCoordinates.__name__ = "GraphCoordinates";
    (() => {
        _a.define(({ Ref }) => ({
            layout: [Ref(LayoutProvider)],
        }));
    })();
    class NodeCoordinates extends GraphCoordinates {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const [x, y] = this.layout.get_node_coordinates(source);
            return { x, y };
        }
    }
    exports.NodeCoordinates = NodeCoordinates;
    NodeCoordinates.__name__ = "NodeCoordinates";
    class EdgeCoordinates extends GraphCoordinates {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const [x, y] = this.layout.get_edge_coordinates(source);
            return { x, y };
        }
    }
    exports.EdgeCoordinates = EdgeCoordinates;
    EdgeCoordinates.__name__ = "EdgeCoordinates";
},
/* models/graphs/static_layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_provider_1 = require(366) /* ./layout_provider */;
    const object_1 = require(9) /* ../../core/util/object */;
    class StaticLayoutProvider extends layout_provider_1.LayoutProvider {
        constructor(attrs) {
            super(attrs);
        }
        get_node_coordinates(node_source) {
            var _b, _c;
            const data = new object_1.Dict(node_source.data);
            const index = (_b = data.get("index")) !== null && _b !== void 0 ? _b : [];
            const n = index.length;
            const xs = new Float64Array(n);
            const ys = new Float64Array(n);
            const { graph_layout } = this;
            for (let i = 0; i < n; i++) {
                const j = index[i];
                const [x, y] = (_c = graph_layout.get(j)) !== null && _c !== void 0 ? _c : [NaN, NaN];
                xs[i] = x;
                ys[i] = y;
            }
            return [xs, ys];
        }
        get_edge_coordinates(edge_source) {
            var _b, _c, _d, _e;
            const data = new object_1.Dict(edge_source.data);
            const starts = (_b = data.get("start")) !== null && _b !== void 0 ? _b : [];
            const ends = (_c = data.get("end")) !== null && _c !== void 0 ? _c : [];
            const n = Math.min(starts.length, ends.length);
            const xs = [];
            const ys = [];
            const edge_xs = data.get("xs");
            const edge_ys = data.get("ys");
            const has_paths = edge_xs != null && edge_ys != null;
            const { graph_layout } = this;
            for (let i = 0; i < n; i++) {
                const in_layout = graph_layout.has(starts[i]) && graph_layout.has(ends[i]);
                if (has_paths && in_layout) {
                    xs.push(edge_xs[i]);
                    ys.push(edge_ys[i]);
                }
                else {
                    const start = (_d = graph_layout.get(starts[i])) !== null && _d !== void 0 ? _d : [NaN, NaN];
                    const end = (_e = graph_layout.get(ends[i])) !== null && _e !== void 0 ? _e : [NaN, NaN];
                    xs.push([start[0], end[0]]);
                    ys.push([start[1], end[1]]);
                }
            }
            return [xs, ys];
        }
    }
    exports.StaticLayoutProvider = StaticLayoutProvider;
    _a = StaticLayoutProvider;
    StaticLayoutProvider.__name__ = "StaticLayoutProvider";
    (() => {
        _a.define(({ Number, Int, Arrayable, Map }) => ({
            graph_layout: [Map(Int, Arrayable(Number)), new globalThis.Map()], // TODO: length == 2
        }));
    })();
},
/* models/grids/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var grid_1 = require(369) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
},
/* models/grids/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const axes_1 = require(160) /* ../axes */;
    const guide_renderer_1 = require(162) /* ../renderers/guide_renderer */;
    const ticker_1 = require(163) /* ../tickers/ticker */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const types_1 = require(8) /* ../../core/util/types */;
    class GridView extends guide_renderer_1.GuideRendererView {
        _render() {
            const ctx = this.layer.ctx;
            ctx.save();
            this._draw_regions(ctx);
            this._draw_minor_grids(ctx);
            this._draw_grids(ctx);
            ctx.restore();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
        }
        _draw_regions(ctx) {
            if (!this.visuals.band_fill.doit && !this.visuals.band_hatch.doit)
                return;
            const [xs, ys] = this.grid_coords("major", false);
            for (let i = 0; i < xs.length - 1; i++) {
                if (i % 2 != 1)
                    continue;
                const [sx0, sy0] = this.coordinates.map_to_screen(xs[i], ys[i]);
                const [sx1, sy1] = this.coordinates.map_to_screen(xs[i + 1], ys[i + 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);
            }
        }
        _draw_grids(ctx) {
            if (!this.visuals.grid_line.doit)
                return;
            const [xs, ys] = this.grid_coords("major");
            this._draw_grid_helper(ctx, this.visuals.grid_line, xs, ys);
        }
        _draw_minor_grids(ctx) {
            if (!this.visuals.minor_grid_line.doit)
                return;
            const [xs, ys] = this.grid_coords("minor");
            this._draw_grid_helper(ctx, this.visuals.minor_grid_line, xs, ys);
        }
        _draw_grid_helper(ctx, visuals, xs, ys) {
            visuals.set_value(ctx);
            ctx.beginPath();
            for (let i = 0; i < xs.length; i++) {
                const [sx, sy] = this.coordinates.map_to_screen(xs[i], ys[i]);
                ctx.moveTo(Math.round(sx[0]), Math.round(sy[0]));
                for (let i = 1; i < sx.length; i++) {
                    ctx.lineTo(Math.round(sx[i]), Math.round(sy[i]));
                }
            }
            ctx.stroke();
        }
        // {{{ TODO: state
        ranges() {
            const i = this.model.dimension;
            const j = 1 - i;
            const { ranges } = this.coordinates;
            return [ranges[i], ranges[j]];
        }
        computed_bounds() {
            const [range] = this.ranges();
            const user_bounds = this.model.bounds;
            const range_bounds = [range.min, range.max];
            let start;
            let 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 {
                [start, end] = range_bounds;
                for (const axis_view of this.plot_view.axis_views) {
                    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) {
                        [start, end] = axis_view.computed_bounds;
                    }
                }
            }
            return [start, end];
        }
        grid_coords(location, exclude_ends = true) {
            const i = this.model.dimension;
            const j = 1 - i;
            const [range, cross_range] = this.ranges();
            const [start, end] = (() => {
                const [start, end] = this.computed_bounds();
                return [Math.min(start, end), Math.max(start, end)];
            })();
            const 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.
            const ticker = this.model.get_ticker();
            if (ticker == null) {
                return coords;
            }
            const ticks = ticker.get_ticks(start, end, range, cross_range.min)[location];
            const min = range.min;
            const max = range.max;
            const [cmin, cmax] = (() => {
                const { cross_bounds } = this.model;
                if (cross_bounds == "auto")
                    return [cross_range.min, cross_range.max];
                else
                    return cross_bounds;
            })();
            if (!exclude_ends) {
                if (ticks[0] != min)
                    ticks.splice(0, 0, min);
                if (ticks[ticks.length - 1] != max)
                    ticks.push(max);
            }
            for (let ii = 0; ii < ticks.length; ii++) {
                if ((ticks[ii] == min || ticks[ii] == max) && exclude_ends)
                    continue;
                const dim_i = [];
                const dim_j = [];
                const N = 2;
                for (let n = 0; n < N; n++) {
                    const 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;
        }
    }
    exports.GridView = GridView;
    GridView.__name__ = "GridView";
    class Grid extends guide_renderer_1.GuideRenderer {
        constructor(attrs) {
            super(attrs);
        }
        get_ticker() {
            if (this.ticker != null) {
                return this.ticker;
            }
            if (this.axis != null) {
                return this.axis.ticker;
            }
            return null;
        }
    }
    exports.Grid = Grid;
    _a = Grid;
    Grid.__name__ = "Grid";
    (() => {
        _a.prototype.default_view = GridView;
        _a.mixins([
            ["grid_", mixins.Line],
            ["minor_grid_", mixins.Line],
            ["band_", mixins.Fill],
            ["band_", mixins.Hatch],
        ]);
        _a.define(({ Number, Auto, Enum, Ref, Tuple, Or, Nullable }) => ({
            bounds: [Or(Tuple(Number, Number), Auto), "auto"],
            cross_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 column_1 = require(371) /* ./column */;
    __esExport("Column", column_1.Column);
    var flex_box_1 = require(372) /* ./flex_box */;
    __esExport("FlexBox", flex_box_1.FlexBox);
    var grid_box_1 = require(377) /* ./grid_box */;
    __esExport("GridBox", grid_box_1.GridBox);
    var group_box_1 = require(379) /* ./group_box */;
    __esExport("GroupBox", group_box_1.GroupBox);
    var hbox_1 = require(381) /* ./hbox */;
    __esExport("HBox", hbox_1.HBox);
    var layout_dom_1 = require(373) /* ./layout_dom */;
    __esExport("LayoutDOM", layout_dom_1.LayoutDOM);
    var row_1 = require(382) /* ./row */;
    __esExport("Row", row_1.Row);
    var scroll_box_1 = require(383) /* ./scroll_box */;
    __esExport("ScrollBox", scroll_box_1.ScrollBox);
    var spacer_1 = require(384) /* ./spacer */;
    __esExport("Spacer", spacer_1.Spacer);
    var tab_panel_1 = require(385) /* ./tab_panel */;
    __esExport("TabPanel", tab_panel_1.TabPanel);
    var tabs_1 = require(386) /* ./tabs */;
    __esExport("Tabs", tabs_1.Tabs);
    var vbox_1 = require(388) /* ./vbox */;
    __esExport("VBox", vbox_1.VBox);
},
/* models/layouts/column.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const flex_box_1 = require(372) /* ./flex_box */;
    class ColumnView extends flex_box_1.FlexBoxView {
        constructor() {
            super(...arguments);
            this._direction = "column";
        }
    }
    exports.ColumnView = ColumnView;
    ColumnView.__name__ = "ColumnView";
    class Column extends flex_box_1.FlexBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Column = Column;
    _a = Column;
    Column.__name__ = "Column";
    (() => {
        _a.prototype.default_view = ColumnView;
    })();
},
/* models/layouts/flex_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(373) /* ./layout_dom */;
    const alignments_1 = require(376) /* ./alignments */;
    const grid_1 = require(233) /* ../../core/layout/grid */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const dom_1 = require(56) /* ../../core/dom */;
    class FlexBoxView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            const { children } = this.model.properties;
            this.on_change(children, () => this.update_children());
        }
        get child_models() {
            return this.model.children;
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flex" };
        }
        _update_layout() {
            super._update_layout();
            this.style.append(":host", {
                flex_direction: this._direction,
                gap: (0, dom_1.px)(this.model.spacing),
            });
            const layoutable = new grid_1.Container();
            let r0 = 0;
            let c0 = 0;
            for (const view of this.child_views) {
                if (!(view instanceof layout_dom_1.LayoutDOMView))
                    continue;
                const sizing = view.box_sizing();
                const flex = (() => {
                    const policy = this._direction == "row" ? sizing.width_policy : sizing.height_policy;
                    const size = this._direction == "row" ? sizing.width : sizing.height;
                    const basis = size != null ? (0, dom_1.px)(size) : "auto";
                    switch (policy) {
                        case "auto":
                        case "fixed": return `0 0 ${basis}`;
                        case "fit": return "1 1 auto";
                        case "min": return "0 1 auto";
                        case "max": return "1 0 0px";
                    }
                })();
                const align_self = (() => {
                    const policy = this._direction == "row" ? sizing.height_policy : sizing.width_policy;
                    switch (policy) {
                        case "auto":
                        case "fixed":
                        case "fit":
                        case "min": return this._direction == "row" ? sizing.valign : sizing.halign;
                        case "max": return "stretch";
                    }
                })();
                view.style.append(":host", { flex, align_self });
                // undo `width/height: 100%` and let `align-self: strech` do the work
                if (this._direction == "row") {
                    if (sizing.height_policy == "max")
                        view.style.append(":host", { height: "auto" });
                }
                else {
                    if (sizing.width_policy == "max")
                        view.style.append(":host", { width: "auto" });
                }
                if (view.layout != null) {
                    layoutable.add({ r0, c0, r1: r0 + 1, c1: c0 + 1 }, view);
                    if (this._direction == "row")
                        c0 += 1;
                    else
                        r0 += 1;
                }
            }
            if (layoutable.size != 0) {
                this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                this.layout.set_sizing();
            }
            else {
                delete this.layout;
            }
        }
    }
    exports.FlexBoxView = FlexBoxView;
    FlexBoxView.__name__ = "FlexBoxView";
    class FlexBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.FlexBox = FlexBox;
    _a = FlexBox;
    FlexBox.__name__ = "FlexBox";
    (() => {
        _a.define(({ Number, Array, Ref }) => ({
            children: [Array(Ref(ui_element_1.UIElement)), []],
            spacing: [Number, 0],
        }));
    })();
},
/* models/layouts/layout_dom.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const menu_1 = require(374) /* ../menus/menu */;
    const logging_1 = require(19) /* ../../core/logging */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const enums_1 = require(20) /* ../../core/enums */;
    const dom_1 = require(56) /* ../../core/dom */;
    const types_1 = require(8) /* ../../core/util/types */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const layout_1 = require(231) /* ../../core/layout */;
    const defer_1 = require(16) /* ../../core/util/defer */;
    const canvas_1 = require(269) /* ../../core/util/canvas */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class LayoutDOMView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._child_views = new Map();
            this.mouseenter = new signaling_1.Signal(this, "mouseenter");
            this.mouseleave = new signaling_1.Signal(this, "mouseleave");
            this.disabled = new signaling_1.Signal(this, "disabled");
            this._resized = false;
            this._auto_width = "fit-content";
            this._auto_height = "fit-content";
            this._layout_computed = false;
            this._was_built = false;
        }
        get is_layout_root() {
            return this.is_root || !(this.parent instanceof LayoutDOMView);
        }
        _after_resize() {
            this._resized = true;
            super._after_resize();
            if (this.is_layout_root && !this._was_built) {
                // This can happen only in pathological cases primarily in tests.
                logging_1.logger.warn(`${this} wasn't built properly`);
                this.render_to(null);
            }
            else
                this.compute_layout();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this.build_child_views();
        }
        remove() {
            for (const child_view of this.child_views)
                child_view.remove();
            this._child_views.clear();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            this.el.addEventListener("mouseenter", (event) => {
                this.mouseenter.emit(event);
            });
            this.el.addEventListener("mouseleave", (event) => {
                this.mouseleave.emit(event);
            });
            this.el.addEventListener("contextmenu", (event) => {
                if (this.model.context_menu != null) {
                    console.log("context menu");
                    event.preventDefault();
                }
            });
            if (this.parent instanceof LayoutDOMView) {
                this.connect(this.parent.disabled, (disabled) => {
                    this.disabled.emit(disabled || this.model.disabled);
                });
            }
            const p = this.model.properties;
            this.on_change(p.disabled, () => {
                this.disabled.emit(this.model.disabled);
            });
            this.on_change([
                p.css_classes,
                p.stylesheets,
                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.flow_mode, p.sizing_mode,
                p.aspect_ratio,
                p.visible,
            ], () => this.invalidate_layout());
        }
        *children() {
            yield* super.children();
            yield* this.child_views;
        }
        get child_views() {
            // TODO In case of a race condition somewhere between layout, resize and children updates,
            // child_models and _child_views may be temporarily inconsistent, resulting in undefined
            // values. Eventually this shouldn't happen and undefined should be treated as a bug.
            return this.child_models.map((child) => this._child_views.get(child)).filter(types_1.isNotNull);
        }
        get layoutable_views() {
            return this.child_views.filter((c) => c instanceof LayoutDOMView);
        }
        async build_child_views() {
            const { created, removed } = await (0, build_views_1.build_views)(this._child_views, this.child_models, { parent: this });
            for (const view of removed) {
                this._resize_observer.unobserve(view.el);
            }
            for (const view of created) {
                this._resize_observer.observe(view.el, { box: "border-box" });
            }
            return created;
        }
        render() {
            super.render();
            for (const child_view of this.child_views) {
                child_view.render();
                this.shadow_el.appendChild(child_view.el);
                // No after_render() here. See r_after_render().
            }
        }
        _update_children() { }
        async update_children() {
            const created_children = new Set(await this.build_child_views());
            if (created_children.size != 0) {
                for (const child_view of this.child_views) {
                    (0, dom_1.remove)(child_view.el);
                }
                for (const child_view of this.child_views) {
                    this.shadow_el.append(child_view.el);
                    if (created_children.has(child_view)) {
                        child_view.render();
                        if (child_view instanceof LayoutDOMView) {
                            child_view.r_after_render();
                        }
                        else {
                            child_view.after_render();
                        }
                    }
                }
            }
            this._update_children();
            this.invalidate_layout();
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flow" };
        }
        _update_layout() {
            function css_sizing(policy, size, auto_size, margin) {
                switch (policy) {
                    case "auto":
                        return size != null ? (0, dom_1.px)(size) : auto_size;
                    case "fixed":
                        return size != null ? (0, dom_1.px)(size) : "fit-content";
                    case "fit":
                        return "fit-content";
                    case "min":
                        return "min-content";
                    case "max":
                        return margin == null ? "100%" : `calc(100% - ${margin})`;
                }
            }
            function css_display(display) {
                // Convert to legacy values due to limitted browser support.
                const { inner, outer } = display;
                switch (`${inner} ${outer}`) {
                    case "block flow": return "block";
                    case "inline flow": return "inline";
                    case "block flow-root": return "flow-root";
                    case "inline flow-root": return "inline-block";
                    case "block flex": return "flex";
                    case "inline flex": return "inline-flex";
                    case "block grid": return "grid";
                    case "inline grid": return "inline-grid";
                    case "block table": return "table";
                    case "inline table": return "inline-table";
                    default: (0, assert_1.unreachable)();
                }
            }
            function to_css(value) {
                return (0, types_1.isNumber)(value) ? (0, dom_1.px)(value) : `${value.percent}%`;
            }
            const styles = {};
            const display = this._intrinsic_display();
            styles.display = css_display(display);
            const sizing = this.box_sizing();
            const { width_policy, height_policy, width, height, aspect_ratio } = sizing;
            const computed_aspect = (() => {
                if (aspect_ratio == "auto") {
                    if (width != null && height != null)
                        return width / height;
                }
                else if ((0, types_1.isNumber)(aspect_ratio))
                    return aspect_ratio;
                return null;
            })();
            if (aspect_ratio == "auto") {
                if (width != null && height != null)
                    styles.aspect_ratio = `${width} / ${height}`;
                else
                    styles.aspect_ratio = "auto";
            }
            else if ((0, types_1.isNumber)(aspect_ratio))
                styles.aspect_ratio = `${aspect_ratio}`;
            const { margin } = this.model;
            const margins = (() => {
                if (margin != null) {
                    if ((0, types_1.isNumber)(margin)) {
                        styles.margin = (0, dom_1.px)(margin);
                        return { width: (0, dom_1.px)(2 * margin), height: (0, dom_1.px)(2 * margin) };
                    }
                    else if (margin.length == 2) {
                        const [vertical, horizontal] = margin;
                        styles.margin = `${(0, dom_1.px)(vertical)} ${(0, dom_1.px)(horizontal)}`;
                        return { width: (0, dom_1.px)(2 * horizontal), height: (0, dom_1.px)(2 * vertical) };
                    }
                    else {
                        const [top, right, bottom, left] = margin;
                        styles.margin = `${(0, dom_1.px)(top)} ${(0, dom_1.px)(right)} ${(0, dom_1.px)(bottom)} ${(0, dom_1.px)(left)}`;
                        return { width: (0, dom_1.px)(left + right), height: (0, dom_1.px)(top + bottom) };
                    }
                }
                else {
                    return { width: null, height: null };
                }
            })();
            const [css_width, css_height] = (() => {
                const css_width = css_sizing(width_policy, width, this._auto_width, margins.width);
                const css_height = css_sizing(height_policy, height, this._auto_height, margins.height);
                if (aspect_ratio != null) {
                    if (width_policy != height_policy) {
                        if (width_policy == "fixed")
                            return [css_width, "auto"];
                        if (height_policy == "fixed")
                            return ["auto", css_height];
                        if (width_policy == "max")
                            return [css_width, "auto"];
                        if (height_policy == "max")
                            return ["auto", css_height];
                        return ["auto", "auto"];
                    }
                    else {
                        if (width_policy != "fixed" && height_policy != "fixed") {
                            if (computed_aspect != null) {
                                if (computed_aspect >= 1)
                                    return [css_width, "auto"];
                                else
                                    return ["auto", css_height];
                            }
                        }
                    }
                }
                return [css_width, css_height];
            })();
            styles.width = css_width;
            styles.height = css_height;
            const { min_width, max_width } = this.model;
            const { min_height, max_height } = this.model;
            styles.min_width = min_width == null ? "0px" : to_css(min_width);
            styles.min_height = min_height == null ? "0px" : to_css(min_height);
            if (this.is_layout_root) {
                if (max_width != null)
                    styles.max_width = to_css(max_width);
                if (max_height != null)
                    styles.max_height = to_css(max_height);
            }
            else {
                if (max_width != null)
                    styles.max_width = `min(${to_css(max_width)}, 100%)`;
                else if (width_policy != "fixed")
                    styles.max_width = "100%";
                if (max_height != null)
                    styles.max_height = `min(${to_css(max_height)}, 100%)`;
                else if (height_policy != "fixed")
                    styles.max_height = "100%";
            }
            const { resizable } = this.model;
            if (resizable !== false) {
                const resize = (() => {
                    switch (resizable) {
                        case "width": return "horizontal";
                        case "height": return "vertical";
                        case true:
                        case "both": return "both";
                    }
                })();
                styles.resize = resize;
                styles.overflow = "auto";
            }
            this.style.append(":host", styles);
        }
        update_layout() {
            this.update_style();
            for (const child_view of this.layoutable_views) {
                child_view.update_layout();
            }
            this._update_layout();
        }
        get is_managed() {
            return this.parent instanceof LayoutDOMView;
        }
        /**
         * Update CSS layout with computed values from canvas layout.
         * This can be done more frequently than `_update_layout()`.
         */
        _measure_layout() { }
        measure_layout() {
            for (const child_view of this.layoutable_views) {
                child_view.measure_layout();
            }
            this._measure_layout();
        }
        compute_layout() {
            if (this.parent instanceof LayoutDOMView) { // TODO: this.is_managed
                this.parent.compute_layout();
            }
            else {
                this.measure_layout();
                this.update_bbox();
                this._compute_layout();
                this.after_layout();
            }
            this._layout_computed = true;
        }
        _compute_layout() {
            if (this.layout != null) {
                this.layout.compute(this.bbox.size);
                for (const child_view of this.layoutable_views) {
                    if (child_view.layout == null)
                        child_view._compute_layout();
                    else
                        child_view._propagate_layout();
                }
            }
            else {
                for (const child_view of this.layoutable_views) {
                    child_view._compute_layout();
                }
            }
        }
        _propagate_layout() {
            for (const child_view of this.layoutable_views) {
                if (child_view.layout == null) {
                    child_view._compute_layout();
                }
            }
        }
        update_bbox() {
            for (const child_view of this.layoutable_views) {
                child_view.update_bbox();
            }
            const changed = super.update_bbox();
            if (this.layout != null) {
                this.layout.visible = this.is_displayed;
            }
            return changed;
        }
        _after_layout() { }
        after_layout() {
            for (const child_view of this.layoutable_views) {
                child_view.after_layout();
            }
            this._after_layout();
        }
        render_to(element) {
            if (!this.is_layout_root)
                throw new Error(`${this.toString()} is not a root layout`);
            this.render();
            if (element != null)
                element.appendChild(this.el);
            this.r_after_render();
            this._was_built = true;
            this.notify_finished();
        }
        r_after_render() {
            for (const child_view of this.child_views) {
                if (child_view instanceof LayoutDOMView)
                    child_view.r_after_render();
                else
                    child_view.after_render();
            }
            this.after_render();
        }
        after_render() {
            this._after_render();
            if (!this.is_managed) {
                this.invalidate_layout();
            }
            if (!this._has_finished) {
                if (!this.is_displayed) {
                    this.finish();
                }
                else {
                    // In case after_resize() wasn't called (see regression test for issue
                    // #9113), then wait one macro task and consider this view finished.
                    (0, defer_1.defer)().then(() => {
                        if (!this._resized) {
                            this.finish();
                        }
                    });
                }
            }
        }
        async rebuild() {
            await this.build_child_views();
            this.invalidate_render();
        }
        invalidate_layout() {
            // TODO: it would be better and more efficient to do a localized
            // update, but for now this guarantees consistent state of layout.
            if (this.parent instanceof LayoutDOMView) {
                this.parent.invalidate_layout();
            }
            else {
                this.update_layout();
                this.compute_layout();
            }
        }
        invalidate_render() {
            this.render();
            this.invalidate_layout();
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (this.is_layout_root && !this._layout_computed) {
                return false;
            }
            for (const child_view of this.child_views) {
                if (!child_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
        box_sizing() {
            let { width_policy, height_policy, aspect_ratio } = this.model;
            const { sizing_mode } = this.model;
            if (sizing_mode != null) {
                if (sizing_mode == "inherit") {
                    if (this.parent instanceof LayoutDOMView) {
                        const sizing = this.parent.box_sizing();
                        width_policy = sizing.width_policy;
                        height_policy = sizing.height_policy;
                        if (aspect_ratio == null)
                            aspect_ratio = sizing.aspect_ratio;
                    }
                }
                else 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;
                    }
                }
            }
            const [halign, valign] = (() => {
                const { align } = this.model;
                if (align == "auto")
                    return [undefined, undefined];
                else if ((0, types_1.isArray)(align))
                    return align;
                else
                    return [align, align];
            })();
            const { width, height } = this.model;
            return {
                width_policy,
                height_policy,
                width,
                height,
                aspect_ratio,
                halign,
                valign,
            };
        }
        export(type = "auto", hidpi = true) {
            const output_backend = (() => {
                switch (type) {
                    case "auto": // TODO: actually infer the best type
                    case "png": return "canvas";
                    case "svg": return "svg";
                }
            })();
            const composite = new canvas_1.CanvasLayer(output_backend, hidpi);
            const { x, y, width, height } = this.bbox;
            composite.resize(width, height);
            const bg_color = getComputedStyle(this.el).backgroundColor;
            composite.ctx.fillStyle = bg_color;
            composite.ctx.fillRect(x, y, width, height);
            for (const view of this.child_views) {
                const region = view.export(type, hidpi);
                const { x, y } = view.bbox.scale(composite.pixel_ratio);
                composite.ctx.drawImage(region.canvas, x, y);
            }
            return composite;
        }
        serializable_state() {
            return Object.assign(Object.assign({}, super.serializable_state()), { children: this.child_views.map((child) => child.serializable_state()) });
        }
    }
    exports.LayoutDOMView = LayoutDOMView;
    LayoutDOMView.__name__ = "LayoutDOMView";
    class LayoutDOM extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LayoutDOM = LayoutDOM;
    _a = LayoutDOM;
    LayoutDOM.__name__ = "LayoutDOM";
    (() => {
        _a.define((types) => {
            const { Boolean, Number, Auto, Tuple, Or, Null, Nullable, Ref } = types;
            const Number2 = Tuple(Number, Number);
            const 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)), null],
                width_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                height_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                aspect_ratio: [Or(Number, Auto, Null), null],
                flow_mode: [enums_1.FlowMode, "block"],
                sizing_mode: [Nullable(enums_1.SizingMode), null],
                disabled: [Boolean, false],
                align: [Or(enums_1.Align, Tuple(enums_1.Align, enums_1.Align), Auto), "auto"],
                context_menu: [Nullable(Ref(menu_1.Menu)), null],
                resizable: [Or(Boolean, enums_1.Dimensions), false],
            };
        });
    })();
},
/* models/menus/menu.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const menu_item_1 = require(375) /* ./menu_item */;
    const enums_1 = require(20) /* ../../core/enums */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const menus_css_1 = tslib_1.__importStar(require(277) /* ../../styles/menus.css */), menus = menus_css_1;
    class MenuView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this.items = new Map();
        }
        stylesheets() {
            return [...super.stylesheets(), menus_css_1.default];
        }
        *children() {
            yield* super.children();
            yield* this.items.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await (0, build_views_1.build_views)(this.items, this.model.items);
        }
        remove() {
            (0, build_views_1.remove_views)(this.items);
            super.remove();
        }
        render() {
            super.render();
            this.el.classList.add(menus[this.model.orientation]);
            const items = (() => {
                const { items, reversed } = this.model;
                const ordererd = reversed ? (0, iterator_1.reverse)(items) : items;
                return (0, iterator_1.map)(ordererd, (item) => this.items.get(item));
            })();
            for (const item of items) {
                item.render();
                this.shadow_el.appendChild(item.el);
            }
        }
    }
    exports.MenuView = MenuView;
    MenuView.__name__ = "MenuView";
    class Menu extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Menu = Menu;
    _a = Menu;
    Menu.__name__ = "Menu";
    (() => {
        _a.define(({ Boolean, Array, Ref }) => ({
            items: [Array(Ref(menu_item_1.MenuItem)), []],
            reversed: [Boolean, false],
            orientation: [enums_1.Orientation, "vertical"],
        }));
    })();
},
/* models/menus/menu_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const menus_css_1 = tslib_1.__importDefault(require(277) /* ../../styles/menus.css */);
    const icons_css_1 = tslib_1.__importDefault(require(278) /* ../../styles/icons.css */);
    class MenuItemView extends ui_element_1.UIElementView {
        stylesheets() {
            return [...super.stylesheets(), menus_css_1.default, icons_css_1.default];
        }
    }
    exports.MenuItemView = MenuItemView;
    MenuItemView.__name__ = "MenuItemView";
    class MenuItem extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MenuItem = MenuItem;
    MenuItem.__name__ = "MenuItem";
},
/* models/layouts/alignments.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layoutable_1 = require(148) /* ../../core/layout/layoutable */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const { max } = Math;
    class GridAlignmentLayout extends layoutable_1.Layoutable {
        constructor(children) {
            super();
            this.children = children;
        }
        _measure(_viewport) {
            return { width: 0, height: 0 };
        }
        compute(viewport = {}) {
            const { width, height } = viewport;
            (0, assert_1.assert)(width != null && height != null);
            const size_hint = { width, height };
            const outer = new bbox_1.BBox({ left: 0, top: 0, width, height });
            let inner = undefined;
            if (size_hint.inner != null) {
                const { left, top, right, bottom } = size_hint.inner;
                inner = new bbox_1.BBox({ left, top, right: width - right, bottom: height - bottom });
            }
            this.set_geometry(outer, inner);
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            const items = this.children.map((_, child) => {
                const { layout, bbox } = child;
                (0, assert_1.assert)(layout != null);
                const size_hint = layout.measure(bbox);
                return { child, layout, bbox, size_hint };
            });
            const row_extents = Array(items.nrows).fill(null).map(() => ({ top: 0, bottom: 0 }));
            const col_extents = Array(items.ncols).fill(null).map(() => ({ left: 0, right: 0 }));
            items.foreach(({ r0, c0, r1, c1 }, { size_hint }) => {
                const { inner } = size_hint;
                if (inner != null) {
                    col_extents[c0].left = max(col_extents[c0].left, inner.left);
                    col_extents[c1].right = max(col_extents[c1].right, inner.right);
                    row_extents[r0].top = max(row_extents[r0].top, inner.top);
                    row_extents[r1].bottom = max(row_extents[r1].bottom, inner.bottom);
                }
            });
            items.foreach(({ r0, c0, r1, c1 }, { layout, size_hint, bbox }) => {
                const outer_bbox = bbox;
                const inner_bbox = size_hint.inner == null ? undefined : (() => {
                    var _a, _b, _c, _d, _e, _f;
                    const { inner, align } = size_hint;
                    const align_left = (_a = align === null || align === void 0 ? void 0 : align.left) !== null && _a !== void 0 ? _a : true;
                    const align_right = (_b = align === null || align === void 0 ? void 0 : align.right) !== null && _b !== void 0 ? _b : true;
                    const align_top = (_c = align === null || align === void 0 ? void 0 : align.top) !== null && _c !== void 0 ? _c : true;
                    const align_bottom = (_d = align === null || align === void 0 ? void 0 : align.bottom) !== null && _d !== void 0 ? _d : true;
                    const fixed_width = (_e = align === null || align === void 0 ? void 0 : align.fixed_width) !== null && _e !== void 0 ? _e : false;
                    const fixed_height = (_f = align === null || align === void 0 ? void 0 : align.fixed_height) !== null && _f !== void 0 ? _f : false;
                    const { left, right } = (() => {
                        if (fixed_width) {
                            const inner_width = outer_bbox.width - inner.right - inner.left;
                            if (align_left) {
                                const left = col_extents[c0].left;
                                const right = outer_bbox.width - (left + inner_width);
                                return { left, right };
                            }
                            else if (align_right) {
                                const right = col_extents[c1].right;
                                const left = outer_bbox.width - (right + inner_width);
                                return { left, right };
                            }
                            else {
                                const left = inner.left;
                                const right = inner.right;
                                return { left, right };
                            }
                        }
                        else {
                            const left = align_left ? col_extents[c0].left : inner.left;
                            const right = align_right ? col_extents[c1].right : inner.right;
                            return { left, right };
                        }
                    })();
                    const { top, bottom } = (() => {
                        if (fixed_height) {
                            const inner_height = outer_bbox.height - inner.bottom - inner.top;
                            if (align_top) {
                                const top = row_extents[r0].top;
                                const bottom = outer_bbox.height - (top + inner_height);
                                return { top, bottom };
                            }
                            else if (align_bottom) {
                                const bottom = row_extents[r1].bottom;
                                const top = outer_bbox.height - (bottom + inner_height);
                                return { top, bottom };
                            }
                            else {
                                const top = inner.top;
                                const bottom = inner.bottom;
                                return { top, bottom };
                            }
                        }
                        else {
                            const top = align_top ? row_extents[r0].top : inner.top;
                            const bottom = align_bottom ? row_extents[r1].bottom : inner.bottom;
                            return { top, bottom };
                        }
                    })();
                    const { width, height } = outer_bbox;
                    return bbox_1.BBox.from_lrtb({ left, top, right: width - right, bottom: height - bottom });
                })();
                layout.set_geometry(outer_bbox, inner_bbox);
            });
        }
    }
    exports.GridAlignmentLayout = GridAlignmentLayout;
    GridAlignmentLayout.__name__ = "GridAlignmentLayout";
},
/* models/layouts/grid_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const css_grid_box_1 = require(378) /* ./css_grid_box */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    class GridBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, rows, cols } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change([rows, cols], () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children;
        }
        get _rows() {
            return this.model.rows;
        }
        get _cols() {
            return this.model.cols;
        }
    }
    exports.GridBoxView = GridBoxView;
    GridBoxView.__name__ = "GridBoxView";
    class GridBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GridBox = GridBox;
    _a = GridBox;
    GridBox.__name__ = "GridBox";
    (() => {
        _a.prototype.default_view = GridBoxView;
        _a.define(({ Array, Nullable }) => {
            return {
                children: [Array((0, kinds_1.GridChild)(ui_element_1.UIElement)), []],
                rows: [Nullable(kinds_1.TracksSizing), null],
                cols: [Nullable(kinds_1.TracksSizing), null],
            };
        });
    })();
},
/* models/layouts/css_grid_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(373) /* ./layout_dom */;
    const alignments_1 = require(376) /* ./alignments */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const dom_1 = require(56) /* ../../core/dom */;
    const grid_1 = require(233) /* ../../core/layout/grid */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const types_1 = require(8) /* ../../core/util/types */;
    const { max } = Math;
    class CSSGridBoxView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            const { spacing } = this.model.properties;
            this.on_change(spacing, () => this.invalidate_layout());
        }
        get child_models() {
            return this._children.map(([child]) => child);
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _update_layout() {
            super._update_layout();
            const styles = {};
            const [row_gap, column_gap] = (() => {
                const { spacing } = this.model;
                return (0, types_1.isNumber)(spacing) ? [spacing, spacing] : spacing;
            })();
            styles.row_gap = (0, dom_1.px)(row_gap);
            styles.column_gap = (0, dom_1.px)(column_gap);
            let nrows = 0;
            let ncols = 0;
            const layoutable = new grid_1.Container();
            for (const [[, row, col, row_span = 1, col_span = 1], i] of (0, iterator_1.enumerate)(this._children)) {
                const view = this.child_views[i];
                nrows = max(nrows, row + row_span);
                ncols = max(ncols, col + col_span);
                // CSS grid is 1-based, but layout is 0-based
                const styles = {};
                styles.grid_row_start = `${row + 1}`;
                styles.grid_row_end = `span ${row_span}`;
                styles.grid_column_start = `${col + 1}`;
                styles.grid_column_end = `span ${col_span}`;
                view.style.append(":host", styles);
                if (view instanceof layout_dom_1.LayoutDOMView && view.layout != null) {
                    const r0 = row;
                    const c0 = col;
                    const r1 = row + row_span - 1;
                    const c1 = col + col_span - 1;
                    layoutable.add({ r0, c0, r1, c1 }, view);
                }
            }
            const { _rows: rows, _cols: cols } = this;
            if (rows instanceof Map)
                nrows = max(nrows, ...rows.keys());
            else if ((0, types_1.isArray)(rows))
                nrows = max(nrows, rows.length);
            if (cols instanceof Map)
                ncols = max(ncols, ...cols.keys());
            else if ((0, types_1.isArray)(cols))
                ncols = max(ncols, cols.length);
            function parse_sizing(tracks, template) {
                if (tracks instanceof Map) {
                    for (const [i, spec] of tracks.entries()) {
                        if ((0, types_1.isString)(spec))
                            template[i].size = spec;
                        else
                            template[i] = spec;
                    }
                }
                else if ((0, types_1.isArray)(tracks)) {
                    for (const [spec, i] of (0, iterator_1.enumerate)(tracks)) {
                        if ((0, types_1.isString)(spec))
                            template[i].size = spec;
                        else
                            template[i] = spec;
                    }
                }
                else if (tracks != null) {
                    for (const row of template) {
                        if ((0, types_1.isString)(tracks))
                            row.size = tracks;
                        else {
                            row.size = tracks.size;
                            row.align = tracks.align;
                        }
                    }
                }
            }
            const rows_template = Array(nrows).fill(null).map(() => ({}));
            const cols_template = Array(ncols).fill(null).map(() => ({}));
            parse_sizing(rows, rows_template);
            parse_sizing(cols, cols_template);
            for (const [[, row, col], i] of (0, iterator_1.enumerate)(this._children)) {
                const child = this.child_views[i];
                const { halign, valign } = child.box_sizing();
                child.style.append(":host", {
                    justify_self: halign !== null && halign !== void 0 ? halign : cols_template[col].align,
                    align_self: valign !== null && valign !== void 0 ? valign : rows_template[row].align,
                });
            }
            const default_size = "auto";
            styles.grid_template_rows = rows_template.map(({ size }) => size !== null && size !== void 0 ? size : default_size).join(" ");
            styles.grid_template_columns = cols_template.map(({ size }) => size !== null && size !== void 0 ? size : default_size).join(" ");
            this.style.append(":host", styles);
            if (layoutable.size != 0) {
                this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                this.layout.set_sizing();
            }
            else {
                delete this.layout;
            }
        }
    }
    exports.CSSGridBoxView = CSSGridBoxView;
    CSSGridBoxView.__name__ = "CSSGridBoxView";
    class CSSGridBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CSSGridBox = CSSGridBox;
    _a = CSSGridBox;
    CSSGridBox.__name__ = "CSSGridBox";
    (() => {
        _a.define(() => ({
            spacing: [kinds_1.GridSpacing, 0],
        }));
    })();
},
/* models/layouts/group_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const layout_dom_1 = require(373) /* ./layout_dom */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const dom_1 = require(56) /* ../../core/dom */;
    const group_box_css_1 = tslib_1.__importDefault(require(380) /* ../../styles/group_box.css */);
    class GroupBoxView extends layout_dom_1.LayoutDOMView {
        stylesheets() {
            return [...super.stylesheets(), group_box_css_1.default];
        }
        connect_signals() {
            super.connect_signals();
            const { child } = this.model.properties;
            this.on_change(child, () => this.update_children());
            const { checkable, disabled } = this.model.properties;
            this.on_change(checkable, () => {
                (0, dom_1.display)(this.checkbox_el, this.model.checkable);
            });
            this.on_change(disabled, () => {
                this.checkbox_el.checked = !this.model.disabled;
            });
        }
        get child_models() {
            return [this.model.child];
        }
        render() {
            super.render();
            const { checkable, disabled, title } = this.model;
            this.checkbox_el = (0, dom_1.input)({ type: "checkbox", checked: !disabled });
            this.checkbox_el.addEventListener("change", () => {
                this.model.disabled = !this.checkbox_el.checked;
            });
            (0, dom_1.display)(this.checkbox_el, checkable);
            const title_el = (0, dom_1.legend)({}, this.checkbox_el, title);
            const child_els = this.child_views.map((child) => child.el);
            this.fieldset_el = (0, dom_1.fieldset)({}, title_el, ...child_els);
            this.shadow_el.appendChild(this.fieldset_el);
        }
        _update_children() {
            const child_els = this.child_views.map((child) => child.el);
            this.fieldset_el.append(...child_els);
        }
    }
    exports.GroupBoxView = GroupBoxView;
    GroupBoxView.__name__ = "GroupBoxView";
    class GroupBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GroupBox = GroupBox;
    _a = GroupBox;
    GroupBox.__name__ = "GroupBox";
    (() => {
        _a.prototype.default_view = GroupBoxView;
        _a.define(({ Boolean, String, Nullable, Ref }) => ({
            title: [Nullable(String), null],
            child: [Ref(ui_element_1.UIElement)],
            checkable: [Boolean, false],
        }));
    })();
},
/* styles/group_box.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `legend{display:flex;gap:0.5em;padding:0 calc(var(--padding-horizontal) / 2);}fieldset{border:1px solid #ccc;}`;
},
/* models/layouts/hbox.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const css_grid_box_1 = require(378) /* ./css_grid_box */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const kinds_2 = require(21) /* ../../core/kinds */;
    const HBoxChild = (0, kinds_2.Struct)({ child: (0, kinds_2.Ref)(ui_element_1.UIElement), col: (0, kinds_2.Opt)(kinds_1.Index), span: (0, kinds_2.Opt)(kinds_1.Span) });
    class HBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, cols } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change(cols, () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children.map(({ child, col, span }, i) => [child, 0, col !== null && col !== void 0 ? col : i, 1, span !== null && span !== void 0 ? span : 1]);
        }
        get _rows() {
            return null;
        }
        get _cols() {
            return this.model.cols;
        }
    }
    exports.HBoxView = HBoxView;
    HBoxView.__name__ = "HBoxView";
    class HBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HBox = HBox;
    _a = HBox;
    HBox.__name__ = "HBox";
    (() => {
        _a.prototype.default_view = HBoxView;
        _a.define(({ Array, Nullable }) => ({
            children: [Array(HBoxChild), []],
            cols: [Nullable(kinds_1.TracksSizing), null],
        }));
    })();
},
/* models/layouts/row.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const flex_box_1 = require(372) /* ./flex_box */;
    class RowView extends flex_box_1.FlexBoxView {
        constructor() {
            super(...arguments);
            this._direction = "row";
        }
    }
    exports.RowView = RowView;
    RowView.__name__ = "RowView";
    class Row extends flex_box_1.FlexBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Row = Row;
    _a = Row;
    Row.__name__ = "Row";
    (() => {
        _a.prototype.default_view = RowView;
    })();
},
/* models/layouts/scroll_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(373) /* ./layout_dom */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const enums_1 = require(20) /* ../../core/enums */;
    class ScrollBoxView extends layout_dom_1.LayoutDOMView {
        stylesheets() {
            return [...super.stylesheets()];
        }
        connect_signals() {
            super.connect_signals();
            const { child, horizontal_scrollbar, vertical_scrollbar } = this.model.properties;
            this.on_change(child, () => this.update_children());
            this.on_change([horizontal_scrollbar, vertical_scrollbar], () => this.invalidate_layout());
        }
        get child_models() {
            return [this.model.child];
        }
        _update_layout() {
            super._update_layout();
            function to_overflow(policy) {
                switch (policy) {
                    case "auto": return "auto";
                    case "visible": return "scroll";
                    case "hidden": return "hidden";
                }
            }
            const { horizontal_scrollbar, vertical_scrollbar } = this.model;
            this.style.append(":host", {
                overflow_x: to_overflow(horizontal_scrollbar),
                overflow_y: to_overflow(vertical_scrollbar),
            });
        }
    }
    exports.ScrollBoxView = ScrollBoxView;
    ScrollBoxView.__name__ = "ScrollBoxView";
    class ScrollBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ScrollBox = ScrollBox;
    _a = ScrollBox;
    ScrollBox.__name__ = "ScrollBox";
    (() => {
        _a.prototype.default_view = ScrollBoxView;
        _a.define(({ Ref }) => ({
            child: [Ref(ui_element_1.UIElement)],
            horizontal_scrollbar: [enums_1.ScrollbarPolicy, "auto"],
            vertical_scrollbar: [enums_1.ScrollbarPolicy, "auto"],
        }));
    })();
},
/* models/layouts/spacer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(373) /* ./layout_dom */;
    class SpacerView extends layout_dom_1.LayoutDOMView {
        constructor() {
            super(...arguments);
            this._auto_width = "auto";
            this._auto_height = "auto";
        }
        get child_models() {
            return [];
        }
    }
    exports.SpacerView = SpacerView;
    SpacerView.__name__ = "SpacerView";
    class Spacer extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Spacer = Spacer;
    _a = Spacer;
    Spacer.__name__ = "Spacer";
    (() => {
        _a.prototype.default_view = SpacerView;
    })();
},
/* models/layouts/tab_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    class TabPanel extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TabPanel = TabPanel;
    _a = TabPanel;
    TabPanel.__name__ = "TabPanel";
    (() => {
        _a.define(({ Boolean, String, Ref }) => ({
            title: [String, ""],
            child: [Ref(ui_element_1.UIElement)],
            closable: [Boolean, false],
            disabled: [Boolean, false],
        }));
    })();
},
/* models/layouts/tabs.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const dom_1 = require(56) /* ../../core/dom */;
    const array_1 = require(10) /* ../../core/util/array */;
    const grid_1 = require(233) /* ../../core/layout/grid */;
    const enums_1 = require(20) /* ../../core/enums */;
    const layout_dom_1 = require(373) /* ./layout_dom */;
    const tab_panel_1 = require(385) /* ./tab_panel */;
    const alignments_1 = require(376) /* ./alignments */;
    const tabs_css_1 = tslib_1.__importStar(require(387) /* ../../styles/tabs.css */), tabs = tabs_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(278) /* ../../styles/icons.css */);
    class TabsView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            const { tabs, active } = this.model.properties;
            this.on_change(tabs, () => {
                this._update_headers();
                this.update_children();
            });
            this.on_change(active, () => {
                this.update_active();
            });
        }
        stylesheets() {
            return [...super.stylesheets(), tabs_css_1.default, icons_css_1.default];
        }
        get child_models() {
            return this.model.tabs.map((tab) => tab.child);
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _update_layout() {
            super._update_layout();
            const loc = this.model.tabs_location;
            this.class_list.remove([...enums_1.Location].map((loc) => tabs[loc]));
            this.class_list.add(tabs[loc]);
            const layoutable = new grid_1.Container();
            for (const view of this.child_views) {
                view.style.append(":host", { grid_area: "stack" });
                if (view instanceof layout_dom_1.LayoutDOMView && view.layout != null) {
                    layoutable.add({ r0: 0, c0: 0, r1: 1, c1: 1 }, view);
                }
            }
            if (layoutable.size != 0) {
                this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                this.layout.set_sizing();
            }
            else {
                delete this.layout;
            }
        }
        _after_layout() {
            super._after_layout();
            const { child_views } = this;
            for (const child_view of child_views)
                (0, dom_1.hide)(child_view.el);
            const { active } = this.model;
            if (active in child_views) {
                const tab = child_views[active];
                (0, dom_1.show)(tab.el);
            }
        }
        render() {
            super.render();
            this.header_el = (0, dom_1.div)({ class: tabs.header });
            this.shadow_el.append(this.header_el);
            this._update_headers();
        }
        _update_headers() {
            const { active } = this.model;
            const headers = this.model.tabs.map((tab, i) => {
                const el = (0, dom_1.div)({ class: [tabs.tab, i == active ? tabs.active : null], tabIndex: 0 }, tab.title);
                el.addEventListener("click", (event) => {
                    if (this.model.disabled)
                        return;
                    if (event.target == event.currentTarget)
                        this.change_active(i);
                });
                if (tab.closable) {
                    const close_el = (0, dom_1.div)({ class: tabs.close });
                    close_el.addEventListener("click", (event) => {
                        if (event.target == event.currentTarget) {
                            this.model.tabs = (0, array_1.remove_at)(this.model.tabs, i);
                            const 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.header_els = headers;
            (0, dom_1.empty)(this.header_el);
            this.header_el.append(...headers);
        }
        change_active(i) {
            if (i != this.model.active) {
                this.model.active = i;
            }
        }
        update_active() {
            const i = this.model.active;
            const { header_els } = this;
            for (const el of header_els) {
                el.classList.remove(tabs.active);
            }
            if (i in header_els) {
                header_els[i].classList.add(tabs.active);
            }
            const { child_views } = this;
            for (const child_view of child_views) {
                (0, dom_1.hide)(child_view.el);
            }
            if (i in child_views) {
                (0, dom_1.show)(child_views[i].el);
            }
        }
    }
    exports.TabsView = TabsView;
    TabsView.__name__ = "TabsView";
    class Tabs extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Tabs = Tabs;
    _a = Tabs;
    Tabs.__name__ = "Tabs";
    (() => {
        _a.prototype.default_view = TabsView;
        _a.define(({ Int, Array, Ref }) => ({
            tabs: [Array(Ref(tab_panel_1.TabPanel)), []],
            tabs_location: [enums_1.Location, "above"],
            active: [Int, 0],
        }));
    })();
},
/* styles/tabs.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.header = "bk-header";
    exports.tab = "bk-tab";
    exports.active = "bk-active";
    exports.close = "bk-close";
    exports.disabled = "bk-disabled";
    exports.default = `:host{display:grid;}:host(.bk-above){grid-template:"header" max-content "stack" 1fr / 1fr;}:host(.bk-below){grid-template:"stack" 1fr "header" max-content / 1fr;}:host(.bk-left){grid-template:"header stack" 1fr / max-content 1fr;}:host(.bk-right){grid-template:"stack header" 1fr / 1fr max-content;}.bk-header{grid-area:"header";display:flex;flex-wrap:nowrap;align-items:stretch;user-select:none;-webkit-user-select:none;}:host(.bk-above) .bk-header,:host(.bk-below) .bk-header{flex-direction:row;}:host(.bk-left) .bk-header,:host(.bk-right) .bk-header{flex-direction:column;}:host(.bk-above) .bk-header{border-bottom:1px solid #e6e6e6;}:host(.bk-right) .bk-header{border-left:1px solid #e6e6e6;}:host(.bk-below) .bk-header{border-top:1px solid #e6e6e6;}:host(.bk-left) .bk-header{border-right:1px solid #e6e6e6;}.bk-tab{padding:4px 8px;border:solid transparent;outline:0;outline-offset:-5px;white-space:nowrap;cursor:pointer;text-align:center;}.bk-tab:hover{background-color:#f2f2f2;}.bk-tab:focus,.bk-tab:active{outline:1px dotted #ccc;}.bk-tab.bk-active{color:#4d4d4d;background-color:white;border-color:#e6e6e6;}.bk-tab .bk-close{margin-left:10px;}.bk-tab.bk-disabled{cursor:not-allowed;pointer-events:none;opacity:0.65;}:host(.bk-above) .bk-tab{border-width:3px 1px 0px 1px;border-radius:var(--border-radius) var(--border-radius) 0 0;}:host(.bk-right) .bk-tab{border-width:1px 3px 1px 0px;border-radius:0 var(--border-radius) var(--border-radius) 0;}:host(.bk-below) .bk-tab{border-width:0px 1px 3px 1px;border-radius:0 0 var(--border-radius) var(--border-radius);}:host(.bk-left) .bk-tab{border-width:1px 0px 1px 3px;border-radius:var(--border-radius) 0 0 var(--border-radius);}.bk-close{display:inline-block;vertical-align:middle;width:14px;height:14px;cursor:pointer;background-color:gray;mask-image:var(--bokeh-icon-x);mask-size:contain;mask-repeat:no-repeat;-webkit-mask-image:var(--bokeh-icon-x);-webkit-mask-size:contain;-webkit-mask-repeat:no-repeat;}.bk-close:hover{background-color:red;}`;
},
/* models/layouts/vbox.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const css_grid_box_1 = require(378) /* ./css_grid_box */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const kinds_2 = require(21) /* ../../core/kinds */;
    const VBoxChild = (0, kinds_2.Struct)({ child: (0, kinds_2.Ref)(ui_element_1.UIElement), row: (0, kinds_2.Opt)(kinds_1.Index), span: (0, kinds_2.Opt)(kinds_1.Span) });
    class VBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, rows } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change(rows, () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children.map(({ child, row, span }, i) => [child, row !== null && row !== void 0 ? row : i, 0, span !== null && span !== void 0 ? span : 1, 1]);
        }
        get _rows() {
            return this.model.rows;
        }
        get _cols() {
            return null;
        }
    }
    exports.VBoxView = VBoxView;
    VBoxView.__name__ = "VBoxView";
    class VBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VBox = VBox;
    _a = VBox;
    VBox.__name__ = "VBox";
    (() => {
        _a.prototype.default_view = VBoxView;
        _a.define(({ Array, Nullable }) => ({
            children: [Array(VBoxChild), []],
            rows: [Nullable(kinds_1.TracksSizing), null],
        }));
    })();
},
/* models/menus/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var menu_1 = require(374) /* ./menu */;
    __esExport("Menu", menu_1.Menu);
    var action_1 = require(390) /* ./action */;
    __esExport("Action", action_1.Action);
    var check_action_1 = require(392) /* ./check_action */;
    __esExport("CheckAction", check_action_1.CheckAction);
    var section_1 = require(393) /* ./section */;
    __esExport("Section", section_1.Section);
    var divider_1 = require(394) /* ./divider */;
    __esExport("Divider", divider_1.Divider);
},
/* models/menus/action.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const menu_item_1 = require(375) /* ./menu_item */;
    const menu_1 = require(374) /* ./menu */;
    const icon_1 = require(391) /* ../ui/icons/icon */;
    const dom_1 = require(56) /* ../../core/dom */;
    // import * as menus from "styles/menus.css"
    class ActionView extends menu_item_1.MenuItemView {
        _click() {
        }
        render() {
            super.render();
            const { label, description } = this.model;
            this.el.tabIndex = 0;
            this.el.title = description !== null && description !== void 0 ? description : "";
            this.el.appendChild((0, dom_1.span)(label));
            this.el.addEventListener("click", () => {
                this._click();
            });
            this.el.addEventListener("keydown", (event) => {
                if (event.key == "Enter") {
                    this._click();
                }
            });
        }
    }
    exports.ActionView = ActionView;
    ActionView.__name__ = "ActionView";
    class Action extends menu_item_1.MenuItem {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Action = Action;
    _a = Action;
    Action.__name__ = "Action";
    (() => {
        _a.prototype.default_view = ActionView;
        _a.define(({ String, Nullable, Ref }) => ({
            icon: [Nullable(Ref(icon_1.Icon)), null],
            label: [String],
            description: [Nullable(String), null],
            menu: [Nullable(Ref(menu_1.Menu)), null],
        }));
    })();
},
/* models/ui/icons/icon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../../model */;
    const dom_view_1 = require(55) /* ../../../core/dom_view */;
    class IconView extends dom_view_1.DOMComponentView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.render());
        }
    }
    exports.IconView = IconView;
    IconView.__name__ = "IconView";
    class Icon extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Icon = Icon;
    _a = Icon;
    Icon.__name__ = "Icon";
    (() => {
        _a.define(({ Number, Or, CSSLength }) => ({
            size: [Or(Number, CSSLength), "1em"],
        }));
    })();
},
/* models/menus/check_action.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const action_1 = require(390) /* ./action */;
    class CheckActionView extends action_1.ActionView {
    }
    exports.CheckActionView = CheckActionView;
    CheckActionView.__name__ = "CheckActionView";
    class CheckAction extends action_1.Action {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CheckAction = CheckAction;
    _a = CheckAction;
    CheckAction.__name__ = "CheckAction";
    (() => {
        _a.prototype.default_view = CheckActionView;
        _a.define(({ Boolean }) => ({
            checked: [Boolean, false],
        }));
    })();
},
/* models/menus/section.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const menu_item_1 = require(375) /* ./menu_item */;
    class SectionView extends menu_item_1.MenuItemView {
        render() {
            super.render();
        }
    }
    exports.SectionView = SectionView;
    SectionView.__name__ = "SectionView";
    class Section extends menu_item_1.MenuItem {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Section = Section;
    _a = Section;
    Section.__name__ = "Section";
    (() => {
        _a.prototype.default_view = SectionView;
        _a.define(({ Array, Ref }) => ({
            items: [Array(Ref(menu_item_1.MenuItem)), []],
        }));
    })();
},
/* models/menus/divider.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const menu_item_1 = require(375) /* ./menu_item */;
    const menus = tslib_1.__importStar(require(277) /* ../../styles/menus.css */);
    class DividerView extends menu_item_1.MenuItemView {
        render() {
            super.render();
            this.el.classList.add(menus.divider);
        }
    }
    exports.DividerView = DividerView;
    DividerView.__name__ = "DividerView";
    class Divider extends menu_item_1.MenuItem {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Divider = Divider;
    _a = Divider;
    Divider.__name__ = "Divider";
    (() => {
        _a.prototype.default_view = DividerView;
    })();
},
/* models/text/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var math_text_1 = require(151) /* ./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(158) /* ./plain_text */;
    __esExport("PlainText", plain_text_1.PlainText);
},
/* models/transforms/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_transform_1 = require(397) /* ./customjs_transform */;
    __esExport("CustomJSTransform", customjs_transform_1.CustomJSTransform);
    var dodge_1 = require(398) /* ./dodge */;
    __esExport("Dodge", dodge_1.Dodge);
    var interpolator_1 = require(400) /* ./interpolator */;
    __esExport("Interpolator", interpolator_1.Interpolator);
    var jitter_1 = require(401) /* ./jitter */;
    __esExport("Jitter", jitter_1.Jitter);
    var linear_interpolator_1 = require(403) /* ./linear_interpolator */;
    __esExport("LinearInterpolator", linear_interpolator_1.LinearInterpolator);
    var step_interpolator_1 = require(404) /* ./step_interpolator */;
    __esExport("StepInterpolator", step_interpolator_1.StepInterpolator);
    var transform_1 = require(86) /* ./transform */;
    __esExport("Transform", transform_1.Transform);
},
/* models/transforms/customjs_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const transform_1 = require(86) /* ./transform */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CustomJSTransform extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        _make_transform(name, func) {
            return new Function(...this.names, name, (0, string_1.use_strict)(func));
        }
        get scalar_transform() {
            return this._make_transform("x", this.func);
        }
        get vector_transform() {
            return this._make_transform("xs", this.v_func);
        }
        compute(x) {
            return this.scalar_transform(...this.values, x);
        }
        v_compute(xs) {
            return this.vector_transform(...this.values, xs);
        }
    }
    exports.CustomJSTransform = CustomJSTransform;
    _a = CustomJSTransform;
    CustomJSTransform.__name__ = "CustomJSTransform";
    (() => {
        _a.define(({ Unknown, String, Dict }) => ({
            args: [Dict(Unknown), {}],
            func: [String, ""],
            v_func: [String, ""],
        }));
    })();
},
/* models/transforms/dodge.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const range_transform_1 = require(399) /* ./range_transform */;
    class Dodge extends range_transform_1.RangeTransform {
        constructor(attrs) {
            super(attrs);
        }
        _compute(x) {
            return x + this.value;
        }
    }
    exports.Dodge = Dodge;
    _a = Dodge;
    Dodge.__name__ = "Dodge";
    (() => {
        _a.define(({ Number }) => ({
            value: [Number, 0],
        }));
    })();
},
/* models/transforms/range_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const transform_1 = require(86) /* ./transform */;
    const range_1 = require(87) /* ../ranges/range */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    const types_1 = require(24) /* ../../core/types */;
    const types_2 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class RangeTransform extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        v_compute(xs0) {
            let 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)();
            const result = new ((0, types_1.infer_type)(xs))(xs.length);
            for (let i = 0; i < xs.length; i++) {
                const x = xs[i];
                result[i] = this._compute(x);
            }
            return result;
        }
        compute(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)();
        }
    }
    exports.RangeTransform = RangeTransform;
    _a = RangeTransform;
    RangeTransform.__name__ = "RangeTransform";
    (() => {
        _a.define(({ Ref, Nullable }) => ({
            range: [Nullable(Ref(range_1.Range)), null],
        }));
    })();
},
/* models/transforms/interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const transform_1 = require(86) /* ./transform */;
    const columnar_data_source_1 = require(101) /* ../sources/columnar_data_source */;
    const types_1 = require(24) /* ../../core/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_2 = require(8) /* ../../core/util/types */;
    class Interpolator extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
            this._sorted_dirty = true;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.change, () => this._sorted_dirty = true);
        }
        v_compute(xs) {
            const ArrayType = (0, types_1.infer_type)(xs);
            const result = new ArrayType(xs.length);
            for (let i = 0; i < xs.length; i++) {
                const x = xs[i];
                result[i] = this.compute(x);
            }
            return result;
        }
        sort(descending = false) {
            if (!this._sorted_dirty)
                return;
            let tsx;
            let tsy;
            if ((0, types_2.isString)(this.x) && (0, types_2.isString)(this.y) && this.data != null) {
                const 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");
            const n = tsx.length;
            const index = new Uint32Array(n);
            for (let i = 0; i < n; i++) {
                index[i] = i;
            }
            const sign = descending ? -1 : 1;
            index.sort((i, j) => 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 (let i = 0; i < n; i++) {
                this._x_sorted[i] = tsx[index[i]];
                this._y_sorted[i] = tsy[index[i]];
            }
            this._sorted_dirty = false;
        }
    }
    exports.Interpolator = Interpolator;
    _a = Interpolator;
    Interpolator.__name__ = "Interpolator";
    (() => {
        _a.define(({ Boolean, Number, String, Ref, Array, Or, Nullable }) => ({
            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) {
    var _a;
    __esModule();
    const range_transform_1 = require(399) /* ./range_transform */;
    const factor_range_1 = require(98) /* ../ranges/factor_range */;
    const random_generator_1 = require(402) /* ../random/random_generator */;
    const enums_1 = require(20) /* ../../core/enums */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const random_1 = require(271) /* ../../core/util/random */;
    class Jitter extends range_transform_1.RangeTransform {
        constructor(attrs) {
            super(attrs);
            this._previous_offsets = null;
        }
        initialize() {
            var _b, _c;
            super.initialize();
            this._generator = (_c = (_b = this.random_generator) === null || _b === void 0 ? void 0 : _b.generator()) !== null && _c !== void 0 ? _c : new random_1.SystemRandom();
        }
        v_compute(xs0) {
            const xs = (() => {
                if (this.range instanceof factor_range_1.FactorRange)
                    return this.range.v_synthetic(xs0);
                else
                    return xs0;
            })();
            const offsets = (() => {
                var _b;
                const xs_length = xs.length;
                if (((_b = this._previous_offsets) === null || _b === void 0 ? void 0 : _b.length) != xs_length) {
                    this._previous_offsets = this._v_compute(xs_length);
                }
                return this._previous_offsets;
            })();
            return (0, arrayable_1.map)(offsets, (offset, i) => offset + xs[i]);
        }
        _compute() {
            const { mean, width } = this;
            switch (this.distribution) {
                case "uniform": return this._generator.uniform(mean, width);
                case "normal": return this._generator.normal(mean, width);
            }
        }
        _v_compute(n) {
            const { mean, width } = this;
            switch (this.distribution) {
                case "uniform": return this._generator.uniforms(mean, width, n);
                case "normal": return this._generator.normals(mean, width, n);
            }
        }
    }
    exports.Jitter = Jitter;
    _a = Jitter;
    Jitter.__name__ = "Jitter";
    (() => {
        _a.define(({ Number }) => ({
            mean: [Number, 0],
            width: [Number, 1],
            distribution: [enums_1.Distribution, "uniform"],
        }));
        _a.internal(({ Nullable, Ref }) => ({
            random_generator: [Nullable(Ref(random_generator_1.RandomGenerator)), null],
        }));
    })();
},
/* models/random/random_generator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class RandomGenerator extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.RandomGenerator = RandomGenerator;
    RandomGenerator.__name__ = "RandomGenerator";
},
/* models/transforms/linear_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(10) /* ../../core/util/array */;
    const interpolator_1 = require(400) /* ./interpolator */;
    class LinearInterpolator extends interpolator_1.Interpolator {
        constructor(attrs) {
            super(attrs);
        }
        compute(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];
            const ind = (0, array_1.find_last_index)(this._x_sorted, num => num < x);
            const x1 = this._x_sorted[ind];
            const x2 = this._x_sorted[ind + 1];
            const y1 = this._y_sorted[ind];
            const y2 = this._y_sorted[ind + 1];
            return y1 + (((x - x1) / (x2 - x1)) * (y2 - y1));
        }
    }
    exports.LinearInterpolator = LinearInterpolator;
    LinearInterpolator.__name__ = "LinearInterpolator";
},
/* models/transforms/step_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const interpolator_1 = require(400) /* ./interpolator */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    class StepInterpolator extends interpolator_1.Interpolator {
        constructor(attrs) {
            super(attrs);
        }
        compute(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];
            }
            let ind;
            switch (this.mode) {
                case "after": {
                    ind = (0, array_1.find_last_index)(this._x_sorted, num => x >= num);
                    break;
                }
                case "before": {
                    ind = (0, array_1.find_index)(this._x_sorted, num => x <= num);
                    break;
                }
                case "center": {
                    const diffs = (0, array_1.map)(this._x_sorted, (tx) => Math.abs(tx - x));
                    const mdiff = (0, array_1.min)(diffs);
                    ind = (0, array_1.find_index)(diffs, num => mdiff === num);
                    break;
                }
                default:
                    throw new Error(`unknown mode: ${this.mode}`);
            }
            return ind != -1 ? this._y_sorted[ind] : NaN;
        }
    }
    exports.StepInterpolator = StepInterpolator;
    _a = StepInterpolator;
    StepInterpolator.__name__ = "StepInterpolator";
    (() => {
        _a.define(() => ({
            mode: [enums_1.StepMode, "after"],
        }));
    })();
},
/* models/plots/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var gmap_plot_1 = require(406) /* ./gmap_plot */;
    __esExport("MapOptions", gmap_plot_1.MapOptions);
    var gmap_plot_2 = require(406) /* ./gmap_plot */;
    __esExport("GMapOptions", gmap_plot_2.GMapOptions);
    var gmap_plot_3 = require(406) /* ./gmap_plot */;
    __esExport("GMapPlot", gmap_plot_3.GMapPlot);
    var gmap_1 = require(414) /* ./gmap */;
    __esExport("GMap", gmap_1.GMap);
    var plot_1 = require(407) /* ./plot */;
    __esExport("Plot", plot_1.Plot);
    var grid_plot_1 = require(415) /* ./grid_plot */;
    __esExport("GridPlot", grid_plot_1.GridPlot);
    var figure_1 = require(416) /* ./figure */;
    __esExport("Figure", figure_1.Figure);
},
/* models/plots/gmap_plot.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c;
    __esModule();
    const plot_1 = require(407) /* ./plot */;
    const enums_1 = require(20) /* ../../core/enums */;
    const model_1 = require(50) /* ../../model */;
    const range1d_1 = require(88) /* ../ranges/range1d */;
    const gmap_plot_canvas_1 = require(413) /* ./gmap_plot_canvas */;
    __esExport("GMapPlotView", gmap_plot_canvas_1.GMapPlotView);
    class MapOptions extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MapOptions = MapOptions;
    _a = MapOptions;
    MapOptions.__name__ = "MapOptions";
    (() => {
        _a.define(({ Int, Number }) => ({
            lat: [Number],
            lng: [Number],
            zoom: [Int, 12],
        }));
    })();
    class GMapOptions extends MapOptions {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GMapOptions = GMapOptions;
    _b = GMapOptions;
    GMapOptions.__name__ = "GMapOptions";
    (() => {
        _b.define(({ Boolean, Int, String, Nullable }) => ({
            map_type: [enums_1.MapType, "roadmap"],
            scale_control: [Boolean, false],
            styles: [Nullable(String), null],
            tilt: [Int, 45],
        }));
    })();
    class GMapPlot extends plot_1.Plot {
        constructor(attrs) {
            super(attrs);
            this.use_map = true;
        }
    }
    exports.GMapPlot = GMapPlot;
    _c = GMapPlot;
    GMapPlot.__name__ = "GMapPlot";
    (() => {
        _c.prototype.default_view = gmap_plot_canvas_1.GMapPlotView;
        _c.define(({ String, Bytes, Ref }) => ({
            map_options: [Ref(GMapOptions)],
            api_key: [Bytes],
            api_version: [String, "weekly"],
        }));
        _c.override({
            x_range: () => new range1d_1.Range1d(),
            y_range: () => new range1d_1.Range1d(),
            background_fill_alpha: 0.0,
        });
    })();
},
/* models/plots/plot.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const mixins = tslib_1.__importStar(require(78) /* ../../core/property_mixins */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const signaling_1 = require(15) /* ../../core/signaling */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const set_1 = require(44) /* ../../core/util/set */;
    const types_1 = require(8) /* ../../core/util/types */;
    const layout_dom_1 = require(373) /* ../layouts/layout_dom */;
    const axis_1 = require(161) /* ../axes/axis */;
    const grid_1 = require(369) /* ../grids/grid */;
    const annotation_1 = require(73) /* ../annotations/annotation */;
    const title_1 = require(144) /* ../annotations/title */;
    const linear_scale_1 = require(90) /* ../scales/linear_scale */;
    const toolbar_1 = require(265) /* ../tools/toolbar */;
    const range_1 = require(87) /* ../ranges/range */;
    const scale_1 = require(85) /* ../scales/scale */;
    const column_data_source_1 = require(106) /* ../sources/column_data_source */;
    const renderer_1 = require(74) /* ../renderers/renderer */;
    const data_renderer_1 = require(202) /* ../renderers/data_renderer */;
    const glyph_renderer_1 = require(201) /* ../renderers/glyph_renderer */;
    const tool_1 = require(273) /* ../tools/tool */;
    const data_range1d_1 = require(95) /* ../ranges/data_range1d */;
    const plot_canvas_1 = require(408) /* ./plot_canvas */;
    __esExport("PlotView", plot_canvas_1.PlotView);
    class Plot extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
            this.use_map = false;
            this.reset = new signaling_1.Signal0(this, "reset");
        }
        add_layout(renderer, side = "center") {
            const renderers = this.properties[side].get_value();
            this.setv({ [side]: [...renderers, renderer] });
        }
        remove_layout(renderer) {
            const del = (items) => {
                (0, array_1.remove_by)(items, (item) => item == renderer);
            };
            del(this.left);
            del(this.right);
            del(this.above);
            del(this.below);
            del(this.center);
        }
        get data_renderers() {
            return this.renderers.filter((r) => r instanceof data_renderer_1.DataRenderer);
        }
        add_renderers(...renderers) {
            this.renderers = [...this.renderers, ...renderers];
        }
        add_glyph(glyph, source = new column_data_source_1.ColumnDataSource(), attrs = {}) {
            const renderer = new glyph_renderer_1.GlyphRenderer(Object.assign(Object.assign({}, attrs), { data_source: source, glyph }));
            this.add_renderers(renderer);
            return renderer;
        }
        add_tools(...tools) {
            const computed_tools = tools.map((tool) => tool instanceof tool_1.Tool ? tool : tool_1.Tool.from_string(tool));
            this.toolbar.tools = [...this.toolbar.tools, ...computed_tools];
        }
        remove_tools(...tools) {
            this.toolbar.tools = [...(0, set_1.difference)(new Set(this.toolbar.tools), new Set(tools))];
        }
        get panels() {
            return [...this.side_panels, ...this.center];
        }
        get side_panels() {
            const { above, below, left, right } = this;
            return (0, array_1.concat)([above, below, left, right]);
        }
    }
    exports.Plot = Plot;
    _a = Plot;
    Plot.__name__ = "Plot";
    (() => {
        _a.prototype.default_view = plot_canvas_1.PlotView;
        _a.mixins([
            ["outline_", mixins.Line],
            ["background_", mixins.Fill],
            ["border_", mixins.Fill],
        ]);
        _a.define(({ Boolean, Number, String, Array, Dict, Or, Ref, Null, Nullable, Struct, Opt }) => ({
            toolbar: [Ref(toolbar_1.Toolbar), () => new toolbar_1.Toolbar()],
            toolbar_location: [Nullable(enums_1.Location), "right"],
            toolbar_sticky: [Boolean, true],
            toolbar_inner: [Boolean, false],
            frame_width: [Nullable(Number), null],
            frame_height: [Nullable(Number), null],
            frame_align: [Or(Boolean, Struct({ left: Opt(Boolean), right: Opt(Boolean), top: Opt(Boolean), bottom: Opt(Boolean) })), true],
            // revise this when https://github.com/microsoft/TypeScript/pull/42425 is merged
            title: [Or(Ref(title_1.Title), String, Null), "", {
                    convert: (title) => (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), () => new data_range1d_1.DataRange1d()],
            y_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            y_scale: [Ref(scale_1.Scale), () => 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, p.unset, { readonly: true }],
            inner_height: [Number, p.unset, { readonly: true }],
            outer_width: [Number, p.unset, { readonly: true }],
            outer_height: [Number, p.unset, { readonly: true }],
            match_aspect: [Boolean, false],
            aspect_scale: [Number, 1],
            reset_policy: [enums_1.ResetPolicy, "standard"],
            hold_render: [Boolean, false],
        }));
        _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();
    const tslib_1 = require(1) /* tslib */;
    const cartesian_frame_1 = require(159) /* ../canvas/cartesian_frame */;
    const canvas_1 = require(300) /* ../canvas/canvas */;
    const tool_proxy_1 = require(274) /* ../tools/tool_proxy */;
    const layout_dom_1 = require(373) /* ../layouts/layout_dom */;
    const annotation_1 = require(73) /* ../annotations/annotation */;
    const title_1 = require(144) /* ../annotations/title */;
    const axis_1 = require(161) /* ../axes/axis */;
    const toolbar_panel_1 = require(264) /* ../annotations/toolbar_panel */;
    const data_range1d_1 = require(95) /* ../ranges/data_range1d */;
    const bokeh_events_1 = require(52) /* ../../core/bokeh_events */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const visuals_1 = require(75) /* ../../core/visuals */;
    const logging_1 = require(19) /* ../../core/logging */;
    const bokeh_events_2 = require(52) /* ../../core/bokeh_events */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const throttle_1 = require(409) /* ../../core/util/throttle */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const canvas_2 = require(269) /* ../../core/util/canvas */;
    const alignments_1 = require(232) /* ../../core/layout/alignments */;
    const border_1 = require(234) /* ../../core/layout/border */;
    const grid_1 = require(233) /* ../../core/layout/grid */;
    const side_panel_1 = require(146) /* ../../core/layout/side_panel */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const text_1 = require(154) /* ../../core/util/text */;
    const range_manager_1 = require(410) /* ./range_manager */;
    const state_manager_1 = require(411) /* ./state_manager */;
    const settings_1 = require(29) /* ../../core/settings */;
    const dom_1 = require(56) /* ../../core/dom */;
    const plots_css_1 = tslib_1.__importDefault(require(412) /* ../../styles/plots.css */);
    const { max } = Math;
    class PlotView extends layout_dom_1.LayoutDOMView {
        constructor() {
            super(...arguments);
            this._render_count = 0;
            this.repainted = new signaling_1.Signal0(this, "repainted");
            this._computed_style = new dom_1.InlineStyleSheet();
            this._outer_bbox = new bbox_1.BBox();
            this._inner_bbox = new bbox_1.BBox();
            this._needs_paint = true;
            this._invalidated_painters = new Set();
            this._invalidate_all = true;
            /*protected*/ this.renderer_views = new Map();
            /*protected*/ this.tool_views = new Map();
            this._needs_notify = false;
        }
        get canvas() {
            return this.canvas_view;
        }
        stylesheets() {
            return [...super.stylesheets(), plots_css_1.default, this._computed_style];
        }
        get toolbar_panel() {
            return this._toolbar != null ? this.renderer_view(this._toolbar) : undefined;
        }
        get state() {
            return this._state_manager;
        }
        set invalidate_dataranges(value) {
            this._range_manager.invalidate_dataranges = value;
        }
        get computed_renderer_views() {
            return this.computed_renderers.map((r) => this.renderer_views.get(r));
        }
        renderer_view(renderer) {
            const view = this.renderer_views.get(renderer);
            if (view == null) {
                for (const [, renderer_view] of this.renderer_views) {
                    const view = renderer_view.renderer_view(renderer);
                    if (view != null)
                        return view;
                }
            }
            return view;
        }
        get auto_ranged_renderers() {
            return this.model.renderers.map((r) => this.renderer_view(r)).filter(data_range1d_1.is_auto_ranged);
        }
        get base_font_size() {
            const font_size = getComputedStyle(this.el).fontSize;
            const result = (0, text_1.parse_css_font_size)(font_size);
            if (result != null) {
                const { value, unit } = result;
                if (unit == "px")
                    return value;
            }
            return null;
        }
        *children() {
            yield* super.children();
            yield* this.renderer_views.values();
            yield* this.tool_views.values();
            yield this.canvas;
        }
        get is_paused() {
            return this._is_paused != null && this._is_paused !== 0;
        }
        get child_models() {
            return [];
        }
        pause() {
            if (this._is_paused == null)
                this._is_paused = 1;
            else
                this._is_paused += 1;
        }
        unpause(no_render = false) {
            if (this._is_paused == null)
                throw new Error("wasn't paused");
            this._is_paused = Math.max(this._is_paused - 1, 0);
            if (this._is_paused == 0 && !no_render)
                this.request_paint("everything");
        }
        notify_finished_after_paint() {
            this._needs_notify = true;
        }
        // TODO: this needs to be removed
        request_render() {
            this.request_paint("everything");
        }
        request_paint(to_invalidate) {
            this.invalidate_painters(to_invalidate);
            this.schedule_paint();
        }
        invalidate_painters(to_invalidate) {
            if (to_invalidate == "everything")
                this._invalidate_all = true;
            else if ((0, types_1.isArray)(to_invalidate)) {
                for (const renderer_view of to_invalidate)
                    this._invalidated_painters.add(renderer_view);
            }
            else
                this._invalidated_painters.add(to_invalidate);
        }
        schedule_paint() {
            if (!this.is_paused) {
                const promise = this.throttled_paint();
                this._ready = this._ready.then(() => promise);
            }
        }
        request_layout() {
            this.request_paint("everything");
        }
        reset() {
            if (this.model.reset_policy == "standard") {
                this.state.clear();
                this.reset_range();
                this.reset_selection();
            }
            this.model.trigger_event(new bokeh_events_1.Reset());
        }
        remove() {
            for (const r of this.frame.ranges.values()) {
                r.plots.delete(this);
            }
            (0, build_views_1.remove_views)(this.renderer_views);
            (0, build_views_1.remove_views)(this.tool_views);
            this.canvas_view.remove();
            super.remove();
        }
        render() {
            super.render();
            this.shadow_el.appendChild(this.canvas_view.el);
            this.canvas_view.render();
        }
        initialize() {
            this.pause();
            super.initialize();
            this.lod_started = false;
            this.visuals = new visuals_1.Visuals(this);
            this._initial_state = {
                selection: new Map(), // XXX: initial selection?
            };
            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);
            for (const r of this.frame.ranges.values()) {
                r.plots.add(this);
            }
            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)(() => {
                if (!this._removed)
                    this.repaint();
            }, 1000 / 60);
            const { title_location, title } = this.model;
            if (title_location != null && title != null) {
                this._title = title instanceof title_1.Title ? title : new title_1.Title({ text: title });
            }
            const { toolbar_location, toolbar_inner, toolbar } = this.model;
            if (toolbar_location != null) {
                this._toolbar = new toolbar_panel_1.ToolbarPanel({ toolbar });
                toolbar.location = toolbar_location;
                toolbar.inner = toolbar_inner;
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { hidpi, output_backend } = this.model;
            const canvas = new canvas_1.Canvas({ hidpi, output_backend });
            this.canvas_view = await (0, build_views_1.build_view)(canvas, { parent: this });
            this.canvas_view.plot_views = [this];
            await this.build_tool_views();
            await this.build_renderer_views();
            this._range_manager.update_dataranges();
        }
        box_sizing() {
            const _a = super.box_sizing(), { width_policy, height_policy } = _a, sizing = tslib_1.__rest(_a, ["width_policy", "height_policy"]);
            const { frame_width, frame_height } = this.model;
            return Object.assign(Object.assign({}, sizing), { width_policy: frame_width != null && width_policy == "auto" ? "fit" : width_policy, height_policy: frame_height != null && height_policy == "auto" ? "fit" : height_policy });
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _update_layout() {
            var _a, _b, _c, _d, _e;
            super._update_layout();
            // TODO: invalidating all should imply "needs paint"
            this._invalidate_all = true;
            this._needs_paint = true;
            const layout = new border_1.BorderLayout();
            const { frame_align } = this.model;
            layout.aligns = (() => {
                if ((0, types_1.isBoolean)(frame_align))
                    return { left: frame_align, right: frame_align, top: frame_align, bottom: frame_align };
                else {
                    const { left = true, right = true, top = true, bottom = true } = frame_align;
                    return { left, right, top, bottom };
                }
            })();
            layout.set_sizing({ width_policy: "max", height_policy: "max" });
            if (this.visuals.outline_line.doit) {
                const width = this.visuals.outline_line.line_width.get_value();
                layout.center_border_width = width;
            }
            const outer_above = (0, array_1.copy)(this.model.above);
            const outer_below = (0, array_1.copy)(this.model.below);
            const outer_left = (0, array_1.copy)(this.model.left);
            const outer_right = (0, array_1.copy)(this.model.right);
            const inner_above = [];
            const inner_below = [];
            const inner_left = [];
            const inner_right = [];
            const get_side = (side, inner = false) => {
                switch (side) {
                    case "above": return inner ? inner_above : outer_above;
                    case "below": return inner ? inner_below : outer_below;
                    case "left": return inner ? inner_left : outer_left;
                    case "right": return inner ? inner_right : outer_right;
                }
            };
            const { title_location } = this.model;
            if (title_location != null && this._title != null) {
                get_side(title_location).push(this._title);
            }
            if (this._toolbar != null) {
                const { location } = this._toolbar.toolbar;
                if (!this.model.toolbar_inner) {
                    const panels = get_side(location);
                    let push_toolbar = true;
                    if (this.model.toolbar_sticky) {
                        for (let i = 0; i < panels.length; i++) {
                            const panel = panels[i];
                            if (panel instanceof title_1.Title) {
                                if (location == "above" || location == "below")
                                    panels[i] = [panel, this._toolbar];
                                else
                                    panels[i] = [this._toolbar, panel];
                                push_toolbar = false;
                                break;
                            }
                        }
                    }
                    if (push_toolbar)
                        panels.push(this._toolbar);
                }
                else {
                    const panels = get_side(location, true);
                    panels.push(this._toolbar);
                }
            }
            const set_layout = (side, model) => {
                var _a;
                const 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;
            };
            const set_layouts = (side, panels) => {
                const horizontal = side == "above" || side == "below";
                const layouts = [];
                for (const panel of panels) {
                    if ((0, types_1.isArray)(panel)) {
                        const items = panel.map((subpanel) => {
                            const item = set_layout(side, subpanel);
                            if (item == null)
                                return undefined;
                            if (subpanel instanceof toolbar_panel_1.ToolbarPanel) {
                                const dim = horizontal ? "width_policy" : "height_policy";
                                item.set_sizing(Object.assign(Object.assign({}, item.sizing), { [dim]: "min" }));
                            }
                            return item;
                        }).filter((item) => item != null);
                        let layout;
                        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 {
                        const layout = set_layout(side, panel);
                        if (layout != null)
                            layouts.push(layout);
                    }
                }
                return layouts;
            };
            const min_border = (_a = this.model.min_border) !== null && _a !== void 0 ? _a : 0;
            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,
            };
            const center_panel = new alignments_1.NodeLayout();
            const top_panel = new alignments_1.VStack();
            const bottom_panel = new alignments_1.VStack();
            const left_panel = new alignments_1.HStack();
            const right_panel = new alignments_1.HStack();
            const inner_top_panel = new alignments_1.VStack();
            const inner_bottom_panel = new alignments_1.VStack();
            const inner_left_panel = new alignments_1.HStack();
            const inner_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;
            inner_top_panel.absolute = true;
            inner_bottom_panel.absolute = true;
            inner_left_panel.absolute = true;
            inner_right_panel.absolute = true;
            center_panel.children =
                this.model.center.filter((obj) => {
                    return obj instanceof annotation_1.Annotation;
                }).map((model) => {
                    var _a;
                    const view = this.renderer_view(model);
                    (_a = view.update_layout) === null || _a === void 0 ? void 0 : _a.call(view);
                    return view.layout;
                }).filter((layout) => {
                    return layout != null;
                });
            const { frame_width, frame_height } = this.model;
            center_panel.set_sizing(Object.assign(Object.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((bbox) => this.frame.set_geometry(bbox));
            top_panel.children = (0, array_1.reversed)(set_layouts("above", outer_above));
            bottom_panel.children = set_layouts("below", outer_below);
            left_panel.children = (0, array_1.reversed)(set_layouts("left", outer_left));
            right_panel.children = set_layouts("right", outer_right);
            inner_top_panel.children = set_layouts("above", inner_above);
            inner_bottom_panel.children = set_layouts("below", inner_below);
            inner_left_panel.children = set_layouts("left", inner_left);
            inner_right_panel.children = set_layouts("right", inner_right);
            top_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: layout.min_border.top*/ });
            bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: layout.min_width.bottom*/ });
            left_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: layout.min_width.left*/ });
            right_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: layout.min_width.right*/ });
            inner_top_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            inner_bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            inner_left_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            inner_right_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            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;
            if (inner_top_panel.children.length != 0)
                layout.inner_top_panel = inner_top_panel;
            if (inner_bottom_panel.children.length != 0)
                layout.inner_bottom_panel = inner_bottom_panel;
            if (inner_left_panel.children.length != 0)
                layout.inner_left_panel = inner_left_panel;
            if (inner_right_panel.children.length != 0)
                layout.inner_right_panel = inner_right_panel;
            this.layout = layout;
        }
        _measure_layout() {
            const { frame_width, frame_height } = this.model;
            const frame = {
                width: frame_width == null ? "1fr" : (0, dom_1.px)(frame_width),
                height: frame_height == null ? "1fr" : (0, dom_1.px)(frame_height),
            };
            const { layout } = this;
            const top = layout.top_panel.measure({ width: Infinity, height: Infinity });
            const bottom = layout.bottom_panel.measure({ width: Infinity, height: Infinity });
            const left = layout.left_panel.measure({ width: Infinity, height: Infinity });
            const right = layout.right_panel.measure({ width: Infinity, height: Infinity });
            const top_height = max(top.height, layout.min_border.top);
            const bottom_height = max(bottom.height, layout.min_border.bottom);
            const left_width = max(left.width, layout.min_border.left);
            const right_width = max(right.width, layout.min_border.right);
            this._computed_style.replace(`
      :host {
        grid-template-rows: ${top_height}px ${frame.height} ${bottom_height}px;
        grid-template-columns: ${left_width}px ${frame.width} ${right_width}px;
      }
    `);
        }
        get axis_views() {
            const views = [];
            for (const [, renderer_view] of this.renderer_views) {
                if (renderer_view instanceof axis_1.AxisView)
                    views.push(renderer_view);
            }
            return views;
        }
        update_range(range_info, options) {
            this.pause();
            this._range_manager.update(range_info, options);
            this.unpause();
        }
        reset_range() {
            this.pause();
            this._range_manager.reset();
            this.unpause();
            this.trigger_ranges_update_event();
        }
        trigger_ranges_update_event(extra_ranges = []) {
            /**
             * Emits `RangesUpdate` event on all plots linked by all
             * ranges managed by this plot's range manager and linked
             * by additional context dependent ranges (`extra_ranges`).
             */
            const { x_ranges, y_ranges } = this._range_manager.ranges();
            const ranges = [...x_ranges, ...y_ranges, ...extra_ranges];
            const linked_plots = new Set(ranges.flatMap((r) => [...r.plots]));
            for (const plot_view of linked_plots) {
                const { x_range, y_range } = plot_view.model;
                const event = new bokeh_events_2.RangesUpdate(x_range.start, x_range.end, y_range.start, y_range.end);
                plot_view.model.trigger_event(event);
            }
        }
        get_selection() {
            const selection = new Map();
            for (const renderer of this.model.data_renderers) {
                const { selected } = renderer.selection_manager.source;
                selection.set(renderer, selected);
            }
            return selection;
        }
        update_selection(selections) {
            for (const renderer of this.model.data_renderers) {
                const ds = renderer.selection_manager.source;
                if (selections != null) {
                    const selection = selections.get(renderer);
                    if (selection != null) {
                        ds.selected.update(selection, true);
                    }
                }
                else
                    ds.selection_manager.clear();
            }
        }
        reset_selection() {
            this.update_selection(null);
        }
        _invalidate_layout_if_needed() {
            const needs_layout = (() => {
                var _a, _b;
                for (const panel of this.model.side_panels) {
                    const view = this.renderer_views.get(panel);
                    if ((_b = (_a = view.layout) === null || _a === void 0 ? void 0 : _a.has_size_changed()) !== null && _b !== void 0 ? _b : false) {
                        this.invalidate_painters(view);
                        return true;
                    }
                }
                return false;
            })();
            if (needs_layout) {
                this.compute_layout();
            }
        }
        get_renderer_views() {
            return this.computed_renderers.map((r) => this.renderer_views.get(r));
        }
        *_compute_renderers() {
            const { above, below, left, right, center, renderers } = this.model;
            yield* renderers;
            yield* above;
            yield* below;
            yield* left;
            yield* right;
            yield* center;
            if (this._title != null)
                yield this._title;
            if (this._toolbar != null)
                yield this._toolbar;
            for (const [, view] of this.tool_views) {
                yield* view.overlays;
            }
        }
        async build_renderer_views() {
            this.computed_renderers = [...this._compute_renderers()];
            await (0, build_views_1.build_views)(this.renderer_views, this.computed_renderers, { parent: this });
        }
        async build_tool_views() {
            const tool_models = (0, iterator_1.flat_map)(this.model.toolbar.tools, (item) => item instanceof tool_proxy_1.ToolProxy ? item.tools : [item]);
            const { created } = await (0, build_views_1.build_views)(this.tool_views, [...tool_models], { parent: this });
            created.map((tool_view) => this.canvas_view.ui_event_bus.register_tool(tool_view));
        }
        connect_signals() {
            super.connect_signals();
            const { extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales } = this.model.properties;
            this.on_change([extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales], () => {
                this.frame.x_range = this.model.x_range;
                this.frame.y_range = this.model.y_range;
                this.frame.in_x_scale = this.model.x_scale;
                this.frame.in_y_scale = this.model.y_scale;
                this.frame.extra_x_ranges = this.model.extra_x_ranges;
                this.frame.extra_y_ranges = this.model.extra_y_ranges;
                this.frame.extra_x_scales = this.model.extra_x_scales;
                this.frame.extra_y_scales = this.model.extra_y_scales;
                this.frame.configure_scales();
            });
            const { above, below, left, right, center, renderers } = this.model.properties;
            const panels = [above, below, left, right, center];
            this.on_change(renderers, async () => {
                await this.build_renderer_views();
            });
            this.on_change(panels, async () => {
                await this.build_renderer_views();
                this.invalidate_layout();
            });
            this.connect(this.model.toolbar.properties.tools.change, async () => {
                await this.build_tool_views();
                await this.build_renderer_views();
            });
            const { x_ranges, y_ranges } = this.frame;
            for (const [, range] of x_ranges) {
                this.connect(range.change, () => { this.request_paint("everything"); });
            }
            for (const [, range] of y_ranges) {
                this.connect(range.change, () => { this.request_paint("everything"); });
            }
            this.connect(this.model.change, () => this.request_paint("everything"));
            this.connect(this.model.reset, () => this.reset());
            const { toolbar_location } = this.model.properties;
            this.on_change(toolbar_location, async () => {
                const { toolbar_location } = this.model;
                if (this._toolbar != null) {
                    if (toolbar_location != null) {
                        this._toolbar.toolbar.location = toolbar_location;
                    }
                    else {
                        this._toolbar = undefined;
                        await this.build_renderer_views();
                    }
                }
                else {
                    if (toolbar_location != null) {
                        const { toolbar, toolbar_inner } = this.model;
                        this._toolbar = new toolbar_panel_1.ToolbarPanel({ toolbar });
                        toolbar.location = toolbar_location;
                        toolbar.inner = toolbar_inner;
                        await this.build_renderer_views();
                    }
                }
                this.invalidate_layout();
            });
            const { hold_render } = this.model.properties;
            this.on_change(hold_render, () => this._hold_render_changed());
        }
        has_finished() {
            if (!super.has_finished())
                return false;
            if (this.model.visible) {
                for (const [, renderer_view] of this.renderer_views) {
                    if (!renderer_view.has_finished())
                        return false;
                }
            }
            return true;
        }
        _after_layout() {
            var _a;
            super._after_layout();
            this.unpause(true);
            const left = this.layout.left_panel.bbox;
            const right = this.layout.right_panel.bbox;
            const center = this.layout.center_panel.bbox;
            const top = this.layout.top_panel.bbox;
            const bottom = this.layout.bottom_panel.bbox;
            const { bbox } = this;
            const top_height = top.bottom;
            const bottom_height = bbox.height - bottom.top;
            const left_width = left.right;
            const right_width = bbox.width - right.left;
            // TODO: don't replace here; inject stylesheet?
            this.canvas.style.replace(`
      .bk-layer.bk-events {
        display: grid;
        grid-template-areas:
          ".    above  .    "
          "left center right"
          ".    below  .    ";
        grid-template-rows: ${(0, dom_1.px)(top_height)} ${(0, dom_1.px)(center.height)} ${(0, dom_1.px)(bottom_height)};
        grid-template-columns: ${(0, dom_1.px)(left_width)} ${(0, dom_1.px)(center.width)} ${(0, dom_1.px)(right_width)};
      }
    `);
            for (const [, child_view] of this.renderer_views) {
                if (child_view instanceof annotation_1.AnnotationView)
                    (_a = child_view.after_layout) === null || _a === void 0 ? void 0 : _a.call(child_view);
            }
            this.model.setv({
                inner_width: Math.round(this.frame.bbox.width),
                inner_height: Math.round(this.frame.bbox.height),
                outer_width: Math.round(this.bbox.width),
                outer_height: Math.round(this.bbox.height),
            }, { no_change: true });
            if (this.model.match_aspect) {
                this.pause();
                this._range_manager.update_dataranges();
                this.unpause(true);
            }
            if (!this._outer_bbox.equals(this.bbox)) {
                this.canvas_view.resize(); // XXX temporary hack
                this._outer_bbox = this.bbox;
                this._invalidate_all = true;
                this._needs_paint = true;
            }
            const { inner_bbox } = this.layout;
            if (!this._inner_bbox.equals(inner_bbox)) {
                this._inner_bbox = inner_bbox;
                this._invalidate_all = true;
                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();
            }
        }
        repaint() {
            this._invalidate_layout_if_needed();
            this.paint();
        }
        paint() {
            if (this.is_paused)
                return;
            if (this.is_displayed) {
                logging_1.logger.trace(`${this.toString()}.paint()`);
                this._actual_paint();
            }
            else {
                // This is possibly the first render cycle, but plot isn't displayed,
                // so all renderers have to be manually marked as finished, because
                // their `render()` method didn't run.
                for (const renderer_view of this.computed_renderer_views) {
                    renderer_view.mark_finished();
                }
            }
            if (this._needs_notify) {
                this._needs_notify = false;
                this.notify_finished();
            }
        }
        _actual_paint() {
            var _a;
            logging_1.logger.trace(`${this.toString()}._actual_paint ${this._render_count} start`);
            const { document } = this.model;
            if (document != null) {
                const interactive_duration = document.interactive_duration();
                if (interactive_duration >= 0 && interactive_duration < this.model.lod_interval) {
                    setTimeout(() => {
                        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_if_needed();
            }
            let do_primary = false;
            let do_overlays = false;
            if (this._invalidate_all) {
                do_primary = true;
                do_overlays = true;
            }
            else {
                for (const painter of this._invalidated_painters) {
                    const { level } = painter.model;
                    if (level != "overlay")
                        do_primary = true;
                    else
                        do_overlays = true;
                    if (do_primary && do_overlays)
                        break;
                }
            }
            this._invalidated_painters.clear();
            this._invalidate_all = false;
            const frame_box = [
                this.frame.bbox.left,
                this.frame.bbox.top,
                this.frame.bbox.width,
                this.frame.bbox.height,
            ];
            const { primary, overlays } = this.canvas_view;
            if (do_primary) {
                primary.prepare();
                this.canvas_view.prepare_webgl(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 = (_a = this._range_manager.compute_initial()) !== null && _a !== void 0 ? _a : undefined;
            }
            this._needs_paint = false;
            this.repainted.emit();
            logging_1.logger.trace(`${this.toString()}._actual_paint ${this._render_count} end`);
            this._render_count++;
        }
        _paint_levels(ctx, level, clip_region, global_clip) {
            for (const renderer of this.computed_renderers) {
                if (renderer.level != level)
                    continue;
                const renderer_view = this.renderer_views.get(renderer);
                ctx.save();
                if (global_clip || renderer_view.needs_clip) {
                    ctx.beginPath();
                    ctx.rect(...clip_region);
                    ctx.clip();
                }
                renderer_view.render();
                ctx.restore();
                if (renderer_view.has_webgl) {
                    this.canvas_view.blit_webgl(ctx);
                }
            }
        }
        paint_layout(ctx, layout) {
            const { x, y, width, height } = layout.bbox;
            ctx.strokeStyle = "blue";
            ctx.strokeRect(x, y, width, height);
            for (const child of layout) {
                ctx.save();
                if (!layout.absolute)
                    ctx.translate(x, y);
                this.paint_layout(ctx, child);
                ctx.restore();
            }
        }
        _paint_empty(ctx, frame_box) {
            const [cx, cy, cw, ch] = [0, 0, this.bbox.width, this.bbox.height];
            const [fx, fy, fw, fh] = frame_box;
            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);
            }
        }
        _paint_outline(ctx, frame_box) {
            if (this.visuals.outline_line.doit) {
                ctx.save();
                this.visuals.outline_line.set_value(ctx);
                let [x0, y0, w, h] = frame_box;
                // 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.bbox.width) {
                    w -= 1;
                }
                if (y0 + h == this.bbox.height) {
                    h -= 1;
                }
                ctx.strokeRect(x0, y0, w, h);
                ctx.restore();
            }
        }
        export(type = "auto", hidpi = true) {
            const output_backend = (() => {
                switch (type) {
                    case "auto": return this.canvas_view.model.output_backend;
                    case "png": return "canvas";
                    case "svg": return "svg";
                }
            })();
            const composite = new canvas_2.CanvasLayer(output_backend, hidpi);
            const { width, height } = this.bbox;
            composite.resize(width, height);
            if (width != 0 && height != 0) {
                const { canvas } = this.canvas_view.compose();
                composite.ctx.drawImage(canvas, 0, 0);
            }
            return composite;
        }
        serializable_state() {
            const _a = super.serializable_state(), { children } = _a, state = tslib_1.__rest(_a, ["children"]);
            const renderers = this.get_renderer_views()
                .filter((view) => view.model.syncable) // filters out computed renderers
                .map((view) => view.serializable_state())
                .filter((item) => item.bbox != null);
            // TODO: remove this when frame is generalized
            const frame = { type: "CartesianFrame", bbox: this.frame.bbox };
            return Object.assign(Object.assign({}, state), { children: [...children !== null && children !== void 0 ? children : [], frame, ...renderers] });
        }
        _hold_render_changed() {
            if (this.model.hold_render) {
                this.pause();
            }
            else {
                this.unpause();
            }
        }
    }
    exports.PlotView = PlotView;
    PlotView.__name__ = "PlotView";
},
/* core/util/throttle.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    function throttle(func, wait) {
        let timeout = null;
        let request = null;
        let previous = 0;
        let pending = false;
        let resolver;
        const fn = function () {
            return new Promise((resolve, reject) => {
                resolver = resolve;
                const later = function () {
                    previous = Date.now();
                    timeout = null;
                    request = null;
                    pending = false;
                    try {
                        func();
                        resolve();
                    }
                    catch (error) {
                        reject(error);
                    }
                };
                const now = Date.now();
                const remaining = wait - (now - previous);
                if (remaining <= 0 && !pending) {
                    if (timeout != null) {
                        clearTimeout(timeout);
                    }
                    pending = true;
                    request = requestAnimationFrame(later);
                }
                else if (timeout == null && !pending) {
                    timeout = setTimeout(() => request = requestAnimationFrame(later), remaining);
                }
                else {
                    resolve();
                }
            });
        };
        fn.stop = function () {
            if (timeout != null)
                clearTimeout(timeout);
            if (request != null)
                cancelAnimationFrame(request);
            resolver();
        };
        return fn;
    }
    exports.throttle = throttle;
},
/* models/plots/range_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_range1d_1 = require(95) /* ../ranges/data_range1d */;
    const logging_1 = require(19) /* ../../core/logging */;
    class RangeManager {
        constructor(parent) {
            this.invalidate_dataranges = true;
            this.parent = parent;
        }
        get frame() {
            return this.parent.frame;
        }
        update(range_info, options = {}) {
            var _a;
            const range_state = new Map();
            for (const [range, interval] of range_info.xrs) {
                range_state.set(range, interval);
            }
            for (const [range, interval] of range_info.yrs) {
                range_state.set(range, interval);
            }
            if ((_a = options.scrolling) !== null && _a !== void 0 ? _a : false) {
                this._update_ranges_together(range_state); // apply interval bounds while keeping aspect
            }
            this._update_ranges_individually(range_state, options);
        }
        ranges() {
            const x_ranges = new Set();
            const y_ranges = new Set();
            for (const range of this.frame.x_ranges.values()) {
                x_ranges.add(range);
            }
            for (const range of this.frame.y_ranges.values()) {
                y_ranges.add(range);
            }
            for (const renderer of this.parent.model.data_renderers) {
                const { coordinates } = renderer;
                if (coordinates != null) {
                    x_ranges.add(coordinates.x_source);
                    y_ranges.add(coordinates.y_source);
                }
            }
            return {
                x_ranges: [...x_ranges],
                y_ranges: [...y_ranges],
            };
        }
        reset() {
            const { x_ranges, y_ranges } = this.ranges();
            for (const range of x_ranges) {
                range.reset();
            }
            for (const range of y_ranges) {
                range.reset();
            }
            this.update_dataranges();
        }
        _update_dataranges(frame) {
            // Update any DataRange1ds here
            const bounds = new Map();
            const log_bounds = new Map();
            let calculate_log_bounds = false;
            for (const [, xr] of frame.x_ranges) {
                if (xr instanceof data_range1d_1.DataRange1d && xr.scale_hint == "log")
                    calculate_log_bounds = true;
            }
            for (const [, yr] of frame.y_ranges) {
                if (yr instanceof data_range1d_1.DataRange1d && yr.scale_hint == "log")
                    calculate_log_bounds = true;
            }
            for (const renderer of this.parent.auto_ranged_renderers) {
                const bds = renderer.bounds();
                bounds.set(renderer.model, bds);
                if (calculate_log_bounds) {
                    const log_bds = renderer.log_bounds();
                    log_bounds.set(renderer.model, log_bds);
                }
            }
            let follow_enabled = false;
            let has_bounds = false;
            //const {width, height} = frame.bbox
            const width = frame.x_target.span;
            const height = frame.y_target.span;
            let r;
            if (this.parent.model.match_aspect !== false && width != 0 && height != 0)
                r = (1 / this.parent.model.aspect_scale) * (width / height);
            for (const [, xr] of frame.x_ranges) {
                if (xr instanceof data_range1d_1.DataRange1d) {
                    const bounds_to_use = xr.scale_hint == "log" ? log_bounds : bounds;
                    xr.update(bounds_to_use, 0, this.parent, r);
                    if (xr.follow != null) {
                        follow_enabled = true;
                    }
                }
                if (xr.bounds != null)
                    has_bounds = true;
            }
            for (const [, yr] of frame.y_ranges) {
                if (yr instanceof data_range1d_1.DataRange1d) {
                    const bounds_to_use = yr.scale_hint == "log" ? log_bounds : bounds;
                    yr.update(bounds_to_use, 1, this.parent, r);
                    if (yr.follow != null) {
                        follow_enabled = true;
                    }
                }
                if (yr.bounds != null)
                    has_bounds = true;
            }
            if (follow_enabled && has_bounds) {
                logging_1.logger.warn("Follow enabled so bounds are unset.");
                for (const [, xr] of frame.x_ranges) {
                    xr.bounds = null;
                }
                for (const [, yr] of frame.y_ranges) {
                    yr.bounds = null;
                }
            }
        }
        update_dataranges() {
            this._update_dataranges(this.frame);
            for (const renderer of this.parent.auto_ranged_renderers) {
                const { coordinates } = renderer.model;
                if (coordinates != null)
                    this._update_dataranges(coordinates);
            }
            if (this.compute_initial() != null)
                this.invalidate_dataranges = false;
        }
        compute_initial() {
            // check for good values for ranges before setting initial range
            let good_vals = true;
            const { x_ranges, y_ranges } = this.frame;
            const xrs = new Map();
            const yrs = new Map();
            for (const [, range] of x_ranges) {
                const { start, end } = range;
                if (isNaN(start + end)) {
                    good_vals = false;
                    break;
                }
                xrs.set(range, { start, end });
            }
            if (good_vals) {
                for (const [, range] of y_ranges) {
                    const { start, end } = range;
                    if (isNaN(start + end)) {
                        good_vals = false;
                        break;
                    }
                    yrs.set(range, { start, end });
                }
            }
            if (good_vals)
                return { xrs, yrs };
            else {
                logging_1.logger.warn("could not set initial ranges");
                return null;
            }
        }
        _update_ranges_together(range_state) {
            // Get weight needed to scale the diff of the range to honor interval limits
            let weight = 1.0;
            for (const [rng, range_info] of range_state) {
                weight = Math.min(weight, this._get_weight_to_constrain_interval(rng, range_info));
            }
            // Apply shared weight to all ranges
            if (weight < 1) {
                for (const [rng, range_info] of range_state) {
                    range_info.start = weight * range_info.start + (1 - weight) * rng.start;
                    range_info.end = weight * range_info.end + (1 - weight) * rng.end;
                }
            }
        }
        _update_ranges_individually(range_state, options = {}) {
            var _a, _b, _c;
            const panning = (_a = options.panning) !== null && _a !== void 0 ? _a : false;
            const scrolling = (_b = options.scrolling) !== null && _b !== void 0 ? _b : false;
            const maintain_focus = (_c = options.maintain_focus) !== null && _c !== void 0 ? _c : false;
            let hit_bound = false;
            for (const [rng, range_info] of range_state) {
                // Limit range interval first. Note that for scroll events,
                // the interval has already been limited for all ranges simultaneously
                if (!scrolling) {
                    const 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) {
                    const [min, max] = rng.computed_bounds;
                    const new_interval = Math.abs(range_info.end - range_info.start);
                    if (rng.is_reversed) {
                        if (min > range_info.end) {
                            hit_bound = true;
                            range_info.end = min;
                            if (panning || scrolling) {
                                range_info.start = min + new_interval;
                            }
                        }
                        if (max < range_info.start) {
                            hit_bound = true;
                            range_info.start = max;
                            if (panning || scrolling) {
                                range_info.end = max - new_interval;
                            }
                        }
                    }
                    else {
                        if (min > range_info.start) {
                            hit_bound = true;
                            range_info.start = min;
                            if (panning || scrolling) {
                                range_info.end = min + new_interval;
                            }
                        }
                        if (max < range_info.end) {
                            hit_bound = true;
                            range_info.end = max;
                            if (panning || scrolling) {
                                range_info.start = max - new_interval;
                            }
                        }
                    }
                }
            }
            // 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 && maintain_focus)
                return;
            for (const [rng, range_info] of range_state) {
                rng.have_updated_interactively = true;
                if (rng.start != range_info.start || rng.end != range_info.end)
                    rng.setv(range_info);
            }
        }
        _get_weight_to_constrain_interval(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)
            const { min_interval } = rng;
            let { max_interval } = rng;
            // 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
                const [min, max] = rng.bounds;
                if (min != null && max != null) {
                    const max_interval2 = Math.abs(max - min);
                    max_interval = max_interval != null ? Math.min(max_interval, max_interval2) : max_interval2;
                }
            }
            let weight = 1.0;
            if (min_interval != null || max_interval != null) {
                const old_interval = Math.abs(rng.end - rng.start);
                const 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;
        }
    }
    exports.RangeManager = RangeManager;
    RangeManager.__name__ = "RangeManager";
},
/* models/plots/state_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const signaling_1 = require(15) /* ../../core/signaling */;
    class StateManager {
        constructor(parent, initial_state) {
            this.history = [];
            this.index = -1;
            this.parent = parent;
            this.initial_state = initial_state;
            this.changed = new signaling_1.Signal0(this.parent, "state_changed");
        }
        _do_state_change(index) {
            const state = index in this.history ? 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;
        }
        peek() {
            return this.can_undo ? this.history[this.index] : null;
        }
        push(type, new_state) {
            const { history, index } = this;
            const prev_state = index in history ? history[index].state : {};
            const state = Object.assign(Object.assign(Object.assign({}, this.initial_state), prev_state), new_state);
            this.history = this.history.slice(0, this.index + 1);
            this.history.push({ type, state });
            this.index = this.history.length - 1;
            this.changed.emit();
        }
        clear() {
            this.history = [];
            this.index = -1;
            this.changed.emit();
        }
        undo() {
            if (this.can_undo) {
                this.index -= 1;
                const state = this._do_state_change(this.index);
                this.changed.emit();
                return state;
            }
            return null;
        }
        redo() {
            if (this.can_redo) {
                this.index += 1;
                const state = this._do_state_change(this.index);
                this.changed.emit();
                return state;
            }
            return null;
        }
        get can_undo() {
            return this.index >= 0;
        }
        get can_redo() {
            return this.index < this.history.length - 1;
        }
    }
    exports.StateManager = StateManager;
    StateManager.__name__ = "StateManager";
},
/* styles/plots.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.Canvas = "bk-Canvas";
    exports.default = `:host{display:grid;grid-template-areas:".    above  .    " "left center right" ".    below  .    ";grid-template-rows:0px 1fr 0px;grid-template-columns:0px 1fr 0px;}.bk-Canvas{grid-row-start:1;grid-row-end:span 3;grid-column-start:1;grid-column-end:span 3;}`;
},
/* models/plots/gmap_plot_canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const logging_1 = require(19) /* ../../core/logging */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const dom_1 = require(56) /* ../../core/dom */;
    const projections_1 = require(107) /* ../../core/util/projections */;
    const plot_canvas_1 = require(408) /* ./plot_canvas */;
    function has_maps_API() {
        return typeof google != "undefined" && typeof google.maps != "undefined";
    }
    const gmaps_ready = new signaling_1.Signal0({}, "gmaps_ready");
    const load_google_api = function (api_key, api_version) {
        window._bokeh_gmaps_callback = () => gmaps_ready.emit();
        const enc = encodeURIComponent;
        const 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);
    };
    class GMapPlotView extends plot_canvas_1.PlotView {
        initialize() {
            super.initialize();
            this._tiles_loaded = false;
            this.zoom_count = 0;
            const { zoom, lat, lng } = this.model.map_options;
            this.initial_zoom = zoom;
            this.initial_lat = lat;
            this.initial_lng = lng;
            const decoder = new TextDecoder("utf-8");
            this._api_key = decoder.decode(this.model.api_key);
            if (this._api_key == "") {
                const 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.`);
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.map_el = (0, dom_1.div)({ style: { position: "absolute" } });
            this.canvas_view.add_underlay(this.map_el);
            if (!has_maps_API()) {
                if (typeof window._bokeh_gmaps_callback === "undefined") {
                    const { api_version } = this.model;
                    load_google_api(this._api_key, api_version);
                }
                gmaps_ready.connect(() => {
                    this._build_map();
                    this.request_paint("everything");
                });
            }
            else
                this._build_map();
        }
        remove() {
            (0, dom_1.remove)(this.map_el);
            super.remove();
        }
        update_range(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.reset_range();
                // 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.update_range(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.update_range(range_info, options);
                const zoom_change = range_info.factor < 0 ? -1 : 1;
                const old_map_zoom = this.map.getZoom();
                if (old_map_zoom != null) {
                    const 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
                        const [proj_xstart, proj_xend] = this._get_projected_bounds();
                        if (proj_xend - proj_xstart < 0) {
                            this.map.setZoom(old_map_zoom);
                        }
                    }
                }
                this.unpause();
            }
            // Finally re-center
            this._set_bokeh_ranges();
        }
        _build_map() {
            const { maps } = google;
            this.map_types = {
                satellite: maps.MapTypeId.SATELLITE,
                terrain: maps.MapTypeId.TERRAIN,
                roadmap: maps.MapTypeId.ROADMAP,
                hybrid: maps.MapTypeId.HYBRID,
            };
            const mo = this.model.map_options;
            const 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 = 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", () => 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", () => this._set_bokeh_ranges());
            maps.event.addListenerOnce(this.map, "tilesloaded", () => this._render_finished());
            // wire up listeners so that changes to properties are reflected
            this.connect(this.model.properties.map_options.change, () => this._update_options());
            this.connect(this.model.map_options.properties.styles.change, () => this._update_styling());
            this.connect(this.model.map_options.properties.lat.change, () => this._update_center("lat"));
            this.connect(this.model.map_options.properties.lng.change, () => this._update_center("lng"));
            this.connect(this.model.map_options.properties.zoom.change, () => this._update_zoom());
            this.connect(this.model.map_options.properties.map_type.change, () => this._update_map_type());
            this.connect(this.model.map_options.properties.scale_control.change, () => this._update_scale_control());
            this.connect(this.model.map_options.properties.tilt.change, () => this._update_tilt());
        }
        _render_finished() {
            this._tiles_loaded = true;
            this.notify_finished();
        }
        has_finished() {
            return super.has_finished() && this._tiles_loaded === true;
        }
        _get_latlon_bounds() {
            const bounds = this.map.getBounds();
            const top_right = bounds.getNorthEast();
            const bottom_left = bounds.getSouthWest();
            const xstart = bottom_left.lng();
            const xend = top_right.lng();
            const ystart = bottom_left.lat();
            const yend = top_right.lat();
            return [xstart, xend, ystart, yend];
        }
        _get_projected_bounds() {
            const [xstart, xend, ystart, yend] = this._get_latlon_bounds();
            const [proj_xstart, proj_ystart] = projections_1.wgs84_mercator.compute(xstart, ystart);
            const [proj_xend, proj_yend] = projections_1.wgs84_mercator.compute(xend, yend);
            return [proj_xstart, proj_xend, proj_ystart, proj_yend];
        }
        _set_bokeh_ranges() {
            const [proj_xstart, proj_xend, proj_ystart, proj_yend] = this._get_projected_bounds();
            this.frame.x_range.setv({ start: proj_xstart, end: proj_xend });
            this.frame.y_range.setv({ start: proj_ystart, end: proj_yend });
        }
        _update_center(fld) {
            var _a;
            const 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();
            }
        }
        _update_map_type() {
            this.map.setOptions({ mapTypeId: this.map_types[this.model.map_options.map_type] });
        }
        _update_scale_control() {
            this.map.setOptions({ scaleControl: this.model.map_options.scale_control });
        }
        _update_tilt() {
            this.map.setOptions({ tilt: this.model.map_options.tilt });
        }
        _update_options() {
            this._update_styling();
            this._update_center("lat");
            this._update_center("lng");
            this._update_zoom();
            this._update_map_type();
        }
        _update_styling() {
            const { styles } = this.model.map_options;
            this.map.setOptions({ styles: styles != null ? JSON.parse(styles) : null });
        }
        _update_zoom() {
            this.map.setOptions({ zoom: this.model.map_options.zoom });
            this._set_bokeh_ranges();
        }
        _after_layout() {
            super._after_layout();
            const { left, top, width, height } = this.frame.bbox;
            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`;
        }
    }
    exports.GMapPlotView = GMapPlotView;
    GMapPlotView.__name__ = "GMapPlotView";
},
/* models/plots/gmap.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const gmap_plot_1 = require(406) /* ./gmap_plot */;
    class GMapView extends gmap_plot_1.GMapPlotView {
        // TODO: remove this before bokeh 3.0 and update *.blf files
        serializable_state() {
            const state = super.serializable_state();
            return Object.assign(Object.assign({}, state), { type: "GMapPlot" });
        }
    }
    exports.GMapView = GMapView;
    GMapView.__name__ = "GMapView";
    class GMap extends gmap_plot_1.GMapPlot {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GMap = GMap;
    _a = GMap;
    GMap.__name__ = "GMap";
    (() => {
        _a.prototype.default_view = GMapView;
    })();
},
/* models/plots/grid_plot.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(373) /* ../layouts/layout_dom */;
    const grid_box_1 = require(377) /* ../layouts/grid_box */;
    const kinds_1 = require(238) /* ../common/kinds */;
    const toolbar_1 = require(265) /* ../tools/toolbar */;
    const action_tool_1 = require(283) /* ../tools/actions/action_tool */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const enums_1 = require(20) /* ../../core/enums */;
    class GridPlotView extends layout_dom_1.LayoutDOMView {
        constructor() {
            super(...arguments);
            this._tool_views = new Map();
        }
        get toolbar_view() {
            return this.child_views.find((v) => v.model == this.model.toolbar);
        }
        get grid_box_view() {
            return this.child_views.find((v) => v.model == this._grid_box);
        }
        _update_location() {
            const location = this.model.toolbar_location;
            if (location == null)
                this.model.toolbar.visible = false;
            else
                this.model.toolbar.setv({ visible: true, location });
        }
        initialize() {
            super.initialize();
            this._update_location();
            const { children, rows, cols, spacing } = this.model;
            this._grid_box = new grid_box_1.GridBox({ children, rows, cols, spacing, sizing_mode: "inherit" });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this.build_tool_views();
        }
        connect_signals() {
            super.connect_signals();
            const { toolbar, toolbar_location, children, rows, cols, spacing } = this.model.properties;
            this.on_change(toolbar_location, () => {
                this._update_location();
                this.rebuild();
            });
            this.on_change([toolbar, children, rows, cols, spacing], () => {
                this.rebuild();
            });
            this.on_change(this.model.toolbar.properties.tools, async () => {
                await this.build_tool_views();
            });
            this.mouseenter.connect(() => {
                this.toolbar_view.set_visibility(true);
            });
            this.mouseleave.connect(() => {
                this.toolbar_view.set_visibility(false);
            });
        }
        remove() {
            (0, build_views_1.remove_views)(this._tool_views);
            super.remove();
        }
        async build_tool_views() {
            const tools = this.model.toolbar.tools.filter((tool) => tool instanceof action_tool_1.ActionTool);
            await (0, build_views_1.build_views)(this._tool_views, tools, { parent: this });
        }
        *children() {
            yield* super.children();
            yield* this._tool_views.values();
        }
        get child_models() {
            return [this.model.toolbar, this._grid_box];
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flex" };
        }
        _update_layout() {
            super._update_layout();
            const { location } = this.model.toolbar;
            const flex_direction = (() => {
                switch (location) {
                    case "above": return "column";
                    case "below": return "column-reverse";
                    case "left": return "row";
                    case "right": return "row-reverse";
                }
            })();
            this.style.append(":host", { flex_direction });
        }
    }
    exports.GridPlotView = GridPlotView;
    GridPlotView.__name__ = "GridPlotView";
    class GridPlot extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GridPlot = GridPlot;
    _a = GridPlot;
    GridPlot.__name__ = "GridPlot";
    (() => {
        _a.prototype.default_view = GridPlotView;
        _a.define(({ Array, Ref, Nullable }) => ({
            toolbar: [Ref(toolbar_1.Toolbar), () => new toolbar_1.Toolbar()],
            toolbar_location: [Nullable(enums_1.Location), "above"],
            children: [Array((0, kinds_1.GridChild)(layout_dom_1.LayoutDOM)), []],
            rows: [Nullable(kinds_1.TracksSizing), null],
            cols: [Nullable(kinds_1.TracksSizing), null],
            spacing: [kinds_1.GridSpacing, 0],
        }));
    })();
},
/* models/plots/figure.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const plot_1 = require(407) /* ./plot */;
    class FigureView extends plot_1.PlotView {
        // TODO: remove this before bokeh 3.0 and update *.blf files
        serializable_state() {
            const state = super.serializable_state();
            return Object.assign(Object.assign({}, state), { type: "Plot" });
        }
    }
    exports.FigureView = FigureView;
    FigureView.__name__ = "FigureView";
    class Figure extends plot_1.Plot {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Figure = Figure;
    _a = Figure;
    Figure.__name__ = "Figure";
    (() => {
        _a.prototype.default_view = FigureView;
    })();
},
/* models/policies/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(165) /* ./labeling */, exports);
},
/* models/random/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var park_miller_lcg_1 = require(419) /* ./park_miller_lcg */;
    __esExport("ParkMillerLCG", park_miller_lcg_1.ParkMillerLCG);
},
/* models/random/park_miller_lcg.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const random_generator_1 = require(402) /* ./random_generator */;
    const random_1 = require(271) /* ../../core/util/random */;
    class ParkMillerLCG extends random_generator_1.RandomGenerator {
        constructor(attrs) {
            super(attrs);
        }
        generator() {
            var _b;
            return new random_1.LCGRandom((_b = this.seed) !== null && _b !== void 0 ? _b : Date.now());
        }
    }
    exports.ParkMillerLCG = ParkMillerLCG;
    _a = ParkMillerLCG;
    ParkMillerLCG.__name__ = "ParkMillerLCG";
    (() => {
        _a.define(({ Int, Nullable }) => ({
            seed: [Nullable(Int), null],
        }));
    })();
},
/* models/renderers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var contour_renderer_1 = require(421) /* ./contour_renderer */;
    __esExport("ContourRenderer", contour_renderer_1.ContourRenderer);
    var glyph_renderer_1 = require(201) /* ./glyph_renderer */;
    __esExport("GlyphRenderer", glyph_renderer_1.GlyphRenderer);
    var graph_renderer_1 = require(422) /* ./graph_renderer */;
    __esExport("GraphRenderer", graph_renderer_1.GraphRenderer);
    var guide_renderer_1 = require(162) /* ./guide_renderer */;
    __esExport("GuideRenderer", guide_renderer_1.GuideRenderer);
    var renderer_1 = require(74) /* ./renderer */;
    __esExport("Renderer", renderer_1.Renderer);
    __esExport("RendererGroup", renderer_1.RendererGroup);
},
/* models/renderers/contour_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const data_renderer_1 = require(202) /* ./data_renderer */;
    const glyph_renderer_1 = require(201) /* ./glyph_renderer */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    class ContourRendererView extends data_renderer_1.DataRendererView {
        *children() {
            yield* super.children();
            yield this.fill_view;
            yield this.line_view;
        }
        get glyph_view() {
            if (this.fill_view.glyph.data_size > 0)
                return this.fill_view.glyph;
            else
                return this.line_view.glyph;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { parent } = this;
            const { fill_renderer, line_renderer } = this.model;
            this.fill_view = await (0, build_views_1.build_view)(fill_renderer, { parent });
            this.line_view = await (0, build_views_1.build_view)(line_renderer, { parent });
        }
        remove() {
            this.fill_view.remove();
            this.line_view.remove();
            super.remove();
        }
        _render() {
            this.fill_view.render();
            this.line_view.render();
        }
        renderer_view(renderer) {
            if (renderer instanceof glyph_renderer_1.GlyphRenderer) {
                if (renderer == this.fill_view.model)
                    return this.fill_view;
                if (renderer == this.line_view.model)
                    return this.line_view;
            }
            return super.renderer_view(renderer);
        }
    }
    exports.ContourRendererView = ContourRendererView;
    ContourRendererView.__name__ = "ContourRendererView";
    class ContourRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        get_selection_manager() {
            return this.fill_renderer.data_source.selection_manager;
        }
    }
    exports.ContourRenderer = ContourRenderer;
    _a = ContourRenderer;
    ContourRenderer.__name__ = "ContourRenderer";
    (() => {
        _a.prototype.default_view = ContourRendererView;
        _a.define(({ Array, Number, Ref }) => ({
            fill_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            line_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            levels: [Array(Number), []],
        }));
    })();
},
/* models/renderers/graph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const data_renderer_1 = require(202) /* ./data_renderer */;
    const glyph_renderer_1 = require(201) /* ./glyph_renderer */;
    const layout_provider_1 = require(366) /* ../graphs/layout_provider */;
    const graph_hit_test_policy_1 = require(365) /* ../graphs/graph_hit_test_policy */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const xy_glyph_1 = require(204) /* ../glyphs/xy_glyph */;
    const multi_line_1 = require(344) /* ../glyphs/multi_line */;
    const patches_1 = require(346) /* ../glyphs/patches */;
    class GraphRendererView extends data_renderer_1.DataRendererView {
        get glyph_view() {
            return this.node_view.glyph;
        }
        *children() {
            yield* super.children();
            yield this.edge_view;
            yield this.node_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.apply_coordinates();
            const { parent } = this;
            const { edge_renderer, node_renderer } = this.model;
            this.edge_view = await (0, build_views_1.build_view)(edge_renderer, { parent });
            this.node_view = await (0, build_views_1.build_view)(node_renderer, { parent });
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.layout_provider.change, () => {
                this.apply_coordinates();
                this.edge_view.set_data();
                this.node_view.set_data();
                this.request_render();
            });
        }
        apply_coordinates() {
            const { edge_renderer, node_renderer } = this.model;
            // 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`);
            }
            const edge_coords = this.model.layout_provider.edge_coordinates;
            const 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 };
        }
        remove() {
            this.edge_view.remove();
            this.node_view.remove();
            super.remove();
        }
        _render() {
            this.edge_view.render();
            this.node_view.render();
        }
        get has_webgl() {
            return this.edge_view.has_webgl || this.node_view.has_webgl;
        }
        renderer_view(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.renderer_view(renderer);
        }
    }
    exports.GraphRendererView = GraphRendererView;
    GraphRendererView.__name__ = "GraphRendererView";
    class GraphRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        get_selection_manager() {
            return this.node_renderer.data_source.selection_manager;
        }
    }
    exports.GraphRenderer = GraphRenderer;
    _a = GraphRenderer;
    GraphRenderer.__name__ = "GraphRenderer";
    (() => {
        _a.prototype.default_view = GraphRendererView;
        _a.define(({ Ref }) => ({
            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), () => new graph_hit_test_policy_1.NodesOnly()],
            inspection_policy: [Ref(graph_hit_test_policy_1.GraphHitTestPolicy), () => new graph_hit_test_policy_1.NodesOnly()],
        }));
    })();
},
/* models/selections/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(104) /* ./interaction_policy */, exports);
    var selection_1 = require(103) /* ./selection */;
    __esExport("Selection", selection_1.Selection);
},
/* models/selectors/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var by_id_1 = require(425) /* ./by_id */;
    __esExport("ByID", by_id_1.ByID);
    var by_class_1 = require(427) /* ./by_class */;
    __esExport("ByClass", by_class_1.ByClass);
    var by_css_1 = require(428) /* ./by_css */;
    __esExport("ByCSS", by_css_1.ByCSS);
    var by_xpath_1 = require(429) /* ./by_xpath */;
    __esExport("ByXPath", by_xpath_1.ByXPath);
},
/* models/selectors/by_id.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(426) /* ./selector */;
    class ByID extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(`#${this.query}`);
        }
    }
    exports.ByID = ByID;
    ByID.__name__ = "ByID";
},
/* models/selectors/selector.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    class Selector extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Selector = Selector;
    _a = Selector;
    Selector.__name__ = "Selector";
    (() => {
        _a.define(({ String }) => ({
            query: [String],
        }));
    })();
},
/* models/selectors/by_class.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(426) /* ./selector */;
    class ByClass extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(`.${this.query}`);
        }
    }
    exports.ByClass = ByClass;
    ByClass.__name__ = "ByClass";
},
/* models/selectors/by_css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(426) /* ./selector */;
    class ByCSS extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(this.query);
        }
    }
    exports.ByCSS = ByCSS;
    ByCSS.__name__ = "ByCSS";
},
/* models/selectors/by_xpath.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(426) /* ./selector */;
    class ByXPath extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return document.evaluate(this.query, target).iterateNext();
        }
    }
    exports.ByXPath = ByXPath;
    ByXPath.__name__ = "ByXPath";
},
/* models/sources/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var server_sent_data_source_1 = require(431) /* ./server_sent_data_source */;
    __esExport("ServerSentDataSource", server_sent_data_source_1.ServerSentDataSource);
    var ajax_data_source_1 = require(433) /* ./ajax_data_source */;
    __esExport("AjaxDataSource", ajax_data_source_1.AjaxDataSource);
    var column_data_source_1 = require(106) /* ./column_data_source */;
    __esExport("ColumnDataSource", column_data_source_1.ColumnDataSource);
    var columnar_data_source_1 = require(101) /* ./columnar_data_source */;
    __esExport("ColumnarDataSource", columnar_data_source_1.ColumnarDataSource);
    var cds_view_1 = require(220) /* ./cds_view */;
    __esExport("CDSView", cds_view_1.CDSView);
    var data_source_1 = require(105) /* ./data_source */;
    __esExport("DataSource", data_source_1.DataSource);
    var geojson_data_source_1 = require(434) /* ./geojson_data_source */;
    __esExport("GeoJSONDataSource", geojson_data_source_1.GeoJSONDataSource);
    var web_data_source_1 = require(432) /* ./web_data_source */;
    __esExport("WebDataSource", web_data_source_1.WebDataSource);
},
/* models/sources/server_sent_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const web_data_source_1 = require(432) /* ./web_data_source */;
    class ServerSentDataSource extends web_data_source_1.WebDataSource {
        constructor(attrs) {
            super(attrs);
            this.initialized = false;
        }
        setup() {
            if (!this.initialized) {
                this.initialized = true;
                const source = new EventSource(this.data_url);
                source.onmessage = async (event) => {
                    var _a;
                    await this.load_data(JSON.parse(event.data), this.mode, (_a = this.max_size) !== null && _a !== void 0 ? _a : undefined);
                };
            }
        }
    }
    exports.ServerSentDataSource = ServerSentDataSource;
    ServerSentDataSource.__name__ = "ServerSentDataSource";
},
/* models/sources/web_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const column_data_source_1 = require(106) /* ./column_data_source */;
    const enums_1 = require(20) /* ../../core/enums */;
    class WebDataSource extends column_data_source_1.ColumnDataSource {
        constructor(attrs) {
            super(attrs);
        }
        get_column(name) {
            return name in this.data ? this.data[name] : [];
        }
        get_length() {
            var _b;
            return (_b = super.get_length()) !== null && _b !== void 0 ? _b : 0;
        }
        initialize() {
            super.initialize();
            this.setup();
        }
        async load_data(raw_data, mode, max_size) {
            const { adapter } = this;
            let data;
            if (adapter != null)
                data = await adapter.execute(this, { response: raw_data });
            else
                data = raw_data;
            switch (mode) {
                case "replace": {
                    this.data = data;
                    break;
                }
                case "append": {
                    const original_data = this.data;
                    for (const column of this.columns()) {
                        // XXX: support typed arrays
                        const old_col = Array.from(original_data[column]);
                        const new_col = Array.from(data[column]);
                        const array = old_col.concat(new_col);
                        data[column] = max_size != null ? array.slice(-max_size) : array;
                    }
                    this.data = data;
                    break;
                }
            }
        }
    }
    exports.WebDataSource = WebDataSource;
    _a = WebDataSource;
    WebDataSource.__name__ = "WebDataSource";
    (() => {
        _a.define(({ Any, Int, String, Nullable }) => ({
            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) {
    var _a;
    __esModule();
    const web_data_source_1 = require(432) /* ./web_data_source */;
    const enums_1 = require(20) /* ../../core/enums */;
    const logging_1 = require(19) /* ../../core/logging */;
    const object_1 = require(9) /* ../../core/util/object */;
    class AjaxDataSource extends web_data_source_1.WebDataSource {
        constructor(attrs) {
            super(attrs);
            this.interval = null;
            this.initialized = false;
        }
        destroy() {
            if (this.interval != null)
                clearInterval(this.interval);
            super.destroy();
        }
        setup() {
            if (!this.initialized) {
                this.initialized = true;
                this.get_data(this.mode);
                if (this.polling_interval != null) {
                    const callback = () => this.get_data(this.mode, this.max_size, this.if_modified);
                    this.interval = setInterval(callback, this.polling_interval);
                }
            }
        }
        get_data(mode, max_size = null, _if_modified = false) {
            const xhr = this.prepare_request();
            // TODO: if_modified
            xhr.addEventListener("load", () => this.do_load(xhr, mode, max_size !== null && max_size !== void 0 ? max_size : undefined));
            xhr.addEventListener("error", () => this.do_error(xhr));
            xhr.send();
        }
        prepare_request() {
            const xhr = new XMLHttpRequest();
            xhr.open(this.method, this.data_url, true);
            xhr.withCredentials = false;
            xhr.setRequestHeader("Content-Type", this.content_type);
            const http_headers = this.http_headers;
            for (const [name, value] of (0, object_1.entries)(http_headers)) {
                xhr.setRequestHeader(name, value);
            }
            return xhr;
        }
        async do_load(xhr, mode, max_size) {
            if (xhr.status == 200) {
                const raw_data = JSON.parse(xhr.responseText);
                await this.load_data(raw_data, mode, max_size);
            }
        }
        do_error(xhr) {
            logging_1.logger.error(`Failed to fetch JSON from ${this.data_url} with code ${xhr.status}`);
        }
    }
    exports.AjaxDataSource = AjaxDataSource;
    _a = AjaxDataSource;
    AjaxDataSource.__name__ = "AjaxDataSource";
    (() => {
        _a.define(({ Boolean, Int, String, Dict, Nullable }) => ({
            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) {
    var _a;
    __esModule();
    const columnar_data_source_1 = require(101) /* ./columnar_data_source */;
    const logging_1 = require(19) /* ../../core/logging */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    function orNaN(v) {
        return v != null ? v : NaN;
    }
    const { hasOwnProperty } = Object.prototype;
    class GeoJSONDataSource extends columnar_data_source_1.ColumnarDataSource {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._update_data();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.properties.geojson.change, () => this._update_data());
        }
        _update_data() {
            this.data = this.geojson_to_column_data();
        }
        _get_new_list_array(length) {
            return (0, array_1.range)(0, length).map((_i) => []);
        }
        _get_new_nan_array(length) {
            return (0, array_1.range)(0, length).map((_i) => NaN);
        }
        _add_properties(item, data, i, item_count) {
            var _b;
            const properties = (_b = item.properties) !== null && _b !== void 0 ? _b : {};
            for (const [property, value] of (0, object_1.entries)(properties)) {
                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);
            }
        }
        _add_geometry(geometry, data, i) {
            function flatten(acc, item) {
                return acc.concat([[NaN, NaN, NaN]]).concat(item);
            }
            switch (geometry.type) {
                case "Point": {
                    const [x, y, z] = geometry.coordinates;
                    data.x[i] = x;
                    data.y[i] = y;
                    data.z[i] = orNaN(z);
                    break;
                }
                case "LineString": {
                    const { coordinates } = geometry;
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        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.");
                    const exterior_ring = geometry.coordinates[0];
                    for (let j = 0; j < exterior_ring.length; j++) {
                        const [x, y, z] = exterior_ring[j];
                        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": {
                    const coordinates = geometry.coordinates.reduce(flatten);
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "MultiPolygon": {
                    const exterior_rings = [];
                    for (const polygon of geometry.coordinates) {
                        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]);
                    }
                    const coordinates = exterior_rings.reduce(flatten);
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        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}`);
            }
        }
        geojson_to_column_data() {
            const geojson = JSON.parse(this.geojson);
            let items;
            switch (geojson.type) {
                case "GeometryCollection": {
                    if ((0, types_1.is_undefined)(geojson.geometries))
                        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 ((0, types_1.is_undefined)(geojson.features))
                        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");
            }
            let item_count = 0;
            for (const item of items) {
                const geometry = item.type === "Feature" ? item.geometry : item;
                if (geometry.type == "GeometryCollection")
                    item_count += geometry.geometries.length;
                else
                    item_count += 1;
            }
            const 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),
            };
            let arr_index = 0;
            for (const item of items) {
                const geometry = item.type == "Feature" ? item.geometry : item;
                if (geometry.type == "GeometryCollection") {
                    for (const g of geometry.geometries) {
                        this._add_geometry(g, data, arr_index);
                        if (item.type === "Feature")
                            this._add_properties(item, data, arr_index, item_count);
                        arr_index += 1;
                    }
                }
                else {
                    this._add_geometry(geometry, data, arr_index);
                    if (item.type === "Feature")
                        this._add_properties(item, data, arr_index, item_count);
                    arr_index += 1;
                }
            }
            return data;
        }
    }
    exports.GeoJSONDataSource = GeoJSONDataSource;
    _a = GeoJSONDataSource;
    GeoJSONDataSource.__name__ = "GeoJSONDataSource";
    (() => {
        _a.define(({ String }) => ({
            geojson: [String],
        }));
        _a.internal(({ Any, Dict, Arrayable }) => ({
            data: [Dict(Arrayable(Any)), {}],
        }));
    })();
},
/* models/tiles/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var bbox_tile_source_1 = require(436) /* ./bbox_tile_source */;
    __esExport("BBoxTileSource", bbox_tile_source_1.BBoxTileSource);
    var mercator_tile_source_1 = require(437) /* ./mercator_tile_source */;
    __esExport("MercatorTileSource", mercator_tile_source_1.MercatorTileSource);
    var quadkey_tile_source_1 = require(440) /* ./quadkey_tile_source */;
    __esExport("QUADKEYTileSource", quadkey_tile_source_1.QUADKEYTileSource);
    var tile_renderer_1 = require(441) /* ./tile_renderer */;
    __esExport("TileRenderer", tile_renderer_1.TileRenderer);
    var tile_source_1 = require(438) /* ./tile_source */;
    __esExport("TileSource", tile_source_1.TileSource);
    var tms_tile_source_1 = require(444) /* ./tms_tile_source */;
    __esExport("TMSTileSource", tms_tile_source_1.TMSTileSource);
    var wmts_tile_source_1 = require(442) /* ./wmts_tile_source */;
    __esExport("WMTSTileSource", wmts_tile_source_1.WMTSTileSource);
},
/* models/tiles/bbox_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const mercator_tile_source_1 = require(437) /* ./mercator_tile_source */;
    class BBoxTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            let xmax, xmin, ymax, ymin;
            if (this.use_latlon)
                [xmin, ymin, xmax, ymax] = this.get_tile_geographic_bounds(x, y, z);
            else
                [xmin, ymin, xmax, ymax] = this.get_tile_meter_bounds(x, y, z);
            return image_url
                .replace("{XMIN}", xmin.toString())
                .replace("{YMIN}", ymin.toString())
                .replace("{XMAX}", xmax.toString())
                .replace("{YMAX}", ymax.toString());
        }
    }
    exports.BBoxTileSource = BBoxTileSource;
    _a = BBoxTileSource;
    BBoxTileSource.__name__ = "BBoxTileSource";
    (() => {
        _a.define(({ Boolean }) => ({
            use_latlon: [Boolean, false],
        }));
    })();
},
/* models/tiles/mercator_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tile_source_1 = require(438) /* ./tile_source */;
    const array_1 = require(10) /* ../../core/util/array */;
    const tile_utils_1 = require(439) /* ./tile_utils */;
    class MercatorTileSource extends tile_source_1.TileSource {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._resolutions = (0, array_1.range)(this.min_zoom, this.max_zoom + 1).map((z) => this.get_resolution(z));
        }
        _computed_initial_resolution() {
            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;
            }
        }
        is_valid_tile(x, y, z) {
            if (!this.wrap_around) {
                if (x < 0 || x >= 2 ** z)
                    return false;
            }
            if (y < 0 || y >= 2 ** z)
                return false;
            return true;
        }
        parent_by_tile_xyz(x, y, z) {
            const quadkey = this.tile_xyz_to_quadkey(x, y, z);
            const parent_quadkey = quadkey.substring(0, quadkey.length - 1);
            return this.quadkey_to_tile_xyz(parent_quadkey);
        }
        get_resolution(level) {
            return this._computed_initial_resolution() / 2 ** level;
        }
        get_resolution_by_extent(extent, height, width) {
            const x_rs = (extent[2] - extent[0]) / width;
            const y_rs = (extent[3] - extent[1]) / height;
            return [x_rs, y_rs];
        }
        get_level_by_extent(extent, height, width) {
            const x_rs = (extent[2] - extent[0]) / width;
            const y_rs = (extent[3] - extent[1]) / height;
            const resolution = Math.max(x_rs, y_rs);
            let i = 0;
            for (const r of this._resolutions) {
                if (resolution > r) {
                    if (i == 0)
                        return 0;
                    if (i > 0)
                        return i - 1;
                }
                i += 1;
            }
            // otherwise return the highest available resolution
            return (i - 1);
        }
        get_closest_level_by_extent(extent, height, width) {
            const x_rs = (extent[2] - extent[0]) / width;
            const y_rs = (extent[3] - extent[1]) / height;
            const resolution = Math.max(x_rs, y_rs);
            const 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);
        }
        snap_to_zoom_level(extent, height, width, level) {
            const [xmin, ymin, xmax, ymax] = extent;
            const desired_res = this._resolutions[level];
            let desired_x_delta = width * desired_res;
            let desired_y_delta = height * desired_res;
            if (!this.snap_to_zoom) {
                const xscale = (xmax - xmin) / desired_x_delta;
                const 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);
                }
            }
            const x_adjust = (desired_x_delta - (xmax - xmin)) / 2;
            const y_adjust = (desired_y_delta - (ymax - ymin)) / 2;
            return [xmin - x_adjust, ymin - y_adjust, xmax + x_adjust, ymax + y_adjust];
        }
        tms_to_wmts(x, y, z) {
            // Note this works both ways
            return [x, 2 ** z - 1 - y, z];
        }
        wmts_to_tms(x, y, z) {
            // Note this works both ways
            return [x, 2 ** z - 1 - y, z];
        }
        pixels_to_meters(px, py, level) {
            const res = this.get_resolution(level);
            const mx = (px * res) - this.x_origin_offset;
            const my = (py * res) - this.y_origin_offset;
            return [mx, my];
        }
        meters_to_pixels(mx, my, level) {
            const res = this.get_resolution(level);
            const px = (mx + this.x_origin_offset) / res;
            const py = (my + this.y_origin_offset) / res;
            return [px, py];
        }
        pixels_to_tile(px, py) {
            let tx = Math.ceil(px / this.tile_size);
            tx = tx === 0 ? tx : tx - 1;
            const ty = Math.max(Math.ceil(py / this.tile_size) - 1, 0);
            return [tx, ty];
        }
        pixels_to_raster(px, py, level) {
            const mapSize = this.tile_size << level;
            return [px, mapSize - py];
        }
        meters_to_tile(mx, my, level) {
            const [px, py] = this.meters_to_pixels(mx, my, level);
            return this.pixels_to_tile(px, py);
        }
        get_tile_meter_bounds(tx, ty, level) {
            // expects tms styles coordinates (bottom-left origin)
            const [xmin, ymin] = this.pixels_to_meters(tx * this.tile_size, ty * this.tile_size, level);
            const [xmax, ymax] = this.pixels_to_meters((tx + 1) * this.tile_size, (ty + 1) * this.tile_size, level);
            return [xmin, ymin, xmax, ymax];
        }
        get_tile_geographic_bounds(tx, ty, level) {
            const bounds = this.get_tile_meter_bounds(tx, ty, level);
            const [minLon, minLat, maxLon, maxLat] = (0, tile_utils_1.meters_extent_to_geographic)(bounds);
            return [minLon, minLat, maxLon, maxLat];
        }
        get_tiles_by_extent(extent, level, tile_border = 1) {
            // unpack extent and convert to tile coordinates
            const [xmin, ymin, xmax, ymax] = extent;
            let [txmin, tymin] = this.meters_to_tile(xmin, ymin, level);
            let [txmax, tymax] = this.meters_to_tile(xmax, ymax, level);
            // add tiles which border
            txmin -= tile_border;
            tymin -= tile_border;
            txmax += tile_border;
            tymax += tile_border;
            const tiles = [];
            for (let ty = tymax; ty >= tymin; ty--) {
                for (let 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;
        }
        quadkey_to_tile_xyz(quadKey) {
            /**
             * Computes tile x, y and z values based on quadKey.
             */
            let tileX = 0;
            let tileY = 0;
            const tileZ = quadKey.length;
            for (let i = tileZ; i > 0; i--) {
                const value = quadKey.charAt(tileZ - i);
                const 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];
        }
        tile_xyz_to_quadkey(x, y, z) {
            /*
             * Computes quadkey value based on tile x, y and z values.
             */
            let quadkey = "";
            for (let i = z; i > 0; i--) {
                const mask = 1 << (i - 1);
                let digit = 0;
                if ((x & mask) !== 0) {
                    digit += 1;
                }
                if ((y & mask) !== 0) {
                    digit += 2;
                }
                quadkey += digit.toString();
            }
            return quadkey;
        }
        children_by_tile_xyz(x, y, z) {
            const quadkey = this.tile_xyz_to_quadkey(x, y, z);
            const child_tile_xyz = [];
            for (let i = 0; i <= 3; i++) {
                const [x, y, z] = this.quadkey_to_tile_xyz(quadkey + i.toString());
                const b = this.get_tile_meter_bounds(x, y, z);
                child_tile_xyz.push([x, y, z, b]);
            }
            return child_tile_xyz;
        }
        get_closest_parent_by_tile_xyz(x, y, z) {
            const world_x = this.calculate_world_x_by_tile_xyz(x, y, z);
            [x, y, z] = this.normalize_xyz(x, y, z);
            let quadkey = this.tile_xyz_to_quadkey(x, y, z);
            while (quadkey.length > 0) {
                quadkey = quadkey.substring(0, quadkey.length - 1);
                [x, y, z] = this.quadkey_to_tile_xyz(quadkey);
                [x, y, z] = this.denormalize_xyz(x, y, z, world_x);
                if (this.tiles.has(this.tile_xyz_to_key(x, y, z)))
                    return [x, y, z];
            }
            return [0, 0, 0];
        }
        normalize_xyz(x, y, z) {
            if (this.wrap_around) {
                const tile_count = 2 ** z;
                return [((x % tile_count) + tile_count) % tile_count, y, z];
            }
            else {
                return [x, y, z];
            }
        }
        denormalize_xyz(x, y, z, world_x) {
            return [x + (world_x * 2 ** z), y, z];
        }
        denormalize_meters(meters_x, meters_y, _level, world_x) {
            return [meters_x + (world_x * 2 * Math.PI * 6378137), meters_y];
        }
        calculate_world_x_by_tile_xyz(x, _y, z) {
            return Math.floor(x / 2 ** z);
        }
    }
    exports.MercatorTileSource = MercatorTileSource;
    _a = MercatorTileSource;
    MercatorTileSource.__name__ = "MercatorTileSource";
    (() => {
        _a.define(({ Boolean }) => ({
            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) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const object_1 = require(9) /* ../../core/util/object */;
    class TileSource extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.tiles = new Map();
            this._normalize_case();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.change, () => this._clear_cache());
        }
        string_lookup_replace(str, lookup) {
            let result_str = str;
            for (const [key, value] of (0, object_1.entries)(lookup)) {
                result_str = result_str.replace(`{${key}}`, value);
            }
            return result_str;
        }
        _normalize_case() {
            /*
             * Note: should probably be refactored into subclasses.
             */
            const 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;
        }
        _clear_cache() {
            this.tiles = new Map();
        }
        tile_xyz_to_key(x, y, z) {
            return `${x}:${y}:${z}`;
        }
        key_to_tile_xyz(key) {
            const [x, y, z] = key.split(":").map((c) => parseInt(c));
            return [x, y, z];
        }
        sort_tiles_from_center(tiles, tile_extent) {
            const [txmin, tymin, txmax, tymax] = tile_extent;
            const center_x = ((txmax - txmin) / 2) + txmin;
            const center_y = ((tymax - tymin) / 2) + tymin;
            tiles.sort(function (a, b) {
                const a_distance = Math.sqrt((center_x - a[0]) ** 2 + (center_y - a[1]) ** 2);
                const b_distance = Math.sqrt((center_x - b[0]) ** 2 + (center_y - b[1]) ** 2);
                return a_distance - b_distance;
            });
        }
        get_image_url(x, y, z) {
            const 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());
        }
    }
    exports.TileSource = TileSource;
    _a = TileSource;
    TileSource.__name__ = "TileSource";
    (() => {
        _a.define(({ Number, String, Dict, Nullable /*, Null, Or, Ref*/ }) => ({
            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();
    const projections_1 = require(107) /* ../../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) {
        const [g_xmin, g_ymin, g_xmax, g_ymax] = extent;
        const [m_xmin, m_ymin] = geographic_to_meters(g_xmin, g_ymin);
        const [m_xmax, m_ymax] = geographic_to_meters(g_xmax, g_ymax);
        return [m_xmin, m_ymin, m_xmax, m_ymax];
    }
    exports.geographic_extent_to_meters = geographic_extent_to_meters;
    function meters_extent_to_geographic(extent) {
        const [m_xmin, m_ymin, m_xmax, m_ymax] = extent;
        const [g_xmin, g_ymin] = meters_to_geographic(m_xmin, m_ymin);
        const [g_xmax, g_ymax] = meters_to_geographic(m_xmax, m_ymax);
        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();
    const mercator_tile_source_1 = require(437) /* ./mercator_tile_source */;
    class QUADKEYTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            const [wx, wy, wz] = this.tms_to_wmts(x, y, z);
            const quadKey = this.tile_xyz_to_quadkey(wx, wy, wz);
            return image_url.replace("{Q}", quadKey);
        }
    }
    exports.QUADKEYTileSource = QUADKEYTileSource;
    QUADKEYTileSource.__name__ = "QUADKEYTileSource";
},
/* models/tiles/tile_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tile_source_1 = require(438) /* ./tile_source */;
    const wmts_tile_source_1 = require(442) /* ./wmts_tile_source */;
    const renderer_1 = require(74) /* ../renderers/renderer */;
    const range1d_1 = require(88) /* ../ranges/range1d */;
    const dom_1 = require(56) /* ../../core/dom */;
    const image_1 = require(152) /* ../../core/util/image */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const attribution_css_1 = tslib_1.__importDefault(require(443) /* ../../styles/attribution.css */);
    class TileRendererView extends renderer_1.RendererView {
        constructor() {
            super(...arguments);
            this._tiles = null;
        }
        mark_finished() {
            super.mark_finished();
            this._tiles = [];
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
            this.connect(this.model.tile_source.change, () => this.request_render());
        }
        remove() {
            if (this.attribution_el != null)
                (0, dom_1.remove)(this.attribution_el);
            super.remove();
        }
        get_extent() {
            const { x_range, y_range } = this;
            const x_start = x_range.start;
            const y_start = y_range.start;
            const x_end = x_range.end;
            const y_end = y_range.end;
            (0, assert_1.assert)(isFinite(x_start));
            (0, assert_1.assert)(isFinite(y_start));
            (0, assert_1.assert)(isFinite(x_end));
            (0, assert_1.assert)(isFinite(y_end));
            return [x_start, y_start, x_end, y_end];
        }
        get map_plot() {
            return this.plot_model;
        }
        get map_canvas() {
            return this.layer.ctx;
        }
        get map_frame() {
            return this.plot_view.frame;
        }
        get x_range() {
            return this.map_plot.x_range;
        }
        get y_range() {
            return this.map_plot.y_range;
        }
        _set_data() {
            this.extent = this.get_extent();
            this._last_height = undefined;
            this._last_width = undefined;
        }
        _update_attribution() {
            if (this.attribution_el != null)
                (0, dom_1.remove)(this.attribution_el);
            const { attribution } = this.model.tile_source;
            if ((0, types_1.isString)(attribution) && attribution.length > 0) {
                const { layout, frame } = this.plot_view;
                const offset_right = layout.bbox.width - frame.bbox.right;
                const offset_bottom = layout.bbox.height - frame.bbox.bottom;
                const max_width = frame.bbox.width;
                this.attribution_el = (0, dom_1.div)({
                    style: {
                        right: `${offset_right}px`,
                        bottom: `${offset_bottom}px`,
                        "max-width": `${max_width}px`,
                    },
                });
                const contents_el = (0, dom_1.div)();
                contents_el.innerHTML = attribution;
                const shadow_el = this.attribution_el.attachShadow({ mode: "open" });
                const stylesheet = new dom_1.InlineStyleSheet(attribution_css_1.default);
                stylesheet.install(shadow_el);
                shadow_el.appendChild(contents_el);
                this.attribution_el.title = contents_el.textContent.replace(/\s*\n\s*/g, " ");
                this.plot_view.canvas_view.add_event(this.attribution_el);
            }
            // TODO: add support for DOMElement
        }
        _map_data() {
            this.initial_extent = this.get_extent();
            const zoom_level = this.model.tile_source.get_level_by_extent(this.initial_extent, this.map_frame.bbox.height, this.map_frame.bbox.width);
            const 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();
        }
        _create_tile(x, y, z, bounds, cache_only = false) {
            const quadkey = this.model.tile_source.tile_xyz_to_quadkey(x, y, z);
            const cache_key = this.model.tile_source.tile_xyz_to_key(x, y, z);
            if (this.model.tile_source.tiles.has(cache_key))
                return;
            const [nx, ny, nz] = this.model.tile_source.normalize_xyz(x, y, z);
            const src = this.model.tile_source.get_image_url(nx, ny, nz);
            const tile = {
                img: undefined,
                tile_coords: [x, y, z],
                normalized_coords: [nx, ny, nz],
                quadkey,
                cache_key,
                bounds,
                loaded: false,
                finished: false,
                x_coord: bounds[0],
                y_coord: bounds[3],
            };
            this.model.tile_source.tiles.set(cache_key, tile);
            if (this._tiles == null)
                this._tiles = [];
            this._tiles.push(tile);
            new image_1.ImageLoader(src, {
                loaded: (img) => {
                    Object.assign(tile, { img, loaded: true });
                    if (cache_only) {
                        tile.finished = true;
                        this.notify_finished();
                    }
                    else
                        this.request_render();
                },
                failed() {
                    tile.finished = true;
                },
            });
        }
        _enforce_aspect_ratio() {
            // 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)) {
                const extent = this.get_extent();
                const zoom_level = this.model.tile_source.get_level_by_extent(extent, this.map_frame.bbox.height, this.map_frame.bbox.width);
                const 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;
            }
        }
        has_finished() {
            if (!super.has_finished())
                return false;
            if (this._tiles == null)
                return false;
            for (const tile of this._tiles) {
                if (!tile.finished)
                    return false;
            }
            return true;
        }
        _render() {
            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();
            }
        }
        _draw_tile(tile_key) {
            const tile_data = this.model.tile_source.tiles.get(tile_key);
            if (tile_data != null && tile_data.loaded) {
                const [[sxmin], [symin]] = this.coordinates.map_to_screen([tile_data.bounds[0]], [tile_data.bounds[3]]);
                const [[sxmax], [symax]] = this.coordinates.map_to_screen([tile_data.bounds[2]], [tile_data.bounds[1]]);
                const sw = sxmax - sxmin;
                const sh = symax - symin;
                const sx = sxmin;
                const sy = symin;
                const old_smoothing = this.map_canvas.imageSmoothingEnabled;
                this.map_canvas.imageSmoothingEnabled = this.model.smoothing;
                this.map_canvas.drawImage(tile_data.img, sx, sy, sw, sh);
                this.map_canvas.imageSmoothingEnabled = old_smoothing;
                tile_data.finished = true;
            }
        }
        _set_rect() {
            const outline_width = this.plot_model.outline_line_width;
            const l = this.map_frame.bbox.left + (outline_width / 2);
            const t = this.map_frame.bbox.top + (outline_width / 2);
            const w = this.map_frame.bbox.width - outline_width;
            const h = this.map_frame.bbox.height - outline_width;
            this.map_canvas.rect(l, t, w, h);
            this.map_canvas.clip();
        }
        _render_tiles(tile_keys) {
            this.map_canvas.save();
            this._set_rect();
            this.map_canvas.globalAlpha = this.model.alpha;
            for (const tile_key of tile_keys) {
                this._draw_tile(tile_key);
            }
            this.map_canvas.restore();
        }
        _prefetch_tiles() {
            const { tile_source } = this.model;
            const extent = this.get_extent();
            const h = this.map_frame.bbox.height;
            const w = this.map_frame.bbox.width;
            const zoom_level = this.model.tile_source.get_level_by_extent(extent, h, w);
            const tiles = this.model.tile_source.get_tiles_by_extent(extent, zoom_level);
            for (let t = 0, end = Math.min(10, tiles.length); t < end; t++) {
                const [x, y, z] = tiles[t];
                const children = this.model.tile_source.children_by_tile_xyz(x, y, z);
                for (const c of children) {
                    const [cx, cy, cz, cbounds] = c;
                    if (tile_source.tiles.has(tile_source.tile_xyz_to_key(cx, cy, cz))) {
                        continue;
                    }
                    else {
                        this._create_tile(cx, cy, cz, cbounds, true);
                    }
                }
            }
        }
        _fetch_tiles(tiles) {
            for (const tile of tiles) {
                const [x, y, z, bounds] = tile;
                this._create_tile(x, y, z, bounds);
            }
        }
        _update() {
            const { tile_source } = this.model;
            const { min_zoom } = tile_source;
            const { max_zoom } = tile_source;
            let extent = this.get_extent();
            const zooming_out = (this.extent[2] - this.extent[0]) < (extent[2] - extent[0]);
            const h = this.map_frame.bbox.height;
            const w = this.map_frame.bbox.width;
            let zoom_level = tile_source.get_level_by_extent(extent, h, w);
            let 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;
            const tiles = tile_source.get_tiles_by_extent(extent, zoom_level);
            const need_load = [];
            const cached = [];
            const parents = [];
            const children = [];
            for (const t of tiles) {
                const [x, y, z] = t;
                const key = tile_source.tile_xyz_to_key(x, y, z);
                const tile = tile_source.tiles.get(key);
                if (tile != null && tile.loaded) {
                    cached.push(key);
                }
                else {
                    if (this.model.render_parents) {
                        const [px, py, pz] = tile_source.get_closest_parent_by_tile_xyz(x, y, z);
                        const parent_key = tile_source.tile_xyz_to_key(px, py, pz);
                        const 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) {
                            const child_tiles = tile_source.children_by_tile_xyz(x, y, z);
                            for (const [cx, cy, cz] of child_tiles) {
                                const child_key = tile_source.tile_xyz_to_key(cx, cy, cz);
                                if (tile_source.tiles.has(child_key))
                                    children.push(child_key);
                            }
                        }
                    }
                }
                if (tile == null)
                    need_load.push(t);
            }
            // 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((() => this._fetch_tiles(need_load)), 65);
        }
    }
    exports.TileRendererView = TileRendererView;
    TileRendererView.__name__ = "TileRendererView";
    class TileRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TileRenderer = TileRenderer;
    _a = TileRenderer;
    TileRenderer.__name__ = "TileRenderer";
    (() => {
        _a.prototype.default_view = TileRendererView;
        _a.define(({ Boolean, Number, Ref }) => ({
            alpha: [Number, 1.0],
            smoothing: [Boolean, true],
            tile_source: [Ref(tile_source_1.TileSource), () => 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();
    const mercator_tile_source_1 = require(437) /* ./mercator_tile_source */;
    class WMTSTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            const [wx, wy, wz] = this.tms_to_wmts(x, y, z);
            return image_url
                .replace("{X}", wx.toString())
                .replace("{Y}", wy.toString())
                .replace("{Z}", wz.toString());
        }
    }
    exports.WMTSTileSource = WMTSTileSource;
    WMTSTileSource.__name__ = "WMTSTileSource";
},
/* styles/attribution.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{position:absolute;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;}a{color:black;}`;
},
/* models/tiles/tms_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(437) /* ./mercator_tile_source */;
    class TMSTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const 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());
        }
    }
    exports.TMSTileSource = TMSTileSource;
    TMSTileSource.__name__ = "TMSTileSource";
},
/* models/textures/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var canvas_texture_1 = require(446) /* ./canvas_texture */;
    __esExport("CanvasTexture", canvas_texture_1.CanvasTexture);
    var image_url_texture_1 = require(448) /* ./image_url_texture */;
    __esExport("ImageURLTexture", image_url_texture_1.ImageURLTexture);
    var texture_1 = require(447) /* ./texture */;
    __esExport("Texture", texture_1.Texture);
},
/* models/textures/canvas_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const texture_1 = require(447) /* ./texture */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CanvasTexture extends texture_1.Texture {
        constructor(attrs) {
            super(attrs);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function("ctx", "color", "scale", "weight", code);
        }
        get_pattern(color, scale, weight) {
            const canvas = document.createElement("canvas");
            canvas.width = scale;
            canvas.height = scale;
            const pattern_ctx = canvas.getContext("2d");
            this.func.call(this, pattern_ctx, color, scale, weight);
            return canvas;
        }
    }
    exports.CanvasTexture = CanvasTexture;
    _a = CanvasTexture;
    CanvasTexture.__name__ = "CanvasTexture";
    (() => {
        _a.define(({ String }) => ({
            code: [String],
        }));
    })();
},
/* models/textures/texture.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const enums_1 = require(20) /* ../../core/enums */;
    class Texture extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Texture = Texture;
    _a = Texture;
    Texture.__name__ = "Texture";
    (() => {
        _a.define(() => ({
            repetition: [enums_1.TextureRepetition, "repeat"],
        }));
    })();
},
/* models/textures/image_url_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const texture_1 = require(447) /* ./texture */;
    const image_1 = require(152) /* ../../core/util/image */;
    class ImageURLTexture extends texture_1.Texture {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._loader = new image_1.ImageLoader(this.url);
        }
        get_pattern(_color, _scale, _weight) {
            const { _loader } = this;
            return this._loader.finished ? _loader.image : _loader.promise;
        }
    }
    exports.ImageURLTexture = ImageURLTexture;
    _a = ImageURLTexture;
    ImageURLTexture.__name__ = "ImageURLTexture";
    (() => {
        _a.define(({ String }) => ({
            url: [String],
        }));
    })();
},
/* models/ui/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(450) /* ./icons */, exports);
    var dialog_1 = require(454) /* ./dialog */;
    __esExport("Dialog", dialog_1.Dialog);
    var examiner_1 = require(458) /* ./examiner */;
    __esExport("Examiner", examiner_1.Examiner);
    var pane_1 = require(460) /* ./pane */;
    __esExport("Pane", pane_1.Pane);
    var tooltip_1 = require(461) /* ./tooltip */;
    __esExport("Tooltip", tooltip_1.Tooltip);
    var ui_element_1 = require(266) /* ./ui_element */;
    __esExport("UIElement", ui_element_1.UIElement);
},
/* models/ui/icons/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var builtin_icon_1 = require(451) /* ./builtin_icon */;
    __esExport("BuiltinIcon", builtin_icon_1.BuiltinIcon);
    var svg_icon_1 = require(452) /* ./svg_icon */;
    __esExport("SVGIcon", svg_icon_1.SVGIcon);
    var tabler_icon_1 = require(453) /* ./tabler_icon */;
    __esExport("TablerIcon", tabler_icon_1.TablerIcon);
},
/* models/ui/icons/builtin_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const icon_1 = require(391) /* ./icon */;
    const dom_1 = require(56) /* ../../../core/dom */;
    const color_1 = require(22) /* ../../../core/util/color */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = tslib_1.__importDefault(require(278) /* ../../../styles/icons.css */);
    class BuiltinIconView extends icon_1.IconView {
        constructor() {
            super(...arguments);
            this._style = new dom_1.InlineStyleSheet();
        }
        stylesheets() {
            return [...super.stylesheets(), icons_css_1.default, this._style];
        }
        render() {
            super.render();
            const icon = `var(--bokeh-icon-${this.model.icon_name})`;
            const color = (0, color_1.color2css)(this.model.color);
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
        width: ${size};
        height: ${size};
        background-color: ${color};
        mask-image: ${icon};
        mask-size: contain;
        mask-repeat: no-repeat;
        -webkit-mask-image: ${icon};
        -webkit-mask-size: contain;
        -webkit-mask-repeat: no-repeat;
      }
    `);
        }
    }
    exports.BuiltinIconView = BuiltinIconView;
    BuiltinIconView.__name__ = "BuiltinIconView";
    class BuiltinIcon extends icon_1.Icon {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BuiltinIcon = BuiltinIcon;
    _a = BuiltinIcon;
    BuiltinIcon.__name__ = "BuiltinIcon";
    (() => {
        _a.prototype.default_view = BuiltinIconView;
        _a.define(({ String, Color }) => ({
            icon_name: [String],
            color: [Color, "gray"],
        }));
    })();
},
/* models/ui/icons/svg_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const icon_1 = require(391) /* ./icon */;
    const dom_1 = require(56) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    class SVGIconView extends icon_1.IconView {
        constructor() {
            super(...arguments);
            this._style = new dom_1.InlineStyleSheet();
        }
        stylesheets() {
            return [...super.stylesheets(), this._style];
        }
        render() {
            super.render();
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
      }
      :host svg {
        width: ${size};
        height: ${size};
      }
    `);
            const parser = new DOMParser();
            const doc = parser.parseFromString(this.model.svg, "image/svg+xml");
            this.shadow_el.append(doc.documentElement);
        }
    }
    exports.SVGIconView = SVGIconView;
    SVGIconView.__name__ = "SVGIconView";
    class SVGIcon extends icon_1.Icon {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.SVGIcon = SVGIcon;
    _a = SVGIcon;
    SVGIcon.__name__ = "SVGIcon";
    (() => {
        _a.prototype.default_view = SVGIconView;
        _a.define(({ String }) => ({
            svg: [String],
        }));
    })();
},
/* models/ui/icons/tabler_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const icon_1 = require(391) /* ./icon */;
    const dom_1 = require(56) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    class TablerIconView extends icon_1.IconView {
        constructor() {
            super(...arguments);
            this._tabler = new dom_1.ImportedStyleSheet(`${_a._url}/tabler-icons.min.css`);
            this._style = new dom_1.InlineStyleSheet();
        }
        stylesheets() {
            return [...super.stylesheets(), _a._fonts, this._tabler, this._style];
        }
        render() {
            super.render();
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
        font-size: ${size};
      }
    `);
            const icon = (0, dom_1.span)({ class: ["ti", `ti-${this.model.icon_name}`] });
            this.shadow_el.appendChild(icon);
        }
    }
    exports.TablerIconView = TablerIconView;
    _a = TablerIconView;
    TablerIconView.__name__ = "TablerIconView";
    TablerIconView._url = "https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@latest";
    TablerIconView._fonts = new dom_1.GlobalInlineStyleSheet(`\
    /*!
    * Tabler Icons 1.68.0 by tabler - https://tabler.io
    * License - https://github.com/tabler/tabler-icons/blob/master/LICENSE
    */
  @font-face {
    font-family: "tabler-icons";
    font-style: normal;
    font-weight: 400;
    src: url("${_a._url}/fonts/tabler-icons.eot");
    src: url("${_a._url}/fonts/tabler-icons.eot?#iefix") format("embedded-opentype"),
         url("${_a._url}/fonts/tabler-icons.woff2") format("woff2"),
         url("${_a._url}/fonts/tabler-icons.woff") format("woff"),
         url("${_a._url}/fonts/tabler-icons.ttf") format("truetype"),
         url("${_a._url}/fonts/tabler-icons.svg#tabler-icons") format("svg");
  }

  @media screen and (-webkit-min-device-pixel-ratio: 0) {
    @font-face {
      font-family: "tabler-icons";
      src: url("${_a._url}/fonts/tabler-icons.svg#tabler-icons") format("svg");
    }
  }
`);
    class TablerIcon extends icon_1.Icon {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TablerIcon = TablerIcon;
    _b = TablerIcon;
    TablerIcon.__name__ = "TablerIcon";
    (() => {
        _b.prototype.default_view = TablerIconView;
        _b.define(({ String }) => ({
            icon_name: [String],
        }));
    })();
},
/* models/ui/dialog.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const dom_node_1 = require(455) /* ../dom/dom_node */;
    const text_1 = require(456) /* ../dom/text */;
    const dom_1 = require(56) /* ../../core/dom */;
    const types_1 = require(8) /* ../../core/util/types */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const dialogs_css_1 = tslib_1.__importStar(require(457) /* ../../styles/dialogs.css */), dialogs = dialogs_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(278) /* ../../styles/icons.css */);
    const Button = ui_element_1.UIElement;
    class DialogView extends ui_element_1.UIElementView {
        *children() {
            yield* super.children();
            yield this._content;
        }
        stylesheets() {
            return [...super.stylesheets(), dialogs_css_1.default, icons_css_1.default];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const content = (() => {
                const { content } = this.model;
                return (0, types_1.isString)(content) ? new text_1.Text({ content }) : content;
            })();
            this._content = await (0, build_views_1.build_view)(content, { parent: this });
        }
        connect_signals() {
            super.connect_signals();
            const { visible } = this.model.properties;
            this.on_change(visible, () => this.render());
        }
        remove() {
            this._content.remove();
            super.remove();
        }
        render() {
            super.render();
            if (!this.model.visible) {
                this.el.remove();
                return;
            }
            document.body.appendChild(this.el);
            this._content.render();
            const title = (0, dom_1.div)({ class: dialogs.title });
            const content = (0, dom_1.div)({ class: dialogs.content }, this._content.el);
            const buttons = (0, dom_1.div)({ class: dialogs.buttons });
            this.shadow_el.appendChild(title);
            this.shadow_el.appendChild(content);
            this.shadow_el.appendChild(buttons);
            if (this.model.closable) {
                const close = (0, dom_1.div)({ class: dialogs.close });
                close.addEventListener("click", () => this.model.visible = false);
                this.shadow_el.appendChild(close);
            }
        }
    }
    exports.DialogView = DialogView;
    DialogView.__name__ = "DialogView";
    class Dialog extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Dialog = Dialog;
    _a = Dialog;
    Dialog.__name__ = "Dialog";
    (() => {
        _a.prototype.default_view = DialogView;
        _a.define(({ Boolean, String, Array, Ref, Or, Nullable }) => ({
            title: [Nullable(Or(String, Ref(dom_node_1.DOMNode))), null],
            content: [Or(String, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))],
            buttons: [Array(Ref(Button)), []],
            modal: [Boolean, false],
            closable: [Boolean, true],
            draggable: [Boolean, true],
        }));
    })();
},
/* models/dom/dom_node.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_view_1 = require(55) /* ../../core/dom_view */;
    const model_1 = require(50) /* ../../model */;
    class DOMNodeView extends dom_view_1.DOMView {
    }
    exports.DOMNodeView = DOMNodeView;
    DOMNodeView.__name__ = "DOMNodeView";
    class DOMNode extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DOMNode = DOMNode;
    DOMNode.__name__ = "DOMNode";
    DOMNode.__module__ = "bokeh.models.dom";
},
/* models/dom/text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const dom_node_1 = require(455) /* ./dom_node */;
    class TextView extends dom_node_1.DOMNodeView {
        render() {
            this.el.textContent = this.model.content;
        }
        _createElement() {
            return document.createTextNode("");
        }
    }
    exports.TextView = TextView;
    TextView.__name__ = "TextView";
    class Text extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Text = Text;
    _a = Text;
    Text.__name__ = "Text";
    (() => {
        _a.prototype.default_view = TextView;
        _a.define(({ String }) => ({
            content: [String, ""],
        }));
    })();
},
/* styles/dialogs.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.title = "bk-title";
    exports.content = "bk-content";
    exports.buttons = "bk-buttons";
    exports.close = "bk-close";
    exports.default = `:host{--bokeh-bg-color:white;--bokeh-border-color:#e5e5e5;--bokeh-shadow-color:#e5e5e5;}:host{position:fixed;z-index:1000;left:0;right:0;top:0;bottom:0;margin-left:auto;margin-right:auto;margin-top:auto;margin-bottom:auto;width:80vw;height:60vh;overflow:hidden;display:flex;flex-direction:column;flex-wrap:nowrap;background-color:var(--bokeh-bg-color);border:1px solid var(--bokeh-border-color);box-shadow:5px 5px 10px var(--bokeh-shadow-color);}.bk-title{position:relative;flex:1;min-height:0;}.bk-content{position:relative;flex:1;min-height:100%;display:flex;}.bk-buttons{position:relative;flex:1;min-height:0;}.bk-close{position:absolute;top:0;right:0;width:18px;height:18px;cursor:pointer;background-color:gray;mask-image:var(--bokeh-icon-x);mask-size:contain;mask-repeat:no-repeat;-webkit-mask-image:var(--bokeh-icon-x);-webkit-mask-size:contain;-webkit-mask-repeat:no-repeat;}.bk-close:hover{background-color:red;}`;
},
/* models/ui/examiner.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(266) /* ./ui_element */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const has_props_1 = require(14) /* ../../core/has_props */;
    const dom_1 = require(56) /* ../../core/dom */;
    const pretty_1 = require(42) /* ../../core/util/pretty */;
    const model_1 = require(50) /* ../../model */;
    const types_1 = require(8) /* ../../core/util/types */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const diagnostics_1 = require(38) /* ../../core/diagnostics */;
    const examiner_css_1 = tslib_1.__importDefault(require(459) /* ../../styles/examiner.css */);
    class HTMLPrinter {
        constructor(click, max_items, max_depth) {
            this.visited = new WeakSet();
            this.depth = 0;
            this.click = click;
            this.max_items = max_items;
            this.max_depth = max_depth;
        }
        to_html(obj) {
            if ((0, types_1.isObject)(obj)) {
                if (this.visited.has(obj))
                    return (0, dom_1.span)("<circular>");
                else
                    this.visited.add(obj);
            }
            if (obj == null)
                return this.null();
            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.isSymbol)(obj))
                return this.symbol(obj);
            else if (obj instanceof model_1.Model)
                return this.model(obj);
            else if (obj instanceof p.Property)
                return this.property(obj);
            else if ((0, types_1.isPlainObject)(obj))
                return this.object(obj);
            else if ((0, types_1.isArray)(obj))
                return this.array(obj);
            else if ((0, types_1.isIterable)(obj))
                return this.iterable(obj);
            else
                return (0, dom_1.span)((0, pretty_1.to_string)(obj));
        }
        null() {
            return (0, dom_1.span)({ class: "null" }, "null");
        }
        token(val) {
            return (0, dom_1.span)({ class: "token" }, val);
        }
        boolean(val) {
            return (0, dom_1.span)({ class: "boolean" }, `${val}`);
        }
        number(val) {
            return (0, dom_1.span)({ class: "number" }, `${val}`);
        }
        string(val) {
            const sq = val.includes("'");
            const dq = val.includes('"');
            const str = (() => {
                if (sq && dq)
                    return `\`${val.replace(/`/g, "\\`")}\``;
                else if (dq)
                    return `'${val}'`;
                else
                    return `"${val}"`;
            })();
            return (0, dom_1.span)({ class: "string" }, str);
        }
        symbol(val) {
            return (0, dom_1.span)({ class: "symbol" }, val.toString());
        }
        array(obj) {
            const T = this.token;
            const items = [];
            let i = 0;
            for (const entry of obj) {
                items.push(this.to_html(entry));
                if (i++ > this.max_items) {
                    items.push((0, dom_1.span)("\u2026"));
                    break;
                }
            }
            return (0, dom_1.span)({ class: "array" }, T("["), ...(0, iterator_1.interleave)(items, () => T(", ")), T("]"));
        }
        iterable(obj) {
            var _b;
            const T = this.token;
            const tag = (_b = Object(obj)[Symbol.toStringTag]) !== null && _b !== void 0 ? _b : "Object";
            const items = this.array([...obj]);
            return (0, dom_1.span)({ class: "iterable" }, `${tag}`, T("("), items, T(")"));
        }
        object(obj) {
            const T = this.token;
            const items = [];
            let i = 0;
            for (const [key, val] of (0, object_1.entries)(obj)) {
                items.push((0, dom_1.span)(`${key}`, T(": "), this.to_html(val)));
                if (i++ > this.max_items) {
                    items.push((0, dom_1.span)("\u2026"));
                    break;
                }
            }
            return (0, dom_1.span)({ class: "object" }, T("{"), ...(0, iterator_1.interleave)(items, () => T(", ")), T("}"));
        }
        model(obj) {
            const T = this.token;
            const el = (0, dom_1.span)({ class: "model" }, obj.constructor.__qualified__, T("("), this.to_html(obj.id), T(")"));
            el.addEventListener("click", () => this.click(obj));
            return el;
        }
        property(obj) {
            const model = this.model(obj.obj);
            const attr = (0, dom_1.span)({ class: "attr" }, obj.attr);
            return (0, dom_1.span)(model, this.token("."), attr);
        }
    }
    exports.HTMLPrinter = HTMLPrinter;
    HTMLPrinter.__name__ = "HTMLPrinter";
    class ExaminerView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this.prev_listener = null;
            this.watched_props = new Set();
        }
        stylesheets() {
            return [...super.stylesheets(), examiner_css_1.default];
        }
        render() {
            super.render();
            if (this.prev_listener != null)
                diagnostics_1.diagnostics.disconnect(this.prev_listener);
            const models_list = [];
            const props_list = [];
            const watches_list = [];
            const animations = new WeakMap();
            const listener = (obj) => {
                if (!(obj instanceof p.Property))
                    return;
                function highlight(el) {
                    const prev = animations.get(el);
                    if (prev != null)
                        prev.cancel();
                    const anim = el.animate([
                        { backgroundColor: "#def189" },
                        { backgroundColor: "initial" },
                    ], { duration: 2000 });
                    animations.set(el, anim);
                }
                function update(prop, prop_el, value_el) {
                    prop_el.classList.toggle("dirty", prop.dirty);
                    (0, dom_1.empty)(value_el);
                    const value = prop.is_unset ? (0, dom_1.span)("unset") : to_html(prop.get_value());
                    value_el.appendChild(value);
                    highlight(value_el);
                }
                for (const [model, model_el] of models_list) {
                    if (model == obj.obj) {
                        highlight(model_el);
                    }
                }
                for (const [prop, prop_el] of props_list) {
                    if (prop == obj) {
                        const [, , , value_el] = prop_el.children;
                        update(prop, prop_el, value_el);
                        break;
                    }
                }
                for (const [prop, prop_el] of watches_list) {
                    if (prop == obj) {
                        const [, value_el] = prop_el.children;
                        update(prop, prop_el, value_el);
                        break;
                    }
                }
            };
            diagnostics_1.diagnostics.connect(listener);
            const models_tb_el = (() => {
                const filter_el = (0, dom_1.input)({ class: "filter", type: "text", placeholder: "Filter" });
                filter_el.addEventListener("keyup", () => {
                    const text = filter_el.value;
                    for (const [model, el] of models_list) {
                        const show = model.constructor.__qualified__.includes(text);
                        el.classList.toggle("hidden", !show);
                    }
                });
                return (0, dom_1.div)({ class: "toolbar" }, filter_el);
            })();
            const initial_cb_el = (0, dom_1.input)({ type: "checkbox", checked: true });
            const internal_cb_el = (0, dom_1.input)({ type: "checkbox", checked: true });
            const update_prop_visibility = () => {
                for (const [prop, prop_el] of props_list) {
                    const show_initial = initial_cb_el.checked;
                    const show_internal = internal_cb_el.checked;
                    const hidden = !prop.dirty && !show_initial || prop.internal && !show_internal;
                    prop_el.classList.toggle("hidden", hidden);
                }
            };
            initial_cb_el.addEventListener("change", () => update_prop_visibility());
            internal_cb_el.addEventListener("change", () => update_prop_visibility());
            const props_tb_el = (() => {
                const filter_el = (0, dom_1.input)({ class: "filter", type: "text", placeholder: "Filter" });
                const group_el = (0, dom_1.span)({ class: "checkbox" }, (0, dom_1.input)({ type: "checkbox", checked: true }), (0, dom_1.span)("Group"));
                const initial_el = (0, dom_1.span)({ class: "checkbox" }, initial_cb_el, (0, dom_1.span)("Initial?"));
                const internal_el = (0, dom_1.span)({ class: "checkbox" }, internal_cb_el, (0, dom_1.span)("Internal?"));
                filter_el.addEventListener("keyup", () => {
                    const text = filter_el.value;
                    for (const [prop, el] of props_list) {
                        const show = prop.attr.includes(text);
                        el.classList.toggle("hidden", !show);
                    }
                });
                return (0, dom_1.div)({ class: "toolbar" }, filter_el, group_el, initial_el, internal_el);
            })();
            const watches_tb_el = (() => {
                const filter_el = (0, dom_1.input)({ class: "filter", type: "text", placeholder: "Filter" });
                filter_el.addEventListener("keyup", () => {
                    const text = filter_el.value;
                    for (const [prop, el] of watches_list) {
                        const show = prop.attr.includes(text);
                        el.classList.toggle("hidden", !show);
                    }
                });
                return (0, dom_1.div)({ class: "toolbar" }, filter_el);
            })();
            const models_list_el = (0, dom_1.div)({ class: "models-list" });
            const props_list_el = (0, dom_1.div)({ class: "props-list" });
            const watches_list_el = (0, dom_1.div)({ class: "watches-list" });
            const models_panel_el = (0, dom_1.div)({ class: "models-panel" }, models_tb_el, models_list_el);
            const props_panel_el = (0, dom_1.div)({ class: "props-panel" }, props_tb_el, props_list_el);
            const watches_panel_el = (0, dom_1.div)({ class: "watches-panel" }, watches_tb_el, watches_list_el);
            const column_el = (0, dom_1.div)({ class: "col", style: { width: "100%" } }, watches_panel_el, props_panel_el);
            const examiner_el = (0, dom_1.div)({ class: "examiner" }, models_panel_el, column_el);
            function click(obj) {
                if (obj instanceof model_1.Model)
                    render_props(obj);
            }
            function to_html(obj) {
                const printer = new HTMLPrinter(click, 5, 3);
                return printer.to_html(obj);
            }
            const render_models = (models, doc) => {
                (0, array_1.clear)(models_list);
                (0, dom_1.empty)(models_list_el);
                const roots = doc != null ? new Set(doc.roots()) : new Set();
                for (const model of models) {
                    const root = roots.has(model) ? (0, dom_1.span)({ class: "tag" }, "root") : null;
                    const ref_el = (0, dom_1.span)({ class: "model-ref", tabIndex: 0 }, to_html(model), root);
                    ref_el.addEventListener("keydown", (event) => {
                        if (event.key == "Enter") {
                            render_props(model);
                        }
                    });
                    models_list.push([model, ref_el]);
                    models_list_el.appendChild(ref_el);
                }
            };
            const render_props = (model) => {
                var _b;
                (0, array_1.clear)(props_list);
                (0, dom_1.empty)(props_list_el);
                for (const [item, el] of models_list) {
                    el.classList.toggle("active", model == item);
                }
                const bases = (() => {
                    const bases = [];
                    let proto = Object.getPrototypeOf(model);
                    do {
                        bases.push([proto.constructor, (0, object_1.keys)(proto._props)]);
                        proto = Object.getPrototypeOf(proto);
                    } while (proto.constructor != has_props_1.HasProps);
                    bases.reverse();
                    const cumulative = [];
                    for (const [, attrs] of bases) {
                        attrs.splice(0, cumulative.length);
                        cumulative.push(...attrs);
                    }
                    return bases;
                })();
                const connections = (_b = signaling_1.receivers_for_sender.get(model)) !== null && _b !== void 0 ? _b : [];
                for (const [base, attrs] of bases) {
                    if (attrs.length == 0)
                        continue;
                    const expander_el = (0, dom_1.span)({ class: ["expander"] });
                    const base_el = (0, dom_1.div)({ class: "base" }, expander_el, "inherited from", " ", (0, dom_1.span)({ class: "monospace" }, base.__qualified__));
                    props_list_el.appendChild(base_el);
                    const props_group = [];
                    for (const attr of attrs) {
                        const prop = model.property(attr);
                        const kind = prop.kind.toString();
                        const value = prop.is_unset ? (0, dom_1.span)("unset") : to_html(prop.get_value());
                        const internal_el = prop.internal ? (0, dom_1.span)({ class: "tag" }, "internal") : null;
                        const listeners = connections.filter((connection) => connection.signal == prop.change).length;
                        const listeners_el = listeners != 0 ? (0, dom_1.span)({ class: "tag" }, `${listeners}`) : null;
                        const watched = this.watched_props.has(prop);
                        const watch_el = (0, dom_1.input)({ type: "checkbox", checked: watched });
                        const attr_el = (0, dom_1.div)({ class: "prop-attr", tabIndex: 0 }, watch_el, (0, dom_1.span)({ class: "attr" }, attr), internal_el);
                        const conns_el = (0, dom_1.div)({ class: "prop-conns" }, listeners_el);
                        const kind_el = (0, dom_1.div)({ class: "prop-kind" }, kind);
                        const value_el = (0, dom_1.div)({ class: "prop-value" }, value);
                        const dirty = prop.dirty ? "dirty" : null;
                        const internal = prop.internal ? "internal" : null;
                        const show_initial = initial_cb_el.checked;
                        const show_internal = internal_cb_el.checked;
                        const hidden = !prop.dirty && !show_initial || prop.internal && !show_internal ? "hidden" : null;
                        const prop_el = (0, dom_1.div)({ class: ["prop", dirty, internal, hidden] }, attr_el, conns_el, kind_el, value_el);
                        props_group.push(prop_el);
                        props_list.push([prop, prop_el]);
                        props_list_el.appendChild(prop_el);
                        watch_el.addEventListener("change", () => {
                            this.watched_props[watch_el.checked ? "add" : "delete"](prop);
                            render_watches();
                        });
                    }
                    base_el.addEventListener("click", () => {
                        expander_el.classList.toggle("closed");
                        for (const el of props_group) {
                            el.classList.toggle("closed");
                        }
                    });
                }
            };
            const render_watches = () => {
                (0, array_1.clear)(watches_list);
                (0, dom_1.empty)(watches_list_el);
                if (this.watched_props.size == 0) {
                    const empty_el = (0, dom_1.div)({ class: "nothing" }, "No watched properties");
                    watches_list_el.appendChild(empty_el);
                }
                else {
                    for (const prop of this.watched_props) {
                        const attr_el = (0, dom_1.span)(to_html(prop));
                        const value_el = (0, dom_1.span)(prop.is_unset ? (0, dom_1.span)("unset") : to_html(prop.get_value()));
                        const prop_el = (0, dom_1.div)({ class: ["prop", prop.dirty ? "dirty" : null] }, attr_el, value_el);
                        watches_list.push([prop, prop_el]);
                        watches_list_el.appendChild(prop_el);
                    }
                }
            };
            this.shadow_el.appendChild(examiner_el);
            const { target } = this.model;
            if (target != null) {
                const models = target.references();
                const { document } = target;
                render_models(models, document);
                render_props(target);
            }
            else {
                const { document } = this.model;
                if (document != null) {
                    const models = document._all_models.values();
                    render_models(models, document);
                    const roots = document.roots();
                    if (roots.length != 0) {
                        const [root] = roots;
                        render_props(root);
                    }
                }
            }
            render_watches();
        }
    }
    exports.ExaminerView = ExaminerView;
    ExaminerView.__name__ = "ExaminerView";
    class Examiner extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Examiner = Examiner;
    _a = Examiner;
    Examiner.__name__ = "Examiner";
    (() => {
        _a.prototype.default_view = ExaminerView;
        _a.define(({ Ref, Nullable }) => ({
            target: [Nullable(Ref(has_props_1.HasProps)), null],
        }));
    })();
},
/* styles/examiner.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `.null{color:#7724c1;}.token{color:#881280;}.boolean{color:#007500;}.number{color:#1a1aa6;}.string{color:#994500;}.symbol{color:#c80000;}.model{cursor:pointer;}.attr{color:#c80000;}:root{--common-padding:3px;--common-outline:#1a73e8 solid 1px;--panel-bg-color:#f1f3f4;--panel-border-color:#cacdd1;}.monospace{font-family:var(--mono-font);}.hidden{display:none !important;}.col{display:flex;flex-direction:column;}.row{display:flex;flex-direction:row;}.toolbar{display:flex;flex-direction:row;gap:1em;background-color:var(--panel-bg-color);border-bottom:1px solid var(--panel-border-color);padding:var(--common-padding);}.checkbox{display:flex;flex-direction:row;align-items:center;gap:0.25em;}.filter:focus{outline:var(--common-outline);}.examiner{height:100%;display:flex;border:1px solid var(--panel-border-color);}.models-panel{display:flex;flex-direction:column;border-right:1px solid var(--panel-border-color);}.props-panel{display:flex;flex-direction:column;height:100%;overflow:auto;}.watches-panel{display:flex;flex-direction:column;border-bottom:1px solid var(--panel-border-color);}.models-list{display:flex;flex-direction:column;height:min-content;padding:var(--common-padding);overflow-x:hidden;overflow-y:auto;}.props-list{display:grid;grid-template-columns:min-content min-content 1fr 1fr;column-gap:1em;padding:var(--common-padding);}.watches-list{display:grid;grid-template-columns:1fr 1fr;column-gap:1em;padding:var(--common-padding);}.nothing{grid-column:1 / span 2;font-style:italic;text-align:center;}.prop{display:contents;}.prop.closed{display:none;}.prop > *{opacity:0.6;}.prop.dirty > *{opacity:1;}.model-ref{display:flex;align-items:center;flex-direction:row;font-family:var(--mono-font);}.model-ref:focus-visible{outline:var(--common-outline);}.model-ref:hover{background-color:#e2e2e2;}.model-ref.active{background-color:#c8e0ee;}.tag{margin-left:1em;padding:0 4px;font-size:60%;border-width:1px;border-style:solid;border-radius:4px;color:#202124;background-color:#f1f3f4;border-color:#cacdd1;}.expander{margin:0 2px;display:inline-block;vertical-align:middle;background-color:#5f6368;--open-image:url('data:image/svg+xml;utf8,\
    <svg xmlns="http://www.w3.org/2000/svg" width="6" height="6">\
      <path d="M 0 1 L 6 1 3 5 Z"/>\
    </svg>');--closed-image:url('data:image/svg+xml;utf8,\
    <svg xmlns="http://www.w3.org/2000/svg" width="6" height="6">\
      <path d="M 1 0 L 5 3 1 6 Z"/>\
    </svg>');}.expander{width:6px;height:6px;mask-image:var(--open-image);-webkit-mask-image:var(--open-image);}.expander.closed{width:6px;height:6px;mask-image:var(--closed-image);-webkit-mask-image:var(--closed-image);}.base{grid-column:1 / span 4;color:#5f6368;cursor:pointer;}.prop-attr,.prop-conns,.prop-kind,.prop-value{display:flex;flex-direction:row;align-items:center;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-family:var(--mono-font);}.prop-attr > input[type="checkbox"]{visibility:hidden;margin-right:0.25em;}.prop-attr > input[type="checkbox"]:checked,.prop-attr:hover > input{visibility:visible;}.prop-attr:focus-visible{outline:var(--common-outline);}`;
},
/* models/ui/pane.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const ui_element_1 = require(266) /* ./ui_element */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const types_1 = require(8) /* ../../core/util/types */;
    class PaneView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._child_views = new Map();
        }
        get _ui_elements() {
            return this.model.children.filter((child) => child instanceof ui_element_1.UIElement);
        }
        get child_views() {
            return this._ui_elements.map((child) => this._child_views.get(child));
        }
        *children() {
            yield* super.children();
            yield* this._child_views.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._rebuild_views();
        }
        async _rebuild_views() {
            await (0, build_views_1.build_views)(this._child_views, this._ui_elements, { parent: this });
        }
        remove() {
            (0, build_views_1.remove_views)(this._child_views);
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            const { children } = this.model.properties;
            this.on_change(children, () => {
                this._rebuild_views();
                this.render();
            });
        }
        render() {
            super.render();
            for (const child of this.model.children) {
                if ((0, types_1.isString)(child)) {
                    const text = document.createTextNode(child);
                    this.shadow_el.append(text);
                }
                else {
                    const child_view = this._child_views.get(child);
                    child_view.render();
                    this.shadow_el.append(child_view.el);
                    child_view.after_render();
                }
            }
        }
        has_finished() {
            if (!super.has_finished())
                return false;
            for (const child_view of this.child_views) {
                if (!child_view.has_finished())
                    return false;
            }
            return true;
        }
        serializable_state() {
            return Object.assign(Object.assign({}, super.serializable_state()), { children: this.child_views.map((child) => child.serializable_state()) });
        }
    }
    exports.PaneView = PaneView;
    PaneView.__name__ = "PaneView";
    class Pane extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Pane = Pane;
    _a = Pane;
    Pane.__name__ = "Pane";
    (() => {
        _a.prototype.default_view = PaneView;
        _a.define(({ String, Array, Ref, Or }) => ({
            children: [Array(Or(String, Ref(ui_element_1.UIElement))), []],
        }));
    })();
},
/* models/ui/tooltip.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(266) /* ./ui_element */;
    const selector_1 = require(426) /* ../selectors/selector */;
    const html_1 = require(462) /* ../dom/html */;
    const enums_1 = require(20) /* ../../core/enums */;
    const dom_1 = require(56) /* ../../core/dom */;
    const dom_view_1 = require(55) /* ../../core/dom_view */;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const bbox_1 = require(57) /* ../../core/util/bbox */;
    const logging_1 = require(19) /* ../../core/logging */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const tooltips_css_1 = tslib_1.__importStar(require(463) /* ../../styles/tooltips.css */), tooltips = tooltips_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(278) /* ../../styles/icons.css */);
    class TooltipView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._html = null;
        }
        get target() {
            return this._target;
        }
        set target(el) {
            this._target = el;
        }
        _init_target() {
            const { target } = this.model;
            const el = (() => {
                var _b, _c;
                if (target instanceof ui_element_1.UIElement) {
                    return (_c = (_b = this.owner.find_one(target)) === null || _b === void 0 ? void 0 : _b.el) !== null && _c !== void 0 ? _c : null;
                }
                else if (target instanceof selector_1.Selector) {
                    return target.find_one(document);
                }
                else if (target instanceof Node) {
                    return target;
                }
                else {
                    const { parent } = this;
                    return parent instanceof dom_view_1.DOMElementView ? parent.el : null;
                }
            })();
            if (el instanceof Element)
                this._target = el;
            else {
                logging_1.logger.warn(`unable to resolve target '${target}' for '${this}'`);
                this._target = document.body;
            }
        }
        initialize() {
            super.initialize();
            this._init_target();
        }
        *children() {
            yield* super.children();
            if (this._html != null)
                yield this._html;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { content } = this.model;
            if (content instanceof html_1.HTML) {
                this._html = await (0, build_views_1.build_view)(content, { parent: this });
            }
            this.render();
        }
        connect_signals() {
            super.connect_signals();
            this._observer = new ResizeObserver(() => {
                this._reposition();
            });
            this._observer.observe(this.target);
            let throttle = false;
            document.addEventListener("scroll", this._scroll_listener = () => {
                if (!throttle) {
                    requestAnimationFrame(() => {
                        this._reposition();
                        throttle = false;
                    });
                    throttle = true;
                }
            }, { capture: true });
            const { target, content, closable, interactive, position, attachment, visible } = this.model.properties;
            this.on_change(target, () => {
                this._init_target();
                this._observer.disconnect();
                this._observer.observe(this.target);
                this.render();
            });
            this.on_change([content, closable, interactive], () => this.render());
            this.on_change([position, attachment, visible], () => this._reposition());
        }
        disconnect_signals() {
            if (this._scroll_listener != null) {
                document.removeEventListener("scroll", this._scroll_listener, { capture: true });
                delete this._scroll_listener;
            }
            super.disconnect_signals();
        }
        remove() {
            var _b;
            (_b = this._html) === null || _b === void 0 ? void 0 : _b.remove();
            this._observer.disconnect();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), tooltips_css_1.default, icons_css_1.default];
        }
        get content() {
            const { content } = this.model;
            if ((0, types_1.isString)(content)) {
                return document.createTextNode(content);
            }
            else if (content instanceof html_1.HTML) {
                (0, assert_1.assert)(this._html != null);
                return this._html.el;
            }
            else
                return content;
        }
        render() {
            var _b;
            super.render();
            (_b = this._html) === null || _b === void 0 ? void 0 : _b.render();
            this.arrow_el = (0, dom_1.div)({ class: [tooltips.arrow] });
            this.content_el = (0, dom_1.div)({ class: tooltips.tooltip_content }, this.content);
            this.shadow_el.append(this.arrow_el, this.content_el);
            if (this.model.closable) {
                const close_el = (0, dom_1.div)({ class: tooltips.close });
                close_el.addEventListener("click", () => {
                    this.model.visible = false;
                });
                this.shadow_el.appendChild(close_el);
            }
            this.el.classList.toggle(tooltips.show_arrow, this.model.show_arrow);
            this.el.classList.toggle(tooltips.non_interactive, !this.model.interactive);
            this._reposition();
        }
        _anchor_to_align(anchor) {
            switch (anchor) {
                case "top_left":
                    return ["top", "left"];
                case "top":
                case "top_center":
                    return ["top", "center"];
                case "top_right":
                    return ["top", "right"];
                case "left":
                case "center_left":
                    return ["center", "left"];
                case "center":
                case "center_center":
                    return ["center", "center"];
                case "right":
                case "center_right":
                    return ["center", "right"];
                case "bottom_left":
                    return ["bottom", "left"];
                case "bottom":
                case "bottom_center":
                    return ["bottom", "center"];
                case "bottom_right":
                    return ["bottom", "right"];
            }
        }
        _reposition() {
            var _b;
            const { position, visible } = this.model;
            if (position == null || !visible) {
                this.el.remove();
                return;
            }
            // Append to `body` to deal with CSS' `contain` interaction
            // with `position: fixed`. We assume initial containment
            // block in this function, but `contain` can introduce a
            // new containment block and offset tooltip's position.
            ((_b = document.body.shadowRoot) !== null && _b !== void 0 ? _b : document.body).append(this.el);
            const bbox = (0, dom_1.bounding_box)(this.target);
            const [sx, sy] = (() => {
                if ((0, types_1.isString)(position)) {
                    const [valign, halign] = this._anchor_to_align(position);
                    const sx = (() => {
                        switch (halign) {
                            case "left": return bbox.left;
                            case "center": return bbox.hcenter;
                            case "right": return bbox.right;
                        }
                    })();
                    const sy = (() => {
                        switch (valign) {
                            case "top": return bbox.top;
                            case "center": return bbox.vcenter;
                            case "bottom": return bbox.bottom;
                        }
                    })();
                    return [sx, sy];
                }
                else {
                    const [x, y] = position;
                    return [bbox.left + x, bbox.top + y];
                }
            })();
            const viewport = new bbox_1.BBox({
                x: 0,
                y: 0,
                width: window.innerWidth,
                height: window.innerHeight,
            });
            const arrow_size = (0, dom_1.box_size)(this.arrow_el);
            const side = (() => {
                const attachment = (() => {
                    const { attachment } = this.model;
                    if (attachment == "auto") {
                        if ((0, types_1.isString)(position)) {
                            const [valign, halign] = this._anchor_to_align(position);
                            if (halign != "center") {
                                return halign == "left" ? "left" : "right";
                            }
                            if (valign != "center") {
                                return valign == "top" ? "above" : "below";
                            }
                        }
                        return "horizontal";
                    }
                    else {
                        return attachment;
                    }
                })();
                const el_size = (0, dom_1.box_size)(this.el);
                const width = el_size.width + arrow_size.width;
                const height = el_size.height + arrow_size.height;
                switch (attachment) {
                    case "horizontal": {
                        if (sx < bbox.hcenter) {
                            return sx + width <= viewport.right ? "right" : "left";
                        }
                        else {
                            return sx - width >= viewport.left ? "left" : "right";
                        }
                    }
                    case "vertical": {
                        if (sy < bbox.vcenter) {
                            return sy + height <= viewport.bottom ? "below" : "above";
                        }
                        else {
                            return sy - height >= viewport.top ? "above" : "below";
                        }
                    }
                    default:
                        return attachment;
                }
            })();
            // 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
            this.class_list.remove(tooltips.right, tooltips.left, tooltips.above, tooltips.below);
            this.class_list.add((() => {
                switch (side) {
                    case "left": return tooltips.right;
                    case "right": return tooltips.left;
                    case "above": return tooltips.below;
                    case "below": return tooltips.above;
                }
            })());
            this.arrow_el.style.left = `${sx}px`;
            this.arrow_el.style.top = `${sy}px`;
            const { left, top } = (() => {
                const { width, height } = (0, dom_1.box_size)(this.el);
                function adjust_top(top) {
                    if (top < viewport.top) {
                        return viewport.top;
                    }
                    else if (top + height > viewport.bottom) {
                        return viewport.bottom - height;
                    }
                    else {
                        return top;
                    }
                }
                function adjust_left(left) {
                    if (left < viewport.left) {
                        return viewport.left;
                    }
                    else if (left + width > viewport.right) {
                        return viewport.right - width;
                    }
                    else {
                        return left;
                    }
                }
                switch (side) {
                    case "left": {
                        return {
                            left: sx - width - arrow_size.width,
                            top: adjust_top(sy - height / 2),
                        };
                    }
                    case "right": {
                        return {
                            left: sx + arrow_size.width,
                            top: adjust_top(sy - height / 2),
                        };
                    }
                    case "above": {
                        return {
                            left: adjust_left(sx - width / 2),
                            top: sy - height - arrow_size.height,
                        };
                    }
                    case "below": {
                        return {
                            left: adjust_left(sx - width / 2),
                            top: sy + arrow_size.height,
                        };
                    }
                }
            })();
            this.el.style.top = `${top}px`;
            this.el.style.left = `${left}px`;
        }
    }
    exports.TooltipView = TooltipView;
    TooltipView.__name__ = "TooltipView";
    class Tooltip extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        clear() {
            this.position = null;
        }
    }
    exports.Tooltip = Tooltip;
    _a = Tooltip;
    Tooltip.__name__ = "Tooltip";
    (() => {
        _a.prototype.default_view = TooltipView;
        _a.define(({ Boolean, Number, String, Tuple, Or, Ref, Nullable, Auto }) => ({
            target: [Or(Ref(ui_element_1.UIElement), Ref(selector_1.Selector), Ref(Node), Auto), "auto"],
            position: [Nullable(Or(enums_1.Anchor, Tuple(Number, Number))), null],
            content: [Or(String, Ref(html_1.HTML), Ref(Node))],
            attachment: [Or(enums_1.TooltipAttachment, Auto), "auto"],
            show_arrow: [Boolean, true],
            closable: [Boolean, false],
            interactive: [Boolean, true],
        }));
        _a.override({
            visible: false,
        });
    })();
},
/* models/dom/html.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const dom_node_1 = require(455) /* ./dom_node */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const dom_1 = require(56) /* ../../core/dom */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const types_1 = require(8) /* ../../core/util/types */;
    class HTMLView extends dom_node_1.DOMNodeView {
        constructor() {
            super(...arguments);
            this._refs = new Map();
        }
        *children() {
            yield* super.children();
            yield* this._refs.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await (0, build_views_1.build_views)(this._refs, this.model.refs);
        }
        remove() {
            (0, build_views_1.remove_views)(this._refs);
            super.remove();
        }
        render() {
            (0, dom_1.empty)(this.el);
            this.el.style.display = "contents";
            const parser = new DOMParser();
            const nodes = (() => {
                const { html } = this.model;
                if ((0, types_1.isString)(html)) {
                    const document = parser.parseFromString(html, "text/html");
                    const iter = document.createNodeIterator(document, NodeFilter.SHOW_ELEMENT, (node) => {
                        return node.nodeName.toLowerCase() == "ref" ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
                    });
                    let node;
                    while ((node = iter.nextNode()) != null) {
                        (0, assert_1.assert)(node instanceof Element);
                        const id = node.getAttribute("id");
                        if (id != null) {
                            for (const [model, view] of this._refs) {
                                if (model.id == id) {
                                    view.render();
                                    node.replaceWith(view.el);
                                    break;
                                }
                            }
                        }
                    }
                    return [...document.body.childNodes];
                }
                else {
                    return []; // TODO
                }
            })();
            for (const node of nodes) {
                this.el.appendChild(node);
            }
        }
    }
    exports.HTMLView = HTMLView;
    HTMLView.__name__ = "HTMLView";
    class HTML extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTML = HTML;
    _a = HTML;
    HTML.__name__ = "HTML";
    (() => {
        _a.prototype.default_view = HTMLView;
        _a.define(({ String, Array, Or, Ref }) => ({
            html: [Or(String, Array(Or(String, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))))],
            refs: [Array(Or(Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))), []],
        }));
    })();
},
/* styles/tooltips.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.non_interactive = "bk-non-interactive";
    exports.arrow = "bk-arrow";
    exports.show_arrow = "bk-show-arrow";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.tooltip_content = "bk-tooltip-content";
    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.close = "bk-close";
    exports.default = `:host{--tooltip-border:#e5e5e5;--tooltip-color:white;--tooltip-text:#2f2f2f;--tooltip-arrow-color:#909599;--tooltip-arrow-width:10px;--tooltip-arrow-height:10px;--tooltip-arrow-half-width:7px;--tooltip-arrow-half-height:7px;}:host{width:max-content;font-weight:300;font-size:12px;position:fixed;padding:5px;border:1px solid var(--tooltip-border);color:var(--tooltip-text);background-color:var(--tooltip-color);opacity:0.95;z-index:100;}:host(.bk-non-interactive){pointer-events:none;}.bk-arrow{position:fixed;width:0;height:0;content:" ";border-style:solid;border-color:transparent;}:host(:not(.bk-show-arrow)) .bk-arrow{display:none;}:host(.bk-left) .bk-arrow,:host(.bk-right) .bk-arrow{border-width:var(--tooltip-arrow-half-height) 0 var(--tooltip-arrow-half-height) 0;}:host(.bk-above) .bk-arrow,:host(.bk-below) .bk-arrow{border-width:0 var(--tooltip-arrow-half-width) 0 var(--tooltip-arrow-half-width);}:host(.bk-left) .bk-arrow{transform:translate(0%, -50%);border-right-width:var(--tooltip-arrow-width);border-right-color:var(--tooltip-arrow-color);}:host(.bk-right) .bk-arrow{transform:translate(-100%, -50%);border-left-width:var(--tooltip-arrow-width);border-left-color:var(--tooltip-arrow-color);}:host(.bk-above) .bk-arrow{transform:translate(-50%, 0%);border-bottom-width:var(--tooltip-arrow-height);border-bottom-color:var(--tooltip-arrow-color);}:host(.bk-below) .bk-arrow{transform:translate(-50%, -100%);border-top-width:var(--tooltip-arrow-height);border-top-color:var(--tooltip-arrow-color);}.bk-tooltip-content > div:not(:first-child){margin-top:5px;border-top:var(--tooltip-border) 1px dashed;}.bk-tooltip-row-label{text-align:right;color:#26aae1;}.bk-tooltip-row-value{color:none;}.bk-tooltip-color-block{width:12px;height:12px;margin-left:5px;margin-right:5px;outline:#dddddd solid 1px;display:inline-block;}.bk-close{position:absolute;top:2px;right:2px;width:12px;height:12px;cursor:pointer;background-color:gray;mask-image:var(--bokeh-icon-x);mask-size:contain;mask-repeat:no-repeat;-webkit-mask-image:var(--bokeh-icon-x);-webkit-mask-size:contain;-webkit-mask-repeat:no-repeat;}.bk-close:hover{background-color:red;}`;
},
/* models/tools/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(465) /* ./actions */, exports);
    tslib_1.__exportStar(require(479) /* ./edit */, exports);
    tslib_1.__exportStar(require(489) /* ./gestures */, exports);
    tslib_1.__exportStar(require(501) /* ./inspectors */, exports);
    var tool_1 = require(273) /* ./tool */;
    __esExport("Tool", tool_1.Tool);
    var tool_proxy_1 = require(274) /* ./tool_proxy */;
    __esExport("ToolProxy", tool_proxy_1.ToolProxy);
    var toolbar_1 = require(265) /* ./toolbar */;
    __esExport("Toolbar", toolbar_1.Toolbar);
    var tool_button_1 = require(275) /* ./tool_button */;
    __esExport("ToolButton", tool_button_1.ToolButton);
    var on_off_button_1 = require(281) /* ./on_off_button */;
    __esExport("OnOffButton", on_off_button_1.OnOffButton);
    var click_button_1 = require(284) /* ./click_button */;
    __esExport("ClickButton", click_button_1.ClickButton);
},
/* models/tools/actions/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var action_tool_1 = require(283) /* ./action_tool */;
    __esExport("ActionTool", action_tool_1.ActionTool);
    var copy_tool_1 = require(466) /* ./copy_tool */;
    __esExport("CopyTool", copy_tool_1.CopyTool);
    var custom_action_1 = require(467) /* ./custom_action */;
    __esExport("CustomAction", custom_action_1.CustomAction);
    var fullscreen_tool_1 = require(468) /* ./fullscreen_tool */;
    __esExport("FullscreenTool", fullscreen_tool_1.FullscreenTool);
    var help_tool_1 = require(285) /* ./help_tool */;
    __esExport("HelpTool", help_tool_1.HelpTool);
    var examine_tool_1 = require(469) /* ./examine_tool */;
    __esExport("ExamineTool", examine_tool_1.ExamineTool);
    var redo_tool_1 = require(470) /* ./redo_tool */;
    __esExport("RedoTool", redo_tool_1.RedoTool);
    var reset_tool_1 = require(472) /* ./reset_tool */;
    __esExport("ResetTool", reset_tool_1.ResetTool);
    var save_tool_1 = require(473) /* ./save_tool */;
    __esExport("SaveTool", save_tool_1.SaveTool);
    var undo_tool_1 = require(474) /* ./undo_tool */;
    __esExport("UndoTool", undo_tool_1.UndoTool);
    var zoom_in_tool_1 = require(475) /* ./zoom_in_tool */;
    __esExport("ZoomInTool", zoom_in_tool_1.ZoomInTool);
    var zoom_out_tool_1 = require(478) /* ./zoom_out_tool */;
    __esExport("ZoomOutTool", zoom_out_tool_1.ZoomOutTool);
},
/* models/tools/actions/copy_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const action_tool_1 = require(283) /* ./action_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class CopyToolView extends action_tool_1.ActionToolView {
        async copy() {
            const blob = await this.parent.export().to_blob();
            const item = new ClipboardItem({ [blob.type]: blob });
            await navigator.clipboard.write([item]);
        }
        doit() {
            this.copy();
        }
    }
    exports.CopyToolView = CopyToolView;
    CopyToolView.__name__ = "CopyToolView";
    class CopyTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Copy";
            this.tool_icon = icons_css_1.tool_icon_copy;
        }
    }
    exports.CopyTool = CopyTool;
    _a = CopyTool;
    CopyTool.__name__ = "CopyTool";
    (() => {
        _a.prototype.default_view = CopyToolView;
        _a.register_alias("copy", () => new _a());
    })();
},
/* models/tools/actions/custom_action.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const action_tool_1 = require(283) /* ./action_tool */;
    const icons = tslib_1.__importStar(require(278) /* ../../../styles/icons.css */);
    class CustomActionView extends action_tool_1.ActionToolView {
        doit() {
            var _b;
            (_b = this.model.callback) === null || _b === void 0 ? void 0 : _b.execute(this.model);
        }
    }
    exports.CustomActionView = CustomActionView;
    CustomActionView.__name__ = "CustomActionView";
    class CustomAction extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Custom Action";
            this.tool_icon = icons.tool_icon_unknown;
        }
    }
    exports.CustomAction = CustomAction;
    _a = CustomAction;
    CustomAction.__name__ = "CustomAction";
    (() => {
        _a.prototype.default_view = CustomActionView;
        _a.define(({ Any, Nullable }) => ({
            callback: [Nullable(Any /*TODO*/), null],
        }));
        _a.override({
            description: "Perform a Custom Action",
        });
    })();
},
/* models/tools/actions/fullscreen_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const action_tool_1 = require(283) /* ./action_tool */;
    const icons = tslib_1.__importStar(require(278) /* ../../../styles/icons.css */);
    const request_fullscreen = (() => {
        if (typeof Element.prototype.webkitRequestFullscreen !== "undefined") {
            return (el, options) => el.webkitRequestFullscreen(options);
        }
        else {
            return (el, options) => el.requestFullscreen(options);
        }
    })();
    class FullscreenToolView extends action_tool_1.ActionToolView {
        doit() {
            if (document.fullscreenElement != null) {
                document.exitFullscreen();
            }
            else {
                (async () => {
                    await request_fullscreen(this.parent.el);
                })();
            }
        }
    }
    exports.FullscreenToolView = FullscreenToolView;
    FullscreenToolView.__name__ = "FullscreenToolView";
    class FullscreenTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Fullscreen";
            this.tool_icon = icons.tool_icon_fullscreen;
        }
    }
    exports.FullscreenTool = FullscreenTool;
    _a = FullscreenTool;
    FullscreenTool.__name__ = "FullscreenTool";
    (() => {
        _a.prototype.default_view = FullscreenToolView;
        _a.register_alias("fullscreen", () => new _a());
    })();
},
/* models/tools/actions/examine_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const action_tool_1 = require(283) /* ./action_tool */;
    const icons = tslib_1.__importStar(require(278) /* ../../../styles/icons.css */);
    const dialog_1 = require(454) /* ../../ui/dialog */;
    const examiner_1 = require(458) /* ../../ui/examiner */;
    const build_views_1 = require(59) /* ../../../core/build_views */;
    class ExamineToolView extends action_tool_1.ActionToolView {
        *children() {
            yield* super.children();
            yield this._dialog;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const dialog = new dialog_1.Dialog({
                content: new examiner_1.Examiner({ target: this.parent.model }),
                closable: true,
                visible: false,
            });
            this._dialog = await (0, build_views_1.build_view)(dialog, { parent: this.parent });
        }
        doit() {
            this._dialog.model.visible = true;
        }
    }
    exports.ExamineToolView = ExamineToolView;
    ExamineToolView.__name__ = "ExamineToolView";
    class ExamineTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Examine";
            this.tool_icon = icons.tool_icon_settings; // TODO: better icon
        }
    }
    exports.ExamineTool = ExamineTool;
    _a = ExamineTool;
    ExamineTool.__name__ = "ExamineTool";
    (() => {
        _a.prototype.default_view = ExamineToolView;
        _a.register_alias("examine", () => new _a());
    })();
},
/* models/tools/actions/redo_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const plot_action_tool_1 = require(471) /* ./plot_action_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class RedoToolView extends plot_action_tool_1.PlotActionToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.plot_view.state.changed, () => this.model.disabled = !this.plot_view.state.can_redo);
        }
        doit() {
            const state = this.plot_view.state.redo();
            if ((state === null || state === void 0 ? void 0 : state.range) != null) {
                this.plot_view.trigger_ranges_update_event();
            }
        }
    }
    exports.RedoToolView = RedoToolView;
    RedoToolView.__name__ = "RedoToolView";
    class RedoTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Redo";
            this.tool_icon = icons_css_1.tool_icon_redo;
        }
    }
    exports.RedoTool = RedoTool;
    _a = RedoTool;
    RedoTool.__name__ = "RedoTool";
    (() => {
        _a.prototype.default_view = RedoToolView;
        _a.override({
            disabled: true,
        });
        _a.register_alias("redo", () => new _a());
    })();
},
/* models/tools/actions/plot_action_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(283) /* ./action_tool */;
    class PlotActionToolView extends action_tool_1.ActionToolView {
        get plot_view() {
            return this.parent;
        }
    }
    exports.PlotActionToolView = PlotActionToolView;
    PlotActionToolView.__name__ = "PlotActionToolView";
    class PlotActionTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.PlotActionTool = PlotActionTool;
    PlotActionTool.__name__ = "PlotActionTool";
},
/* models/tools/actions/reset_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const plot_action_tool_1 = require(471) /* ./plot_action_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class ResetToolView extends plot_action_tool_1.PlotActionToolView {
        doit() {
            // reset() issues the RangesUpdate event
            this.plot_view.reset();
        }
    }
    exports.ResetToolView = ResetToolView;
    ResetToolView.__name__ = "ResetToolView";
    class ResetTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Reset";
            this.tool_icon = icons_css_1.tool_icon_reset;
        }
    }
    exports.ResetTool = ResetTool;
    _a = ResetTool;
    ResetTool.__name__ = "ResetTool";
    (() => {
        _a.prototype.default_view = ResetToolView;
        _a.register_alias("reset", () => new _a());
    })();
},
/* models/tools/actions/save_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const action_tool_1 = require(283) /* ./action_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class SaveToolView extends action_tool_1.ActionToolView {
        async copy() {
            const blob = await this.parent.export().to_blob();
            const item = new ClipboardItem({ [blob.type]: blob });
            await navigator.clipboard.write([item]);
        }
        async save(name) {
            const blob = await this.parent.export().to_blob();
            const 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"));
        }
        doit(action = "save") {
            var _b;
            switch (action) {
                case "save": {
                    const filename = (_b = this.model.filename) !== null && _b !== void 0 ? _b : prompt("Enter filename", "bokeh_plot");
                    if (filename != null) {
                        this.save(filename);
                    }
                    break;
                }
                case "copy": {
                    this.copy();
                    break;
                }
            }
        }
    }
    exports.SaveToolView = SaveToolView;
    SaveToolView.__name__ = "SaveToolView";
    class SaveTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Save";
            this.tool_icon = icons_css_1.tool_icon_save;
        }
        get menu() {
            return [
                {
                    icon: "bk-tool-icon-copy",
                    tooltip: "Copy image to clipboard",
                    if: () => typeof ClipboardItem !== "undefined",
                    handler: () => {
                        this.do.emit("copy");
                    },
                },
            ];
        }
    }
    exports.SaveTool = SaveTool;
    _a = SaveTool;
    SaveTool.__name__ = "SaveTool";
    (() => {
        _a.prototype.default_view = SaveToolView;
        _a.define(({ String, Nullable }) => ({
            filename: [Nullable(String), null],
        }));
        _a.register_alias("save", () => new _a());
    })();
},
/* models/tools/actions/undo_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const plot_action_tool_1 = require(471) /* ./plot_action_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class UndoToolView extends plot_action_tool_1.PlotActionToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.plot_view.state.changed, () => this.model.disabled = !this.plot_view.state.can_undo);
        }
        doit() {
            const state = this.plot_view.state.undo();
            if ((state === null || state === void 0 ? void 0 : state.range) != null) {
                this.plot_view.trigger_ranges_update_event();
            }
        }
    }
    exports.UndoToolView = UndoToolView;
    UndoToolView.__name__ = "UndoToolView";
    class UndoTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Undo";
            this.tool_icon = icons_css_1.tool_icon_undo;
        }
    }
    exports.UndoTool = UndoTool;
    _a = UndoTool;
    UndoTool.__name__ = "UndoTool";
    (() => {
        _a.prototype.default_view = UndoToolView;
        _a.override({
            disabled: true,
        });
        _a.register_alias("undo", () => new _a());
    })();
},
/* models/tools/actions/zoom_in_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const zoom_base_tool_1 = require(476) /* ./zoom_base_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class ZoomInToolView extends zoom_base_tool_1.ZoomBaseToolView {
        get factor() {
            return this.model.factor;
        }
    }
    exports.ZoomInToolView = ZoomInToolView;
    ZoomInToolView.__name__ = "ZoomInToolView";
    class ZoomInTool extends zoom_base_tool_1.ZoomBaseTool {
        constructor(attrs) {
            super(attrs);
            this.maintain_focus = true;
            this.tool_name = "Zoom In";
            this.tool_icon = icons_css_1.tool_icon_zoom_in;
        }
    }
    exports.ZoomInTool = ZoomInTool;
    _a = ZoomInTool;
    ZoomInTool.__name__ = "ZoomInTool";
    (() => {
        _a.prototype.default_view = ZoomInToolView;
        _a.register_alias("zoom_in", () => new _a({ dimensions: "both" }));
        _a.register_alias("xzoom_in", () => new _a({ dimensions: "width" }));
        _a.register_alias("yzoom_in", () => new _a({ dimensions: "height" }));
    })();
},
/* models/tools/actions/zoom_base_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const plot_action_tool_1 = require(471) /* ./plot_action_tool */;
    const data_renderer_1 = require(202) /* ../../renderers/data_renderer */;
    const composite_scale_1 = require(94) /* ../../scales/composite_scale */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const zoom_1 = require(477) /* ../../../core/util/zoom */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    const logging_1 = require(19) /* ../../../core/logging */;
    class ZoomBaseToolView extends plot_action_tool_1.PlotActionToolView {
        doit() {
            var _b;
            // restrict to axis configured in tool's dimensions property
            const { dimensions } = this.model;
            const x_axis = dimensions == "width" || dimensions == "both";
            const y_axis = dimensions == "height" || dimensions == "both";
            const { frame } = this.plot_view;
            const { x_target, y_target } = frame;
            const x_frame_scales = new Map(frame.x_scales);
            const y_frame_scales = new Map(frame.y_scales);
            const { renderers } = this.model;
            if (renderers != "auto") {
                const x_range_names = new Set();
                const y_range_names = new Set();
                for (const renderer of renderers) {
                    if (renderer.coordinates == null) {
                        x_range_names.add(renderer.x_range_name);
                        y_range_names.add(renderer.y_range_name);
                    }
                }
                for (const name of x_frame_scales.keys()) {
                    if (!x_range_names.has(name)) {
                        x_frame_scales.delete(name);
                    }
                }
                for (const name of y_frame_scales.keys()) {
                    if (!y_range_names.has(name)) {
                        y_frame_scales.delete(name);
                    }
                }
            }
            const x_scales = [...x_frame_scales.values()];
            const y_scales = [...y_frame_scales.values()];
            const data_renderers = renderers != "auto" ? renderers : this.plot_view.model.data_renderers;
            for (const renderer of data_renderers) {
                if (renderer.coordinates == null) {
                    continue;
                }
                const rv = this.plot_view.renderer_view(renderer);
                (0, assert_1.assert)(rv != null);
                const process = (scale, dim) => {
                    const { level } = this.model;
                    for (let i = 0; i < level; i++) {
                        if (scale instanceof composite_scale_1.CompositeScale) {
                            scale = scale.source_scale;
                        }
                        else {
                            logging_1.logger.warn(`can't reach sub-coordinate level ${level} for ${scale} in ${dim} dimension; stopped at ${i}`);
                            break;
                        }
                    }
                    if (scale instanceof composite_scale_1.CompositeScale) {
                        return scale.target_scale;
                    }
                    else {
                        return scale;
                    }
                };
                const { x_scale, y_scale } = rv.coordinates;
                x_scales.push(process(x_scale, "x"));
                y_scales.push(process(y_scale, "y"));
            }
            const zoom_info = (0, zoom_1.scale_range)(x_scales, y_scales, x_target, y_target, this.factor, x_axis, y_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_view.model);
            this.plot_view.trigger_ranges_update_event();
        }
    }
    exports.ZoomBaseToolView = ZoomBaseToolView;
    ZoomBaseToolView.__name__ = "ZoomBaseToolView";
    class ZoomBaseTool extends plot_action_tool_1.PlotActionTool {
        constructor(attrs) {
            super(attrs);
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.ZoomBaseTool = ZoomBaseTool;
    _a = ZoomBaseTool;
    ZoomBaseTool.__name__ = "ZoomBaseTool";
    (() => {
        _a.define(({ Percent, Or, Array, Ref, Auto, NonNegative, Int }) => ({
            factor: [Percent, 0.1],
            dimensions: [enums_1.Dimensions, "both"],
            renderers: [Or(Array(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
            level: [NonNegative(Int), 0],
        }));
    })();
},
/* core/util/zoom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const math_1 = require(11) /* ./math */;
    function scale_interval(range, factor, center) {
        const [min, max] = (0, math_1.minmax)(range.start, range.end);
        const x = center !== null && center !== void 0 ? center : (max + min) / 2.0;
        const x0 = min - (min - x) * factor;
        const x1 = max - (max - x) * factor;
        return [x0, x1];
    }
    exports.scale_interval = scale_interval;
    function get_info(scales, [sxy0, sxy1]) {
        const info = new Map();
        for (const scale of scales) {
            const [start, end] = scale.r_invert(sxy0, sxy1);
            info.set(scale.source_range, { start, end });
        }
        return info;
    }
    exports.get_info = get_info;
    function rescale(scales, factor, center) {
        const output = new Map();
        for (const scale of scales) {
            const [v0, v1] = scale_interval(scale.target_range, factor, center);
            const [start, end] = scale.r_invert(v0, v1);
            output.set(scale.source_range, { start, end });
        }
        return output;
    }
    exports.rescale = rescale;
    function scale_range(x_scales, y_scales, _x_target, _y_range, factor, x_axis = true, y_axis = true, center) {
        /*
         * Utility function for zoom tools to calculate/create the zoom_info object
         * of the form required by `PlotView.update_range`.
         */
        const x_factor = x_axis ? factor : 0;
        //const [sx0, sx1] = scale_interval(x_target, x_factor, center?.x)
        //const xrs = get_info(x_scales, [sx0, sx1])
        const xrs = rescale(x_scales, x_factor, center === null || center === void 0 ? void 0 : center.x);
        const y_factor = y_axis ? factor : 0;
        //const [sy0, sy1] = scale_interval(y_range, y_factor, center?.y)
        //const yrs = get_info(y_scales, [sy0, sy1])
        const yrs = rescale(y_scales, y_factor, center === null || center === void 0 ? void 0 : center.y);
        // 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, yrs, factor };
    }
    exports.scale_range = scale_range;
},
/* models/tools/actions/zoom_out_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const zoom_base_tool_1 = require(476) /* ./zoom_base_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class ZoomOutToolView extends zoom_base_tool_1.ZoomBaseToolView {
        get factor() {
            const { factor } = this.model;
            return -factor / (1 - factor);
        }
    }
    exports.ZoomOutToolView = ZoomOutToolView;
    ZoomOutToolView.__name__ = "ZoomOutToolView";
    class ZoomOutTool extends zoom_base_tool_1.ZoomBaseTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Zoom Out";
            this.tool_icon = icons_css_1.tool_icon_zoom_out;
        }
    }
    exports.ZoomOutTool = ZoomOutTool;
    _a = ZoomOutTool;
    ZoomOutTool.__name__ = "ZoomOutTool";
    (() => {
        _a.prototype.default_view = ZoomOutToolView;
        _a.define(({ Boolean }) => ({
            maintain_focus: [Boolean, true],
        }));
        _a.register_alias("zoom_out", () => new _a({ dimensions: "both" }));
        _a.register_alias("xzoom_out", () => new _a({ dimensions: "width" }));
        _a.register_alias("yzoom_out", () => new _a({ dimensions: "height" }));
    })();
},
/* models/tools/edit/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var edit_tool_1 = require(480) /* ./edit_tool */;
    __esExport("EditTool", edit_tool_1.EditTool);
    var box_edit_tool_1 = require(481) /* ./box_edit_tool */;
    __esExport("BoxEditTool", box_edit_tool_1.BoxEditTool);
    var freehand_draw_tool_1 = require(482) /* ./freehand_draw_tool */;
    __esExport("FreehandDrawTool", freehand_draw_tool_1.FreehandDrawTool);
    var line_edit_tool_1 = require(483) /* ./line_edit_tool */;
    __esExport("LineEditTool", line_edit_tool_1.LineEditTool);
    var point_draw_tool_1 = require(485) /* ./point_draw_tool */;
    __esExport("PointDrawTool", point_draw_tool_1.PointDrawTool);
    var poly_draw_tool_1 = require(486) /* ./poly_draw_tool */;
    __esExport("PolyDrawTool", poly_draw_tool_1.PolyDrawTool);
    var poly_tool_1 = require(487) /* ./poly_tool */;
    __esExport("PolyTool", poly_tool_1.PolyTool);
    var poly_edit_tool_1 = require(488) /* ./poly_edit_tool */;
    __esExport("PolyEditTool", poly_edit_tool_1.PolyEditTool);
},
/* models/tools/edit/edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const array_1 = require(10) /* ../../../core/util/array */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    const gesture_tool_1 = require(280) /* ../gestures/gesture_tool */;
    class EditToolView extends gesture_tool_1.GestureToolView {
        constructor() {
            super(...arguments);
            this._mouse_in_frame = true;
        }
        _select_mode(ev) {
            const { shift, ctrl } = ev.modifiers;
            if (!shift && !ctrl)
                return "replace";
            else if (shift && !ctrl)
                return "append";
            else if (!shift && ctrl)
                return "intersect";
            else if (shift && ctrl)
                return "subtract";
            else
                (0, assert_1.unreachable)();
        }
        _move_enter(_e) {
            this._mouse_in_frame = true;
        }
        _move_exit(_e) {
            this._mouse_in_frame = false;
        }
        _map_drag(sx, sy, renderer) {
            // Maps screen to data coordinates
            const frame = this.plot_view.frame;
            if (!frame.bbox.contains(sx, sy)) {
                return null;
            }
            const renderer_view = this.plot_view.renderer_view(renderer);
            if (renderer_view == null)
                return null;
            const x = renderer_view.coordinates.x_scale.invert(sx);
            const y = renderer_view.coordinates.y_scale.invert(sy);
            return [x, y];
        }
        _delete_selected(renderer) {
            // Deletes all selected rows in the ColumnDataSource
            const cds = renderer.data_source;
            const indices = cds.selected.indices;
            indices.sort();
            for (const column of cds.columns()) {
                const values = cds.get_array(column);
                for (let index = 0; index < indices.length; index++) {
                    const ind = indices[index];
                    values.splice(ind - index, 1);
                }
            }
            this._emit_cds_changes(cds);
        }
        _pop_glyphs(cds, num_objects) {
            // Pops rows in the CDS until only num_objects are left
            const columns = cds.columns();
            if (num_objects == 0 || columns.length == 0)
                return;
            for (const column of columns) {
                let array = cds.get_array(column);
                const 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);
            }
        }
        _emit_cds_changes(cds, redraw = true, clear = true, emit = true) {
            if (clear)
                cds.selection_manager.clear();
            if (redraw)
                cds.change.emit();
            if (emit) {
                const { data } = cds;
                cds.setv({ data }, { check_eq: false });
            }
        }
        _drag_points(ev, renderers, dim = "both") {
            if (this._basepoint == null)
                return;
            const [bx, by] = this._basepoint;
            for (const renderer of renderers) {
                const basepoint = this._map_drag(bx, by, renderer);
                const point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null || basepoint == null) {
                    continue;
                }
                const [x, y] = point;
                const [px, py] = basepoint;
                const [dx, dy] = [x - px, y - py];
                // Type once dataspecs are typed
                const glyph = renderer.glyph;
                const cds = renderer.data_source;
                const [xkey, ykey] = [glyph.x.field, glyph.y.field];
                for (const index of cds.selected.indices) {
                    if (xkey && (dim == "width" || dim == "both")) {
                        cds.data[xkey][index] += dx;
                    }
                    if (ykey && (dim == "height" || dim == "both")) {
                        cds.data[ykey][index] += dy;
                    }
                }
                cds.change.emit();
            }
            this._basepoint = [ev.sx, ev.sy];
        }
        _pad_empty_columns(cds, coord_columns) {
            // Pad ColumnDataSource non-coordinate columns with empty_value
            for (const column of cds.columns()) {
                if (!(0, array_1.includes)(coord_columns, column))
                    cds.get_array(column).push(this.model.empty_value);
            }
        }
        _select_event(ev, mode, renderers) {
            // Process selection event on the supplied renderers and return selected renderers
            const frame = this.plot_view.frame;
            const { sx, sy } = ev;
            if (!frame.bbox.contains(sx, sy)) {
                return [];
            }
            const geometry = { type: "point", sx, sy };
            const selected = [];
            for (const renderer of renderers) {
                const sm = renderer.get_selection_manager();
                const cds = renderer.data_source;
                const view = this.plot_view.renderer_view(renderer);
                if (view != null) {
                    const did_hit = sm.select([view], geometry, true, mode);
                    if (did_hit) {
                        selected.push(renderer);
                    }
                    cds.properties.selected.change.emit();
                }
            }
            return selected;
        }
    }
    exports.EditToolView = EditToolView;
    EditToolView.__name__ = "EditToolView";
    class EditTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.EditTool = EditTool;
    _a = EditTool;
    EditTool.__name__ = "EditTool";
    (() => {
        _a.define(({ Unknown }) => ({
            empty_value: [Unknown, 0],
        }));
    })();
},
/* models/tools/edit/box_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const enums_1 = require(20) /* ../../../core/enums */;
    const vectorization_1 = require(28) /* ../../../core/vectorization */;
    const xy_glyph_1 = require(204) /* ../../glyphs/xy_glyph */;
    const rect_1 = require(350) /* ../../glyphs/rect */;
    const block_1 = require(330) /* ../../glyphs/block */;
    const quad_1 = require(347) /* ../../glyphs/quad */;
    const hbar_1 = require(335) /* ../../glyphs/hbar */;
    const vbar_1 = require(359) /* ../../glyphs/vbar */;
    const hstrip_1 = require(337) /* ../../glyphs/hstrip */;
    const vstrip_1 = require(361) /* ../../glyphs/vstrip */;
    const glyph_renderer_1 = require(201) /* ../../renderers/glyph_renderer */;
    const edit_tool_1 = require(480) /* ./edit_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    const object_1 = require(9) /* ../../../core/util/object */;
    class BoxEditToolView extends edit_tool_1.EditToolView {
        constructor() {
            super(...arguments);
            this._recent_renderers = [];
        }
        _tap(ev) {
            if ((this._draw_basepoint != null) || (this._basepoint != null))
                return;
            this._recent_renderers = this._select_event(ev, this._select_mode(ev), this.model.renderers);
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame)
                return;
            for (const renderer of this.model.renderers) {
                if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                }
                else if (ev.key == "Escape") {
                    // Type properly once selection_manager is typed
                    const cds = renderer.data_source;
                    cds.selection_manager.clear();
                }
            }
        }
        _set_extent([sx0, sx1], [sy0, sy1], append, emit = false) {
            var _b;
            const renderer = (_b = this._recent_renderers[0]) !== null && _b !== void 0 ? _b : this.model.renderers[0];
            const renderer_view = this.plot_view.renderer_view(renderer);
            if (renderer_view == null)
                return;
            const { glyph } = renderer;
            const cds = renderer.data_source;
            const [x0, x1] = renderer_view.coordinates.x_scale.r_invert(sx0, sx1);
            const [y0, y1] = renderer_view.coordinates.y_scale.r_invert(sy0, sy1);
            const fields = (() => {
                if (glyph instanceof rect_1.Rect) {
                    const { x, y, width, height } = glyph;
                    if ((0, vectorization_1.isField)(x) && (0, vectorization_1.isField)(y) && (0, vectorization_1.isField)(width) && (0, vectorization_1.isField)(height)) {
                        return {
                            [x.field]: (x0 + x1) / 2,
                            [y.field]: (y0 + y1) / 2,
                            [width.field]: x1 - x0,
                            [height.field]: y1 - y0,
                        };
                    }
                }
                else if (glyph instanceof block_1.Block) {
                    const { x, y, width, height } = glyph;
                    if ((0, vectorization_1.isField)(x) && (0, vectorization_1.isField)(y) && (0, vectorization_1.isField)(width) && (0, vectorization_1.isField)(height)) {
                        return {
                            [x.field]: x0,
                            [y.field]: y0,
                            [width.field]: x1 - x0,
                            [height.field]: y1 - y0,
                        };
                    }
                }
                else if (glyph instanceof quad_1.Quad) {
                    const { right, bottom, left, top } = glyph;
                    if ((0, vectorization_1.isField)(right) && (0, vectorization_1.isField)(bottom) && (0, vectorization_1.isField)(left) && (0, vectorization_1.isField)(top)) {
                        return {
                            [right.field]: x1,
                            [bottom.field]: y0,
                            [left.field]: x0,
                            [top.field]: y1,
                        };
                    }
                }
                else if (glyph instanceof hbar_1.HBar) {
                    const { left, y, height, right } = glyph;
                    if ((0, vectorization_1.isField)(left) && (0, vectorization_1.isField)(y) && (0, vectorization_1.isField)(height) && (0, vectorization_1.isField)(right)) {
                        return {
                            [left.field]: x0,
                            [y.field]: y1,
                            [height.field]: y1 - y0,
                            [right.field]: x1,
                        };
                    }
                }
                else if (glyph instanceof vbar_1.VBar) {
                    const { x, bottom, width, top } = glyph;
                    if ((0, vectorization_1.isField)(x) && (0, vectorization_1.isField)(bottom) && (0, vectorization_1.isField)(width) && (0, vectorization_1.isField)(top)) {
                        return {
                            [x.field]: x0,
                            [bottom.field]: y0,
                            [width.field]: x1 - x0,
                            [top.field]: y1,
                        };
                    }
                }
                else if (glyph instanceof hstrip_1.HStrip) {
                    const { y0, y1 } = glyph;
                    if ((0, vectorization_1.isField)(y0) && (0, vectorization_1.isField)(y1)) {
                        return {
                            [y0.field]: y0,
                            [y1.field]: y1,
                        };
                    }
                }
                else if (glyph instanceof vstrip_1.VStrip) {
                    const { x0, x1 } = glyph;
                    if ((0, vectorization_1.isField)(x0) && (0, vectorization_1.isField)(x1)) {
                        return {
                            [x0.field]: x0,
                            [x1.field]: x1,
                        };
                    }
                }
                else {
                    (0, assert_1.unreachable)(`'${glyph.type}' is not supported"`);
                }
                return null;
            })();
            if (fields == null) {
                return;
            }
            if (append) {
                this._pop_glyphs(cds, this.model.num_objects);
                for (const [key, val] of (0, object_1.entries)(fields)) {
                    cds.get_array(key).push(val);
                }
                this._pad_empty_columns(cds, (0, object_1.keys)(fields));
            }
            else {
                const length = cds.get_length();
                if (length == null)
                    return;
                const index = length - 1;
                for (const [key, val] of (0, object_1.entries)(fields)) {
                    cds.data[key][index] = val;
                }
            }
            this._emit_cds_changes(cds, true, false, emit);
        }
        _update_box(ev, append = false, emit = false) {
            if (this._draw_basepoint == null)
                return;
            const curpoint = [ev.sx, ev.sy];
            const frame = this.plot_view.frame;
            const dims = this.model.dimensions;
            const [sxlim, sylim] = this.model._get_dim_limits(this._draw_basepoint, curpoint, frame, dims);
            this._set_extent(sxlim, sylim, append, emit);
        }
        _doubletap(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);
            }
        }
        _move(ev) {
            this._update_box(ev, false, false);
        }
        _pan_start(ev) {
            if (ev.modifiers.shift) {
                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._recent_renderers = this._select_event(ev, "append", this.model.renderers);
                this._basepoint = [ev.sx, ev.sy];
            }
        }
        _pan(ev, append = false, emit = false) {
            if (ev.modifiers.shift) {
                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);
            }
        }
        _drag_points(ev, renderers, dim = "both") {
            if (this._basepoint == null)
                return;
            const [bx, by] = this._basepoint;
            for (const renderer of renderers) {
                const basepoint = this._map_drag(bx, by, renderer);
                const point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null || basepoint == null) {
                    continue;
                }
                const [x, y] = point;
                const [px, py] = basepoint;
                const dx = dim == "width" || dim == "both" ? x - px : 0;
                const dy = dim == "height" || dim == "both" ? y - py : 0;
                const { glyph } = renderer;
                const cds = renderer.data_source;
                const fields = {};
                if (glyph instanceof xy_glyph_1.XYGlyph) {
                    const { x, y } = glyph;
                    if ((0, vectorization_1.isField)(x))
                        fields[x.field] = dx;
                    if ((0, vectorization_1.isField)(y))
                        fields[y.field] = dy;
                }
                else if (glyph instanceof block_1.Block) {
                    const { x, y } = glyph;
                    if ((0, vectorization_1.isField)(x))
                        fields[x.field] = dx;
                    if ((0, vectorization_1.isField)(y))
                        fields[y.field] = dy;
                }
                else if (glyph instanceof quad_1.Quad) {
                    const { right, bottom, left, top } = glyph;
                    if ((0, vectorization_1.isField)(left) && (0, vectorization_1.isField)(right)) {
                        fields[left.field] = dx;
                        fields[right.field] = dx;
                    }
                    if ((0, vectorization_1.isField)(top) && (0, vectorization_1.isField)(bottom)) {
                        fields[top.field] = dy;
                        fields[bottom.field] = dy;
                    }
                }
                else if (glyph instanceof hbar_1.HBar) {
                    const { left, right, y } = glyph;
                    if ((0, vectorization_1.isField)(left) && (0, vectorization_1.isField)(right)) {
                        fields[left.field] = dx;
                        fields[right.field] = dx;
                    }
                    if ((0, vectorization_1.isField)(y)) {
                        fields[y.field] = dy;
                    }
                }
                else if (glyph instanceof vbar_1.VBar) {
                    const { x, top, bottom } = glyph;
                    if ((0, vectorization_1.isField)(x)) {
                        fields[x.field] = dx;
                    }
                    if ((0, vectorization_1.isField)(top) && (0, vectorization_1.isField)(bottom)) {
                        fields[top.field] = dy;
                        fields[bottom.field] = dy;
                    }
                }
                else if (glyph instanceof hstrip_1.HStrip) {
                    const { y0, y1 } = glyph;
                    if ((0, vectorization_1.isField)(y0) && (0, vectorization_1.isField)(y1)) {
                        fields[y0.field] = dy;
                        fields[y1.field] = dy;
                    }
                }
                else if (glyph instanceof vstrip_1.VStrip) {
                    const { x0, x1 } = glyph;
                    if ((0, vectorization_1.isField)(x0) && (0, vectorization_1.isField)(x1)) {
                        fields[x0.field] = dx;
                        fields[x1.field] = dx;
                    }
                }
                else {
                    (0, assert_1.unreachable)(`'${glyph.type}' is not supported"`);
                }
                for (const index of cds.selected.indices) {
                    for (const [key, val] of (0, object_1.entries)(fields)) {
                        cds.data[key][index] += val;
                    }
                }
                cds.change.emit();
            }
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan_end(ev) {
            this._pan(ev, false, true);
            if (ev.modifiers.shift) {
                this._draw_basepoint = null;
            }
            else {
                this._basepoint = null;
                for (const renderer of this.model.renderers)
                    this._emit_cds_changes(renderer.data_source, false, true, true);
            }
        }
    }
    exports.BoxEditToolView = BoxEditToolView;
    BoxEditToolView.__name__ = "BoxEditToolView";
    class BoxEditTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Box Edit Tool";
            this.tool_icon = icons_css_1.tool_icon_box_edit;
            this.event_type = ["tap", "pan", "move"];
            this.default_order = 1;
        }
    }
    exports.BoxEditTool = BoxEditTool;
    _a = BoxEditTool;
    BoxEditTool.__name__ = "BoxEditTool";
    (() => {
        _a.prototype.default_view = BoxEditToolView;
        _a.define(({ Int, Array, Ref }) => ({
            dimensions: [enums_1.Dimensions, "both"],
            num_objects: [Int, 0],
            renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
        }));
    })();
},
/* models/tools/edit/freehand_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const types_1 = require(8) /* ../../../core/util/types */;
    const edit_tool_1 = require(480) /* ./edit_tool */;
    const glyph_renderer_1 = require(201) /* ../../renderers/glyph_renderer */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class FreehandDrawToolView extends edit_tool_1.EditToolView {
        _draw(ev, mode, emit = false) {
            if (!this.model.active)
                return;
            const renderer = this.model.renderers[0];
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            const [x, y] = point;
            const cds = renderer.data_source;
            const glyph = renderer.glyph;
            const [xkey, ykey] = [glyph.xs.field, glyph.ys.field];
            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) {
                    const xidx = cds.data[xkey].length - 1;
                    let 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) {
                    const yidx = cds.data[ykey].length - 1;
                    let 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);
        }
        _pan_start(ev) {
            this._draw(ev, "new");
        }
        _pan(ev) {
            this._draw(ev, "add");
        }
        _pan_end(ev) {
            this._draw(ev, "add", true);
        }
        _tap(ev) {
            this._select_event(ev, this._select_mode(ev), this.model.renderers);
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame)
                return;
            for (const renderer of this.model.renderers) {
                if (ev.key == "Escape") {
                    renderer.data_source.selection_manager.clear();
                }
                else if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                }
            }
        }
    }
    exports.FreehandDrawToolView = FreehandDrawToolView;
    FreehandDrawToolView.__name__ = "FreehandDrawToolView";
    class FreehandDrawTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Freehand Draw Tool";
            this.tool_icon = icons_css_1.tool_icon_freehand_draw;
            this.event_type = ["pan", "tap"];
            this.default_order = 3;
        }
    }
    exports.FreehandDrawTool = FreehandDrawTool;
    _a = FreehandDrawTool;
    FreehandDrawTool.__name__ = "FreehandDrawTool";
    (() => {
        _a.prototype.default_view = FreehandDrawToolView;
        _a.define(({ Int, Array, Ref }) => ({
            num_objects: [Int, 0],
            renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
        }));
        _a.register_alias("freehand_draw", () => new _a());
    })();
},
/* models/tools/edit/line_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const enums_1 = require(20) /* ../../../core/enums */;
    const glyph_renderer_1 = require(201) /* ../../renderers/glyph_renderer */;
    const line_tool_1 = require(484) /* ./line_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class LineEditToolView extends line_tool_1.LineToolView {
        constructor() {
            super(...arguments);
            this._drawing = false;
        }
        _doubletap(ev) {
            if (!this.model.active)
                return;
            const renderers = this.model.renderers;
            for (const renderer of renderers) {
                const line_selected = this._select_event(ev, "replace", [renderer]);
                if (line_selected.length == 1) {
                    this._selected_renderer = renderer;
                }
            }
            this._show_intersections();
            this._update_line_cds();
        }
        _show_intersections() {
            if (!this.model.active)
                return;
            if (this._selected_renderer == null)
                return;
            const renderers = this.model.renderers;
            if (renderers.length == 0) {
                this._set_intersection([], []);
                this._selected_renderer = null;
                this._drawing = false;
                return;
            }
            const cds = this._selected_renderer.data_source;
            const glyph = this._selected_renderer.glyph;
            const [xkey, ykey] = [glyph.x.field, glyph.y.field];
            const x = cds.get_array(xkey);
            const y = cds.get_array(ykey);
            this._set_intersection(x, y);
        }
        _tap(ev) {
            const renderer = this.model.intersection_renderer;
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            else if (this._drawing && this._selected_renderer != null) {
                const mode = this._select_mode(ev);
                const selected_points = this._select_event(ev, mode, [renderer]);
                if (selected_points.length == 0) {
                    return;
                }
            }
            const mode = this._select_mode(ev);
            this._select_event(ev, mode, [renderer]);
            this._select_event(ev, mode, this.model.renderers);
        }
        _update_line_cds() {
            if (this._selected_renderer == null)
                return;
            const point_glyph = this.model.intersection_renderer.glyph;
            const point_cds = this.model.intersection_renderer.data_source;
            const [pxkey, pykey] = [point_glyph.x.field, point_glyph.y.field];
            if (pxkey && pykey) {
                const x = point_cds.data[pxkey];
                const 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);
        }
        _pan_start(ev) {
            this._select_event(ev, "append", [this.model.intersection_renderer]);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (this._basepoint == null)
                return;
            this._drag_points(ev, [this.model.intersection_renderer], this.model.dimensions);
            if (this._selected_renderer != null)
                this._selected_renderer.data_source.change.emit();
        }
        _pan_end(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 != null) {
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            this._basepoint = null;
        }
        activate() {
            this._drawing = true;
        }
        deactivate() {
            if (this._selected_renderer == null) {
                return;
            }
            else if (this._drawing) {
                this._drawing = false;
            }
            this._hide_intersections();
        }
    }
    exports.LineEditToolView = LineEditToolView;
    LineEditToolView.__name__ = "LineEditToolView";
    class LineEditTool extends line_tool_1.LineTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Line Edit Tool";
            this.tool_icon = icons_css_1.tool_icon_line_edit;
            this.event_type = ["tap", "pan", "move"];
            this.default_order = 4;
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.LineEditTool = LineEditTool;
    _a = LineEditTool;
    LineEditTool.__name__ = "LineEditTool";
    (() => {
        _a.prototype.default_view = LineEditToolView;
        _a.define(({ Array, Ref }) => ({
            dimensions: [enums_1.Dimensions, "both"],
            renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
        }));
    })();
},
/* models/tools/edit/line_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const types_1 = require(8) /* ../../../core/util/types */;
    const edit_tool_1 = require(480) /* ./edit_tool */;
    class LineToolView extends edit_tool_1.EditToolView {
        _set_intersection(x, y) {
            const point_glyph = this.model.intersection_renderer.glyph;
            const point_cds = this.model.intersection_renderer.data_source;
            const [pxkey, pykey] = [point_glyph.x.field, point_glyph.y.field];
            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);
        }
        _hide_intersections() {
            this._set_intersection([], []);
        }
    }
    exports.LineToolView = LineToolView;
    LineToolView.__name__ = "LineToolView";
    class LineTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LineTool = LineTool;
    _a = LineTool;
    LineTool.__name__ = "LineTool";
    (() => {
        _a.define(({ AnyRef }) => ({
            intersection_renderer: [AnyRef()],
        }));
    })();
},
/* models/tools/edit/point_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const glyph_renderer_1 = require(201) /* ../../renderers/glyph_renderer */;
    const edit_tool_1 = require(480) /* ./edit_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class PointDrawToolView extends edit_tool_1.EditToolView {
        _tap(ev) {
            const renderers = this._select_event(ev, this._select_mode(ev), this.model.renderers);
            if (renderers.length != 0 || !this.model.add) {
                return;
            }
            const renderer = this.model.renderers[0];
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            // Type once dataspecs are typed
            const glyph = renderer.glyph;
            const cds = renderer.data_source;
            const [xkey, ykey] = [glyph.x.field, glyph.y.field];
            const [x, y] = point;
            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]);
            const { data } = cds;
            cds.setv({ data }, { check_eq: false }); // XXX: inplace updates
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame)
                return;
            for (const renderer of this.model.renderers) {
                if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                }
                else if (ev.key == "Escape") {
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        _pan_start(ev) {
            if (!this.model.drag)
                return;
            this._select_event(ev, "append", this.model.renderers);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (!this.model.drag || this._basepoint == null)
                return;
            this._drag_points(ev, this.model.renderers);
        }
        _pan_end(ev) {
            if (!this.model.drag)
                return;
            this._pan(ev);
            for (const renderer of this.model.renderers)
                this._emit_cds_changes(renderer.data_source, false, true, true);
            this._basepoint = null;
        }
    }
    exports.PointDrawToolView = PointDrawToolView;
    PointDrawToolView.__name__ = "PointDrawToolView";
    class PointDrawTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Point Draw Tool";
            this.tool_icon = icons_css_1.tool_icon_point_draw;
            this.event_type = ["tap", "pan", "move"];
            this.default_order = 2;
        }
    }
    exports.PointDrawTool = PointDrawTool;
    _a = PointDrawTool;
    PointDrawTool.__name__ = "PointDrawTool";
    (() => {
        _a.prototype.default_view = PointDrawToolView;
        _a.define(({ Boolean, Int, Array, Ref }) => ({
            add: [Boolean, true],
            drag: [Boolean, true],
            num_objects: [Int, 0],
            renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
        }));
    })();
},
/* models/tools/edit/poly_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const types_1 = require(8) /* ../../../core/util/types */;
    const glyph_renderer_1 = require(201) /* ../../renderers/glyph_renderer */;
    const poly_tool_1 = require(487) /* ./poly_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class PolyDrawToolView extends poly_tool_1.PolyToolView {
        constructor() {
            super(...arguments);
            this._drawing = false;
            this._initialized = false;
        }
        _tap(ev) {
            if (this._drawing)
                this._draw(ev, "add", true);
            else
                this._select_event(ev, this._select_mode(ev), this.model.renderers);
        }
        _draw(ev, mode, emit = false) {
            const renderer = this.model.renderers[0];
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (!this._initialized)
                this.activate(); // Ensure that activate has been called
            if (point == null)
                return;
            const [x, y] = this._snap_to_vertex(ev, ...point);
            const cds = renderer.data_source;
            const glyph = renderer.glyph;
            const [xkey, ykey] = [glyph.xs.field, glyph.ys.field];
            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) {
                    const xs = cds.data[xkey][cds.data[xkey].length - 1];
                    xs[xs.length - 1] = x;
                }
                if (ykey) {
                    const ys = cds.data[ykey][cds.data[ykey].length - 1];
                    ys[ys.length - 1] = y;
                }
            }
            else if (mode == "add") {
                if (xkey) {
                    const xidx = cds.data[xkey].length - 1;
                    let xs = cds.get_array(xkey)[xidx];
                    const 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) {
                    const yidx = cds.data[ykey].length - 1;
                    let ys = cds.get_array(ykey)[yidx];
                    const 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);
        }
        _show_vertices() {
            if (!this.model.active) {
                return;
            }
            const xs = [];
            const ys = [];
            for (let i = 0; i < this.model.renderers.length; i++) {
                const renderer = this.model.renderers[i];
                const cds = renderer.data_source;
                const glyph = renderer.glyph;
                const [xkey, ykey] = [glyph.xs.field, glyph.ys.field];
                if (xkey) {
                    for (const array of cds.get_array(xkey)) {
                        xs.push(...array);
                    }
                }
                if (ykey) {
                    for (const array of cds.get_array(ykey)) {
                        ys.push(...array);
                    }
                }
                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);
        }
        _doubletap(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);
            }
        }
        _move(ev) {
            if (this._drawing) {
                this._draw(ev, "edit");
            }
        }
        _remove() {
            const renderer = this.model.renderers[0];
            const cds = renderer.data_source;
            const glyph = renderer.glyph;
            const [xkey, ykey] = [glyph.xs.field, glyph.ys.field];
            if (xkey) {
                const xidx = cds.data[xkey].length - 1;
                const xs = cds.get_array(xkey)[xidx];
                xs.splice(xs.length - 1, 1);
            }
            if (ykey) {
                const yidx = cds.data[ykey].length - 1;
                const ys = cds.get_array(ykey)[yidx];
                ys.splice(ys.length - 1, 1);
            }
            this._emit_cds_changes(cds);
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame)
                return;
            for (const renderer of this.model.renderers) {
                if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                }
                else if (ev.key == "Escape") {
                    if (this._drawing) {
                        this._remove();
                        this._drawing = false;
                    }
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        _pan_start(ev) {
            if (!this.model.drag)
                return;
            this._select_event(ev, "append", this.model.renderers);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (this._basepoint == null || !this.model.drag)
                return;
            const [bx, by] = this._basepoint;
            // Process polygon/line dragging
            for (const renderer of this.model.renderers) {
                const basepoint = this._map_drag(bx, by, renderer);
                const point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null || basepoint == null)
                    continue;
                const cds = renderer.data_source;
                // Type once dataspecs are typed
                const glyph = renderer.glyph;
                const [xkey, ykey] = [glyph.xs.field, glyph.ys.field];
                if (!xkey && !ykey)
                    continue;
                const [x, y] = point;
                const [px, py] = basepoint;
                const [dx, dy] = [x - px, y - py];
                for (const index of cds.selected.indices) {
                    let length, xs, ys;
                    if (xkey)
                        xs = cds.data[xkey][index];
                    if (ykey) {
                        ys = cds.data[ykey][index];
                        length = ys.length;
                    }
                    else {
                        length = xs.length;
                    }
                    for (let i = 0; i < length; i++) {
                        if (xs)
                            xs[i] += dx;
                        if (ys)
                            ys[i] += dy;
                    }
                }
                cds.change.emit();
            }
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan_end(ev) {
            if (!this.model.drag)
                return;
            this._pan(ev);
            for (const renderer of this.model.renderers)
                this._emit_cds_changes(renderer.data_source);
            this._basepoint = null;
        }
        activate() {
            if (this.model.vertex_renderer == null || !this.model.active)
                return;
            this._show_vertices();
            if (!this._initialized) {
                for (const renderer of this.model.renderers) {
                    const cds = renderer.data_source;
                    cds.connect(cds.properties.data.change, () => this._show_vertices());
                }
            }
            this._initialized = true;
        }
        deactivate() {
            if (this._drawing) {
                this._remove();
                this._drawing = false;
            }
            if (this.model.vertex_renderer != null)
                this._hide_vertices();
        }
    }
    exports.PolyDrawToolView = PolyDrawToolView;
    PolyDrawToolView.__name__ = "PolyDrawToolView";
    class PolyDrawTool extends poly_tool_1.PolyTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Polygon Draw Tool";
            this.tool_icon = icons_css_1.tool_icon_poly_draw;
            this.event_type = ["pan", "tap", "move"];
            this.default_order = 3;
        }
    }
    exports.PolyDrawTool = PolyDrawTool;
    _a = PolyDrawTool;
    PolyDrawTool.__name__ = "PolyDrawTool";
    (() => {
        _a.prototype.default_view = PolyDrawToolView;
        _a.define(({ Boolean, Int, Array, Ref }) => ({
            drag: [Boolean, true],
            num_objects: [Int, 0],
            renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
        }));
    })();
},
/* models/tools/edit/poly_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const types_1 = require(8) /* ../../../core/util/types */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    const edit_tool_1 = require(480) /* ./edit_tool */;
    class PolyToolView extends edit_tool_1.EditToolView {
        _set_vertices(xs, ys) {
            const { vertex_renderer } = this.model;
            (0, assert_1.assert)(vertex_renderer != null);
            const point_glyph = vertex_renderer.glyph;
            const point_cds = vertex_renderer.data_source;
            const [pxkey, pykey] = [point_glyph.x.field, point_glyph.y.field];
            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);
        }
        _hide_vertices() {
            this._set_vertices([], []);
        }
        _snap_to_vertex(ev, x, y) {
            if (this.model.vertex_renderer != null) {
                // If an existing vertex is hit snap to it
                const vertex_selected = this._select_event(ev, "replace", [this.model.vertex_renderer]);
                const point_ds = this.model.vertex_renderer.data_source;
                // Type once dataspecs are typed
                const point_glyph = this.model.vertex_renderer.glyph;
                const [pxkey, pykey] = [point_glyph.x.field, point_glyph.y.field];
                if (vertex_selected.length != 0) {
                    const 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];
        }
    }
    exports.PolyToolView = PolyToolView;
    PolyToolView.__name__ = "PolyToolView";
    class PolyTool extends edit_tool_1.EditTool {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.PolyTool = PolyTool;
    _a = PolyTool;
    PolyTool.__name__ = "PolyTool";
    (() => {
        _a.define(({ AnyRef, Nullable }) => ({
            vertex_renderer: [Nullable(AnyRef()), null],
        }));
    })();
},
/* models/tools/edit/poly_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const types_1 = require(8) /* ../../../core/util/types */;
    const glyph_renderer_1 = require(201) /* ../../renderers/glyph_renderer */;
    const poly_tool_1 = require(487) /* ./poly_tool */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class PolyEditToolView extends poly_tool_1.PolyToolView {
        constructor() {
            super(...arguments);
            this._drawing = false;
            this._cur_index = null;
        }
        _doubletap(ev) {
            if (this.model.vertex_renderer == null || !this.model.active)
                return;
            const point = this._map_drag(ev.sx, ev.sy, this.model.vertex_renderer);
            if (point == null)
                return;
            const [x, y] = point;
            // Perform hit testing
            const vertex_selected = this._select_event(ev, "replace", [this.model.vertex_renderer]);
            const point_cds = this.model.vertex_renderer.data_source;
            // Type once dataspecs are typed
            const point_glyph = this.model.vertex_renderer.glyph;
            const [pxkey, pykey] = [point_glyph.x.field, point_glyph.y.field];
            if (vertex_selected.length != 0 && this._selected_renderer != null) {
                // Insert a new point after the selected vertex and enter draw mode
                const 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);
            }
        }
        _show_vertices(ev) {
            if (!this.model.active)
                return;
            if (this.model.renderers.length == 0)
                return;
            const vsync_renderer = this.model.renderers[0];
            const vsync_updater = () => this._update_vertices(vsync_renderer);
            const vsync_ds = vsync_renderer.data_source;
            const renderers = this._select_event(ev, "replace", this.model.renderers);
            if (renderers.length == 0) {
                this._set_vertices([], []);
                this._selected_renderer = null;
                this._drawing = false;
                this._cur_index = null;
                vsync_ds.disconnect(vsync_ds.properties.data.change, vsync_updater);
                return;
            }
            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]);
        }
        _update_vertices(renderer) {
            const glyph = renderer.glyph;
            const cds = renderer.data_source;
            const index = this._cur_index;
            const [xkey, ykey] = [glyph.xs.field, glyph.ys.field];
            if (this._drawing)
                return;
            if ((index == null) && (xkey || ykey))
                return;
            let xs;
            let 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);
        }
        _move(ev) {
            if (this._drawing && this._selected_renderer != null) {
                const renderer = this.model.vertex_renderer;
                if (renderer == null)
                    return;
                const cds = renderer.data_source;
                const glyph = renderer.glyph;
                const point = this._map_drag(ev.sx, ev.sy, renderer);
                if (point == null)
                    return;
                let [x, y] = point;
                const indices = cds.selected.indices;
                [x, y] = this._snap_to_vertex(ev, x, y);
                cds.selected.indices = indices;
                const [xkey, ykey] = [glyph.x.field, glyph.y.field];
                const 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();
            }
        }
        _tap(ev) {
            const renderer = this.model.vertex_renderer;
            if (renderer == null)
                return;
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            else if (this._drawing && this._selected_renderer != null) {
                let [x, y] = point;
                const cds = renderer.data_source;
                // Type once dataspecs are typed
                const glyph = renderer.glyph;
                const [xkey, ykey] = [glyph.x.field, glyph.y.field];
                const indices = cds.selected.indices;
                [x, y] = this._snap_to_vertex(ev, x, y);
                const index = indices[0];
                cds.selected.indices = [index + 1];
                if (xkey) {
                    const xs = cds.get_array(xkey);
                    const nx = xs[index];
                    xs[index] = x;
                    xs.splice(index + 1, 0, nx);
                }
                if (ykey) {
                    const ys = cds.get_array(ykey);
                    const 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;
            }
            const mode = this._select_mode(ev);
            this._select_event(ev, mode, [renderer]);
            this._select_event(ev, mode, this.model.renderers);
        }
        _remove_vertex() {
            if (!this._drawing || this._selected_renderer == null)
                return;
            const renderer = this.model.vertex_renderer;
            if (renderer == null)
                return;
            const cds = renderer.data_source;
            // Type once dataspecs are typed
            const glyph = renderer.glyph;
            const index = cds.selected.indices[0];
            const [xkey, ykey] = [glyph.x.field, glyph.y.field];
            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);
        }
        _pan_start(ev) {
            if (this.model.vertex_renderer == null)
                return;
            this._select_event(ev, "append", [this.model.vertex_renderer]);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (this._basepoint == null)
                return;
            if (this.model.vertex_renderer == null)
                return;
            this._drag_points(ev, [this.model.vertex_renderer]);
            if (this._selected_renderer != null)
                this._selected_renderer.data_source.change.emit();
        }
        _pan_end(ev) {
            if (this._basepoint == null)
                return;
            if (this.model.vertex_renderer == 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 != null) {
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            this._basepoint = null;
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame)
                return;
            let renderers;
            if (this._selected_renderer != null) {
                const { vertex_renderer } = this.model;
                renderers = vertex_renderer != null ? [vertex_renderer] : [];
            }
            else {
                renderers = this.model.renderers;
            }
            for (const renderer of renderers) {
                if (ev.key == "Backspace") {
                    this._delete_selected(renderer);
                    if (this._selected_renderer != null) {
                        this._emit_cds_changes(this._selected_renderer.data_source);
                    }
                }
                else if (ev.key == "Escape") {
                    if (this._drawing) {
                        this._remove_vertex();
                        this._drawing = false;
                    }
                    else if (this._selected_renderer != null) {
                        this._hide_vertices();
                    }
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        deactivate() {
            if (this._selected_renderer == null) {
                return;
            }
            else if (this._drawing) {
                this._remove_vertex();
                this._drawing = false;
            }
            this._hide_vertices();
        }
    }
    exports.PolyEditToolView = PolyEditToolView;
    PolyEditToolView.__name__ = "PolyEditToolView";
    class PolyEditTool extends poly_tool_1.PolyTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Poly Edit Tool";
            this.tool_icon = icons_css_1.tool_icon_poly_edit;
            this.event_type = ["tap", "pan", "move"];
            this.default_order = 4;
        }
    }
    exports.PolyEditTool = PolyEditTool;
    _a = PolyEditTool;
    PolyEditTool.__name__ = "PolyEditTool";
    (() => {
        _a.prototype.default_view = PolyEditToolView;
        _a.define(({ Array, Ref }) => ({
            renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
        }));
    })();
},
/* models/tools/gestures/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var box_select_tool_1 = require(490) /* ./box_select_tool */;
    __esExport("BoxSelectTool", box_select_tool_1.BoxSelectTool);
    var box_zoom_tool_1 = require(493) /* ./box_zoom_tool */;
    __esExport("BoxZoomTool", box_zoom_tool_1.BoxZoomTool);
    var gesture_tool_1 = require(280) /* ./gesture_tool */;
    __esExport("GestureTool", gesture_tool_1.GestureTool);
    var lasso_select_tool_1 = require(494) /* ./lasso_select_tool */;
    __esExport("LassoSelectTool", lasso_select_tool_1.LassoSelectTool);
    var pan_tool_1 = require(496) /* ./pan_tool */;
    __esExport("PanTool", pan_tool_1.PanTool);
    var poly_select_tool_1 = require(495) /* ./poly_select_tool */;
    __esExport("PolySelectTool", poly_select_tool_1.PolySelectTool);
    var range_tool_1 = require(497) /* ./range_tool */;
    __esExport("RangeTool", range_tool_1.RangeTool);
    var select_tool_1 = require(492) /* ./select_tool */;
    __esExport("SelectTool", select_tool_1.SelectTool);
    var tap_tool_1 = require(498) /* ./tap_tool */;
    __esExport("TapTool", tap_tool_1.TapTool);
    var wheel_pan_tool_1 = require(499) /* ./wheel_pan_tool */;
    __esExport("WheelPanTool", wheel_pan_tool_1.WheelPanTool);
    var wheel_zoom_tool_1 = require(500) /* ./wheel_zoom_tool */;
    __esExport("WheelZoomTool", wheel_zoom_tool_1.WheelZoomTool);
},
/* models/tools/gestures/box_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const region_select_tool_1 = require(491) /* ./region_select_tool */;
    const box_annotation_1 = require(237) /* ../../annotations/box_annotation */;
    const node_1 = require(241) /* ../../coordinates/node */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons = tslib_1.__importStar(require(278) /* ../../../styles/icons.css */);
    class BoxSelectToolView extends region_select_tool_1.RegionSelectToolView {
        connect_signals() {
            super.connect_signals();
            const { pan } = this.model.overlay;
            this.connect(pan, ([phase, ev]) => {
                if ((phase == "pan" && this._is_continuous(ev)) || phase == "pan:end") {
                    const { left, top, right, bottom } = this.model.overlay;
                    if (!(left instanceof node_1.Node) && !(top instanceof node_1.Node) && !(right instanceof node_1.Node) && !(bottom instanceof node_1.Node)) {
                        const screen = this._compute_lrtb({ left, right, top, bottom });
                        this._do_select([screen.left, screen.right], [screen.top, screen.bottom], false, this._select_mode(ev));
                    }
                }
            });
            const { active } = this.model.properties;
            this.on_change(active, () => {
                if (!this.model.active && !this.model.persistent)
                    this._clear_overlay();
            });
        }
        _compute_limits(curpoint) {
            const frame = this.plot_view.frame;
            const dims = this.model.dimensions;
            let base_point = this._base_point;
            if (this.model.origin == "center") {
                const [cx, cy] = base_point;
                const [dx, dy] = curpoint;
                base_point = [cx - (dx - cx), cy - (dy - cy)];
            }
            return this.model._get_dim_limits(base_point, curpoint, frame, dims);
        }
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const { overlay } = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                left: mapper(overlay.left_units, x_scale, x_view, x_screen),
                right: mapper(overlay.right_units, x_scale, x_view, x_screen),
                top: mapper(overlay.top_units, y_scale, y_view, y_screen),
                bottom: mapper(overlay.bottom_units, y_scale, y_view, y_screen),
            };
        }
        _compute_lrtb({ left, right, top, bottom }) {
            const lrtb = this._mappers();
            return {
                left: lrtb.left.compute(left),
                right: lrtb.right.compute(right),
                top: lrtb.top.compute(top),
                bottom: lrtb.bottom.compute(bottom),
            };
        }
        _invert_lrtb({ left, right, top, bottom }) {
            const lrtb = this._mappers();
            return {
                left: lrtb.left.invert(left),
                right: lrtb.right.invert(right),
                top: lrtb.top.invert(top),
                bottom: lrtb.bottom.invert(bottom),
            };
        }
        _pan_start(ev) {
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy))
                return;
            this._clear_other_overlays();
            this._base_point = [sx, sy];
        }
        _pan(ev) {
            if (this._base_point == null)
                return;
            const { sx, sy } = ev;
            const [sxlim, sylim] = this._compute_limits([sx, sy]);
            const [[left, right], [top, bottom]] = [sxlim, sylim];
            this.model.overlay.update(this._invert_lrtb({ left, right, top, bottom }));
            if (this._is_continuous(ev.modifiers)) {
                this._do_select(sxlim, sylim, false, this._select_mode(ev.modifiers));
            }
        }
        _pan_end(ev) {
            if (this._base_point == null)
                return;
            const { sx, sy } = ev;
            const [sxlim, sylim] = this._compute_limits([sx, sy]);
            this._do_select(sxlim, sylim, true, this._select_mode(ev.modifiers));
            if (!this.model.persistent) {
                this._clear_overlay();
            }
            this._base_point = null;
            this.plot_view.state.push("box_select", { selection: this.plot_view.get_selection() });
        }
        get _is_selecting() {
            return this._base_point != null;
        }
        _stop() {
            this._clear_overlay();
            this._base_point = null;
        }
        _keyup(ev) {
            if (!this.model.active)
                return;
            if (ev.key == "Escape") {
                if (this._is_selecting) {
                    this._stop();
                    return;
                }
                if (this.model.overlay.visible) {
                    this._clear_overlay();
                    return;
                }
            }
            super._keyup(ev);
        }
        _clear_selection() {
            if (this.model.overlay.visible)
                this._clear_overlay();
            else
                super._clear_selection();
        }
        _do_select([sx0, sx1], [sy0, sy1], final, mode = "replace") {
            const { greedy } = this.model;
            const geometry = { type: "rect", sx0, sx1, sy0, sy1, greedy };
            this._select(geometry, final, mode);
        }
    }
    exports.BoxSelectToolView = BoxSelectToolView;
    BoxSelectToolView.__name__ = "BoxSelectToolView";
    const DEFAULT_BOX_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            syncable: false,
            level: "overlay",
            visible: false,
            editable: true,
            left: NaN,
            right: NaN,
            top: NaN,
            bottom: NaN,
            top_units: "data",
            left_units: "data",
            bottom_units: "data",
            right_units: "data",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    class BoxSelectTool extends region_select_tool_1.RegionSelectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Box Select";
            this.event_type = "pan";
            this.default_order = 30;
        }
        initialize() {
            super.initialize();
            const [resizable, movable] = (() => {
                switch (this.dimensions) {
                    case "width": return ["x", "x"];
                    case "height": return ["y", "y"];
                    case "both": return ["all", "both"];
                }
            })();
            const symmetric = this.origin == "center";
            this.overlay.setv({ resizable, movable, symmetric });
        }
        get computed_icon() {
            const icon = super.computed_icon;
            if (icon != null)
                return icon;
            else {
                switch (this.dimensions) {
                    case "both": return `.${icons.tool_icon_box_select}`;
                    case "width": return `.${icons.tool_icon_x_box_select}`;
                    case "height": return `.${icons.tool_icon_y_box_select}`;
                }
            }
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.BoxSelectTool = BoxSelectTool;
    _a = BoxSelectTool;
    BoxSelectTool.__name__ = "BoxSelectTool";
    (() => {
        _a.prototype.default_view = BoxSelectToolView;
        _a.define(({ Ref }) => ({
            dimensions: [enums_1.Dimensions, "both"],
            overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_BOX_OVERLAY],
            origin: [enums_1.BoxOrigin, "corner"],
        }));
        _a.register_alias("box_select", () => new _a());
        _a.register_alias("xbox_select", () => new _a({ dimensions: "width" }));
        _a.register_alias("ybox_select", () => new _a({ dimensions: "height" }));
    })();
},
/* models/tools/gestures/region_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const select_tool_1 = require(492) /* ./select_tool */;
    class RegionSelectToolView extends select_tool_1.SelectToolView {
        get overlays() {
            return [...super.overlays, this.model.overlay];
        }
        _is_continuous(modifiers) {
            return this.model.continuous != modifiers.alt;
        }
        _select(geometry, final, mode) {
            const renderers_by_source = this._computed_renderers_by_data_source();
            for (const [, renderers] of renderers_by_source) {
                const sm = renderers[0].get_selection_manager();
                const r_views = [];
                for (const r of renderers) {
                    const r_view = this.plot_view.renderer_view(r);
                    if (r_view != null) {
                        r_views.push(r_view);
                    }
                }
                sm.select(r_views, geometry, final, mode);
            }
            this._emit_selection_event(geometry, final);
        }
        _clear_overlay() {
            super._clear_overlay();
            this.model.overlay.clear();
        }
    }
    exports.RegionSelectToolView = RegionSelectToolView;
    RegionSelectToolView.__name__ = "RegionSelectToolView";
    class RegionSelectTool extends select_tool_1.SelectTool {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.RegionSelectTool = RegionSelectTool;
    _a = RegionSelectTool;
    RegionSelectTool.__name__ = "RegionSelectTool";
    (() => {
        _a.define(({ Boolean }) => ({
            continuous: [Boolean, false],
            persistent: [Boolean, false],
            greedy: [Boolean, false],
        }));
    })();
},
/* models/tools/gestures/select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const gesture_tool_1 = require(280) /* ./gesture_tool */;
    const glyph_renderer_1 = require(201) /* ../../renderers/glyph_renderer */;
    const graph_renderer_1 = require(422) /* ../../renderers/graph_renderer */;
    const data_renderer_1 = require(202) /* ../../renderers/data_renderer */;
    const util_1 = require(97) /* ../../util */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const bokeh_events_1 = require(52) /* ../../../core/bokeh_events */;
    const signaling_1 = require(15) /* ../../../core/signaling */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    class SelectToolView extends gesture_tool_1.GestureToolView {
        connect_signals() {
            super.connect_signals();
            this.model.clear.connect(() => this._clear_selection());
        }
        get computed_renderers() {
            const { renderers } = this.model;
            const all_renderers = this.plot_view.model.data_renderers;
            return (0, util_1.compute_renderers)(renderers, all_renderers);
        }
        _computed_renderers_by_data_source() {
            var _b;
            const renderers_by_source = new Map();
            for (const r of this.computed_renderers) {
                let source;
                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;
                const renderers = (_b = renderers_by_source.get(source)) !== null && _b !== void 0 ? _b : [];
                renderers_by_source.set(source, [...renderers, r]);
            }
            return renderers_by_source;
        }
        _clear_overlay() { }
        _clear_other_overlays() {
            for (const view of this.plot_view.tool_views.values()) {
                if (view instanceof SelectToolView && view != this) {
                    view._clear_overlay();
                }
            }
        }
        _clear_selection() {
            this._clear();
        }
        _select_mode(modifiers) {
            const { shift, ctrl } = modifiers;
            if (!shift && !ctrl)
                return this.model.mode;
            else if (shift && !ctrl)
                return "append";
            else if (!shift && ctrl)
                return "intersect";
            else if (shift && ctrl)
                return "subtract";
            else
                (0, assert_1.unreachable)();
        }
        _keyup(ev) {
            if (!this.model.active)
                return;
            if (ev.key == "Escape") {
                this._clear();
            }
        }
        _clear() {
            for (const renderer of this.computed_renderers) {
                renderer.get_selection_manager().clear();
            }
            const renderer_views = this.computed_renderers.map((r) => this.plot_view.renderer_view(r));
            this.plot_view.request_paint(renderer_views);
        }
        _emit_selection_event(geometry, final = true) {
            const { x_scale, y_scale } = this.plot_view.frame;
            const geometry_data = (() => {
                switch (geometry.type) {
                    case "point": {
                        const { sx, sy } = geometry;
                        const x = x_scale.invert(sx);
                        const y = y_scale.invert(sy);
                        return Object.assign(Object.assign({}, geometry), { x, y });
                    }
                    case "span": {
                        const { sx, sy } = geometry;
                        const x = x_scale.invert(sx);
                        const y = y_scale.invert(sy);
                        return Object.assign(Object.assign({}, geometry), { x, y });
                    }
                    case "rect": {
                        const { sx0, sx1, sy0, sy1 } = geometry;
                        const [x0, x1] = x_scale.r_invert(sx0, sx1);
                        const [y0, y1] = y_scale.r_invert(sy0, sy1);
                        return Object.assign(Object.assign({}, geometry), { x0, y0, x1, y1 });
                    }
                    case "poly": {
                        const { sx, sy } = geometry;
                        const x = x_scale.v_invert(sx);
                        const y = y_scale.v_invert(sy);
                        return Object.assign(Object.assign({}, geometry), { x, y });
                    }
                }
            })();
            this.plot_view.model.trigger_event(new bokeh_events_1.SelectionGeometry(geometry_data, final));
        }
    }
    exports.SelectToolView = SelectToolView;
    SelectToolView.__name__ = "SelectToolView";
    class SelectTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.clear = new signaling_1.Signal0(this, "clear");
        }
        get menu() {
            return [
                {
                    icon: "bk-tool-icon-replace-mode",
                    tooltip: "Replace the current selection",
                    active: () => this.mode == "replace",
                    handler: () => {
                        this.mode = "replace";
                        this.active = true;
                    },
                }, {
                    icon: "bk-tool-icon-append-mode",
                    tooltip: "Append to the current selection (Shift)",
                    active: () => this.mode == "append",
                    handler: () => {
                        this.mode = "append";
                        this.active = true;
                    },
                }, {
                    icon: "bk-tool-icon-intersect-mode",
                    tooltip: "Intersect with the current selection (Ctrl)",
                    active: () => this.mode == "intersect",
                    handler: () => {
                        this.mode = "intersect";
                        this.active = true;
                    },
                }, {
                    icon: "bk-tool-icon-subtract-mode",
                    tooltip: "Subtract from the current selection (Shift+Ctrl)",
                    active: () => this.mode == "subtract",
                    handler: () => {
                        this.mode = "subtract";
                        this.active = true;
                    },
                },
                null,
                {
                    icon: "bk-tool-icon-clear-selection",
                    tooltip: "Clear the current selection and/or selection overlay (Esc)",
                    handler: () => {
                        this.clear.emit();
                    },
                },
            ];
        }
    }
    exports.SelectTool = SelectTool;
    _a = SelectTool;
    SelectTool.__name__ = "SelectTool";
    (() => {
        _a.define(({ Array, Ref, Or, Auto }) => ({
            renderers: [Or(Array(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
            mode: [enums_1.SelectionMode, "replace"],
        }));
    })();
},
/* models/tools/gestures/box_zoom_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const gesture_tool_1 = require(280) /* ./gesture_tool */;
    const box_annotation_1 = require(237) /* ../../annotations/box_annotation */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons = tslib_1.__importStar(require(278) /* ../../../styles/icons.css */);
    class BoxZoomToolView extends gesture_tool_1.GestureToolView {
        constructor() {
            super(...arguments);
            this._base_point = null;
        }
        get overlays() {
            return [...super.overlays, this.model.overlay];
        }
        _match_aspect([bx, by], [cx, cy], frame) {
            // aspect ratio of plot frame
            const a = frame.bbox.aspect;
            const hend = frame.bbox.h_range.end;
            const hstart = frame.bbox.h_range.start;
            const vend = frame.bbox.v_range.end;
            const vstart = frame.bbox.v_range.start;
            // current aspect of cursor-defined box
            let vw = Math.abs(bx - cx);
            let vh = Math.abs(by - cy);
            const va = vh == 0 ? 0 : vw / vh;
            const [xmod] = va >= a ? [1, va / a] : [a / va, 1];
            // 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
            // bx is left
            let left;
            let right;
            if (bx <= cx) {
                left = bx;
                right = bx + vw * xmod;
                if (right > hend)
                    right = hend;
                // bx is right
            }
            else {
                right = bx;
                left = bx - vw * xmod;
                if (left < hstart)
                    left = hstart;
            }
            vw = Math.abs(right - left);
            // by is bottom
            let top;
            let bottom;
            if (by <= cy) {
                bottom = by;
                top = by + vw / a;
                if (top > vend)
                    top = vend;
                // by is top
            }
            else {
                top = by;
                bottom = by - vw / a;
                if (bottom < vstart)
                    bottom = vstart;
            }
            vh = Math.abs(top - bottom);
            // bx is left
            if (bx <= cx)
                right = bx + a * vh;
            // bx is right
            else
                left = bx - a * vh;
            return [[left, right], [bottom, top]];
        }
        _compute_limits(base_point, curr_point) {
            const { frame } = this.plot_view;
            if (this.model.origin == "center") {
                const [cx, cy] = base_point;
                const [dx, dy] = curr_point;
                base_point = [cx - (dx - cx), cy - (dy - cy)];
            }
            const dims = (() => {
                const { dimensions } = this.model;
                if (dimensions == "auto") {
                    const [bx, by] = base_point;
                    const [cx, cy] = curr_point;
                    const dx = Math.abs(bx - cx);
                    const dy = Math.abs(by - cy);
                    const tol = 5;
                    if (dx < tol && dy > tol)
                        return "height";
                    else if (dx > tol && dy < tol)
                        return "width";
                    else
                        return "both";
                }
                else
                    return dimensions;
            })();
            if (this.model.match_aspect && dims == "both")
                return this._match_aspect(base_point, curr_point, frame);
            else
                return this.model._get_dim_limits(base_point, curr_point, frame, dims);
        }
        _pan_start(ev) {
            const { sx, sy } = ev;
            if (this.plot_view.frame.bbox.contains(sx, sy))
                this._base_point = [sx, sy];
        }
        _pan(ev) {
            if (this._base_point == null)
                return;
            const [[left, right], [top, bottom]] = this._compute_limits(this._base_point, [ev.sx, ev.sy]);
            this.model.overlay.update({ left, right, top, bottom });
        }
        _pan_end(ev) {
            if (this._base_point == null)
                return;
            const [sx, sy] = this._compute_limits(this._base_point, [ev.sx, ev.sy]);
            this._update(sx, sy);
            this._stop();
        }
        _stop() {
            this.model.overlay.clear();
            this._base_point = null;
        }
        _keydown(ev) {
            if (ev.key == "Escape") {
                this._stop();
            }
        }
        _doubletap(_ev) {
            var _b;
            const { state } = this.plot_view;
            if (((_b = state.peek()) === null || _b === void 0 ? void 0 : _b.type) == "box_zoom")
                state.undo();
        }
        _update([sx0, sx1], [sy0, sy1]) {
            // 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;
            const { x_scales, y_scales } = this.plot_view.frame;
            const xrs = new Map();
            for (const [, scale] of x_scales) {
                const [start, end] = scale.r_invert(sx0, sx1);
                xrs.set(scale.source_range, { start, end });
            }
            const yrs = new Map();
            for (const [, scale] of y_scales) {
                const [start, end] = scale.r_invert(sy0, sy1);
                yrs.set(scale.source_range, { start, end });
            }
            const zoom_info = { xrs, yrs };
            this.plot_view.state.push("box_zoom", { range: zoom_info });
            this.plot_view.update_range(zoom_info);
            this.plot_view.trigger_ranges_update_event();
        }
    }
    exports.BoxZoomToolView = BoxZoomToolView;
    BoxZoomToolView.__name__ = "BoxZoomToolView";
    const DEFAULT_BOX_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            syncable: false,
            level: "overlay",
            visible: false,
            editable: false,
            left: NaN,
            right: NaN,
            top: NaN,
            bottom: NaN,
            top_units: "canvas",
            left_units: "canvas",
            bottom_units: "canvas",
            right_units: "canvas",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    class BoxZoomTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Box Zoom";
            this.event_type = ["pan", "doubletap"];
            this.default_order = 20;
        }
        get event_role() {
            return "pan";
        }
        get computed_icon() {
            const icon = super.computed_icon;
            if (icon != null)
                return icon;
            else {
                switch (this.dimensions) {
                    case "both": return `.${icons.tool_icon_box_zoom}`;
                    case "width": return `.${icons.tool_icon_x_box_zoom}`;
                    case "height": return `.${icons.tool_icon_y_box_zoom}`;
                    case "auto": return `.${icons.tool_icon_auto_box_zoom}`;
                }
            }
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
        get menu() {
            return [
                {
                    icon: icons.tool_icon_box_zoom,
                    tooltip: "Box zoom in both dimensions",
                    active: () => this.dimensions == "both",
                    handler: () => {
                        this.dimensions = "both";
                        this.active = true;
                    },
                }, {
                    icon: icons.tool_icon_x_box_zoom,
                    tooltip: "Box zoom in x-dimension",
                    active: () => this.dimensions == "width",
                    handler: () => {
                        this.dimensions = "width";
                        this.active = true;
                    },
                }, {
                    icon: icons.tool_icon_y_box_zoom,
                    tooltip: "Box zoom in y-dimension",
                    active: () => this.dimensions == "height",
                    handler: () => {
                        this.dimensions = "height";
                        this.active = true;
                    },
                }, {
                    icon: icons.tool_icon_auto_box_zoom,
                    tooltip: "Automatic mode (box zoom in x, y or both dimensions, depending on the mouse gesture)",
                    active: () => this.dimensions == "auto",
                    handler: () => {
                        this.dimensions = "auto";
                        this.active = true;
                    },
                },
            ];
        }
    }
    exports.BoxZoomTool = BoxZoomTool;
    _a = BoxZoomTool;
    BoxZoomTool.__name__ = "BoxZoomTool";
    (() => {
        _a.prototype.default_view = BoxZoomToolView;
        _a.define(({ Boolean, Ref, Or, Auto }) => ({
            dimensions: [Or(enums_1.Dimensions, Auto), "both"],
            overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_BOX_OVERLAY],
            match_aspect: [Boolean, false],
            origin: [enums_1.BoxOrigin, "corner"],
        }));
        _a.register_alias("box_zoom", () => new _a({ dimensions: "both" }));
        _a.register_alias("xbox_zoom", () => new _a({ dimensions: "width" }));
        _a.register_alias("ybox_zoom", () => new _a({ dimensions: "height" }));
        _a.register_alias("auto_box_zoom", () => new _a({ dimensions: "auto" }));
    })();
},
/* models/tools/gestures/lasso_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const region_select_tool_1 = require(491) /* ./region_select_tool */;
    const poly_annotation_1 = require(259) /* ../../annotations/poly_annotation */;
    const poly_select_tool_1 = require(495) /* ./poly_select_tool */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class LassoSelectToolView extends region_select_tool_1.RegionSelectToolView {
        constructor() {
            super(...arguments);
            this._is_selecting = false;
        }
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const { overlay } = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                x: mapper(overlay.xs_units, x_scale, x_view, x_screen),
                y: mapper(overlay.ys_units, y_scale, y_view, y_screen),
            };
        }
        _v_compute(xs, ys) {
            const { x, y } = this._mappers();
            return [x.v_compute(xs), y.v_compute(ys)];
        }
        _v_invert(sxs, sys) {
            const { x, y } = this._mappers();
            return [x.v_invert(sxs), y.v_invert(sys)];
        }
        connect_signals() {
            super.connect_signals();
            const { pan } = this.model.overlay;
            this.connect(pan, ([phase, ev]) => {
                if ((phase == "pan" && this._is_continuous(ev)) || phase == "pan:end") {
                    const { xs, ys } = this.model.overlay;
                    const [sxs, sys] = this._v_compute(xs, ys);
                    this._do_select(sxs, sys, false, this._select_mode(ev));
                }
            });
            const { active } = this.model.properties;
            this.on_change(active, () => {
                if (!this.model.active && !this.model.persistent)
                    this._clear_overlay();
            });
        }
        _pan_start(ev) {
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy))
                return;
            this._clear_other_overlays();
            this._is_selecting = true;
            const [xs, ys] = this._v_invert([sx], [sy]);
            this.model.overlay.update({ xs, ys });
        }
        _pan(ev) {
            (0, assert_1.assert)(this._is_selecting);
            const [sxs, sys] = (() => {
                const { xs, ys } = this.model.overlay;
                const [sxs, sys] = this._v_compute(xs, ys);
                return [[...sxs], [...sys]];
            })();
            const [sx, sy] = this.plot_view.frame.bbox.clip(ev.sx, ev.sy);
            sxs.push(sx);
            sys.push(sy);
            const [xs, ys] = this._v_invert(sxs, sys);
            this.model.overlay.update({ xs, ys });
            if (this._is_continuous(ev.modifiers)) {
                this._do_select(sxs, sys, false, this._select_mode(ev.modifiers));
            }
        }
        _pan_end(ev) {
            (0, assert_1.assert)(this._is_selecting);
            this._is_selecting = false;
            const { xs, ys } = this.model.overlay;
            const [sxs, sys] = this._v_compute(xs, ys);
            this._do_select(sxs, sys, true, this._select_mode(ev.modifiers));
            this.plot_view.state.push("lasso_select", { selection: this.plot_view.get_selection() });
            if (!this.model.persistent) {
                this._clear_overlay();
            }
        }
        _keyup(ev) {
            if (!this.model.active)
                return;
            if (ev.key == "Escape") {
                if (this.model.overlay.visible) {
                    this._clear_overlay();
                    return;
                }
            }
            super._keyup(ev);
        }
        _clear_selection() {
            if (this.model.overlay.visible)
                this._clear_overlay();
            else
                super._clear_selection();
        }
        _do_select(sx, sy, final, mode) {
            const { greedy } = this.model;
            const geometry = { type: "poly", sx, sy, greedy };
            this._select(geometry, final, mode);
        }
    }
    exports.LassoSelectToolView = LassoSelectToolView;
    LassoSelectToolView.__name__ = "LassoSelectToolView";
    class LassoSelectTool extends region_select_tool_1.RegionSelectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Lasso Select";
            this.tool_icon = icons_css_1.tool_icon_lasso_select;
            this.event_type = "pan";
            this.default_order = 12;
        }
    }
    exports.LassoSelectTool = LassoSelectTool;
    _a = LassoSelectTool;
    LassoSelectTool.__name__ = "LassoSelectTool";
    (() => {
        _a.prototype.default_view = LassoSelectToolView;
        _a.define(({ Ref }) => ({
            overlay: [Ref(poly_annotation_1.PolyAnnotation), poly_select_tool_1.DEFAULT_POLY_OVERLAY],
        }));
        _a.override({
            continuous: true,
        });
        _a.register_alias("lasso_select", () => new _a());
    })();
},
/* models/tools/gestures/poly_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const region_select_tool_1 = require(491) /* ./region_select_tool */;
    const poly_annotation_1 = require(259) /* ../../annotations/poly_annotation */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class PolySelectToolView extends region_select_tool_1.RegionSelectToolView {
        constructor() {
            super(...arguments);
            this._is_selecting = false;
        }
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const { overlay } = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                x: mapper(overlay.xs_units, x_scale, x_view, x_screen),
                y: mapper(overlay.ys_units, y_scale, y_view, y_screen),
            };
        }
        _v_compute(xs, ys) {
            const { x, y } = this._mappers();
            return [x.v_compute(xs), y.v_compute(ys)];
        }
        _v_invert(sxs, sys) {
            const { x, y } = this._mappers();
            return [x.v_invert(sxs), y.v_invert(sys)];
        }
        connect_signals() {
            super.connect_signals();
            const { pan } = this.model.overlay;
            this.connect(pan, ([phase, ev]) => {
                if ((phase == "pan" && this._is_continuous(ev)) || (phase == "pan:end" && !this._is_selecting)) {
                    const { xs, ys } = this.model.overlay;
                    const [sxs, sys] = this._v_compute(xs, ys);
                    this._do_select(sxs, sys, false, this._select_mode(ev));
                }
            });
            const { active } = this.model.properties;
            this.on_change(active, () => {
                if (!this.model.active && !this.model.persistent)
                    this._clear_overlay();
            });
        }
        _tap(ev) {
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy))
                return;
            this._clear_other_overlays();
            const [sxs, sys] = (() => {
                if (this._is_selecting) {
                    const { xs, ys } = this.model.overlay;
                    const [sxs, sys] = this._v_compute(xs, ys);
                    return [[...sxs], [...sys]];
                }
                else {
                    this._is_selecting = true;
                    return [[], []];
                }
            })();
            sxs.push(sx);
            sys.push(sy);
            const [xs, ys] = this._v_invert(sxs, sys);
            this.model.overlay.update({ xs, ys });
            if (this._is_continuous(ev.modifiers)) {
                this._do_select(sxs, sys, true, this._select_mode(ev.modifiers));
            }
        }
        _finish_selection(ev) {
            this._is_selecting = false;
            const { xs, ys } = this.model.overlay;
            const [sxs, sys] = this._v_compute(xs, ys);
            this._do_select(sxs, sys, true, this._select_mode(ev));
            this.plot_view.state.push("poly_select", { selection: this.plot_view.get_selection() });
            if (!this.model.persistent)
                this._clear_overlay();
        }
        _doubletap(ev) {
            this._finish_selection(ev.modifiers);
        }
        _keyup(ev) {
            if (!this.model.active)
                return;
            if (ev.key == "Enter") {
                this._finish_selection(ev.modifiers);
                return;
            }
            if (ev.key == "Escape") {
                if (this.model.overlay.visible) {
                    this._clear_overlay();
                    return;
                }
            }
            super._keyup(ev);
        }
        _clear_selection() {
            if (this.model.overlay.visible)
                this._clear_overlay();
            else {
                this._is_selecting = false;
                super._clear_selection();
            }
        }
        _clear_overlay() {
            this._is_selecting = false;
            super._clear_overlay();
        }
        _do_select(sx, sy, final, mode) {
            const { greedy } = this.model;
            const geometry = { type: "poly", sx, sy, greedy };
            this._select(geometry, final, mode);
        }
    }
    exports.PolySelectToolView = PolySelectToolView;
    PolySelectToolView.__name__ = "PolySelectToolView";
    const DEFAULT_POLY_OVERLAY = () => {
        return new poly_annotation_1.PolyAnnotation({
            syncable: false,
            level: "overlay",
            visible: false,
            editable: true,
            xs_units: "data",
            ys_units: "data",
            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;
    class PolySelectTool extends region_select_tool_1.RegionSelectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Poly Select";
            this.tool_icon = icons_css_1.tool_icon_polygon_select;
            this.event_type = "tap";
            this.default_order = 11;
        }
    }
    exports.PolySelectTool = PolySelectTool;
    _a = PolySelectTool;
    PolySelectTool.__name__ = "PolySelectTool";
    (() => {
        _a.prototype.default_view = PolySelectToolView;
        _a.define(({ Ref }) => ({
            overlay: [Ref(poly_annotation_1.PolyAnnotation), exports.DEFAULT_POLY_OVERLAY],
        }));
        _a.register_alias("poly_select", () => new _a());
    })();
},
/* models/tools/gestures/pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const gesture_tool_1 = require(280) /* ./gesture_tool */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons = tslib_1.__importStar(require(278) /* ../../../styles/icons.css */);
    function update_ranges(scales, p0, p1) {
        const r = new Map();
        for (const [, scale] of scales) {
            const [start, end] = scale.r_invert(p0, p1);
            r.set(scale.source_range, { start, end });
        }
        return r;
    }
    exports.update_ranges = update_ranges;
    class PanToolView extends gesture_tool_1.GestureToolView {
        cursor(sx, sy) {
            const axis_view = this.plot_view.axis_views.find((view) => view.bbox.contains(sx, sy));
            if (axis_view != null) {
                switch (axis_view.dimension) {
                    case 0: return "ew-resize";
                    case 1: return "ns-resize";
                }
            }
            else if (this.plot_view.frame.bbox.contains(sx, sy)) {
                return "move";
            }
            else {
                return super.cursor(sx, sy);
            }
        }
        _pan_start(ev) {
            var _b;
            this.last_dx = 0;
            this.last_dy = 0;
            const { sx, sy } = ev;
            const bbox = this.plot_view.frame.bbox;
            if (!bbox.contains(sx, sy)) {
                const hr = bbox.h_range;
                const 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_view.model);
        }
        _pan(ev) {
            var _b;
            this._update(ev.dx, ev.dy);
            (_b = this.model.document) === null || _b === void 0 ? void 0 : _b.interactive_start(this.plot_view.model);
        }
        _pan_end(_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();
        }
        _update(dx, dy) {
            const frame = this.plot_view.frame;
            const new_dx = dx - this.last_dx;
            const new_dy = dy - this.last_dy;
            const hr = frame.bbox.h_range;
            const sx_low = hr.start - new_dx;
            const sx_high = hr.end - new_dx;
            const vr = frame.bbox.v_range;
            const sy_low = vr.start - new_dy;
            const sy_high = vr.end - new_dy;
            const dims = this.model.dimensions;
            let sx0;
            let sx1;
            let 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;
            }
            let sy0;
            let sy1;
            let 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;
            const { x_scales, y_scales } = frame;
            const xrs = update_ranges(x_scales, sx0, sx1);
            const yrs = update_ranges(y_scales, sy0, sy1);
            this.pan_info = { xrs, yrs, sdx, sdy };
            this.plot_view.update_range(this.pan_info, { panning: true });
        }
    }
    exports.PanToolView = PanToolView;
    PanToolView.__name__ = "PanToolView";
    class PanTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Pan";
            this.event_type = "pan";
            this.default_order = 10;
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
        get computed_icon() {
            const icon = super.computed_icon;
            if (icon != null)
                return icon;
            else {
                switch (this.dimensions) {
                    case "both": return `.${icons.tool_icon_pan}`;
                    case "width": return `.${icons.tool_icon_x_pan}`;
                    case "height": return `.${icons.tool_icon_y_pan}`;
                }
            }
        }
        get menu() {
            return [
                {
                    icon: icons.tool_icon_pan,
                    tooltip: "Pan in both dimensions",
                    active: () => this.dimensions == "both",
                    handler: () => {
                        this.dimensions = "both";
                        this.active = true;
                    },
                }, {
                    icon: icons.tool_icon_x_pan,
                    tooltip: "Pan in x-dimension",
                    active: () => this.dimensions == "width",
                    handler: () => {
                        this.dimensions = "width";
                        this.active = true;
                    },
                }, {
                    icon: icons.tool_icon_y_pan,
                    tooltip: "Pan in y-dimension",
                    active: () => this.dimensions == "height",
                    handler: () => {
                        this.dimensions = "height";
                        this.active = true;
                    },
                },
            ];
        }
    }
    exports.PanTool = PanTool;
    _a = PanTool;
    PanTool.__name__ = "PanTool";
    (() => {
        _a.prototype.default_view = PanToolView;
        _a.define(() => ({
            dimensions: [enums_1.Dimensions, "both"],
        }));
        _a.register_alias("pan", () => new _a({ dimensions: "both" }));
        _a.register_alias("xpan", () => new _a({ dimensions: "width" }));
        _a.register_alias("ypan", () => new _a({ dimensions: "height" }));
    })();
},
/* models/tools/gestures/range_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tool_1 = require(273) /* ../tool */;
    const on_off_button_1 = require(281) /* ../on_off_button */;
    const box_annotation_1 = require(237) /* ../../annotations/box_annotation */;
    const range_1 = require(87) /* ../../ranges/range */;
    const logging_1 = require(19) /* ../../../core/logging */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    const node_1 = require(241) /* ../../coordinates/node */;
    class RangeToolView extends tool_1.ToolView {
        get overlays() {
            return [...super.overlays, this.model.overlay];
        }
        initialize() {
            super.initialize();
            this.model.update_overlay_from_ranges();
        }
        connect_signals() {
            super.connect_signals();
            if (this.model.x_range != null) {
                this.connect(this.model.x_range.change, () => this.model.update_overlay_from_ranges());
            }
            if (this.model.y_range != null) {
                this.connect(this.model.y_range.change, () => this.model.update_overlay_from_ranges());
            }
            this.model.overlay.pan.connect(([state, _]) => {
                if (state == "pan") {
                    this.model.update_ranges_from_overlay();
                }
                else if (state == "pan:end") {
                    const ranges = [this.model.x_range, this.model.y_range].filter(types_1.non_null);
                    this.parent.trigger_ranges_update_event(ranges);
                }
            });
            const { active } = this.model.properties;
            this.on_change(active, () => {
                this.model.overlay.editable = this.model.active;
            });
        }
    }
    exports.RangeToolView = RangeToolView;
    RangeToolView.__name__ = "RangeToolView";
    const DEFAULT_RANGE_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            syncable: false,
            level: "overlay",
            visible: true,
            editable: true,
            propagate_hover: true,
            left: NaN,
            right: NaN,
            top: NaN,
            bottom: NaN,
            left_limit: node_1.Node.frame.left,
            right_limit: node_1.Node.frame.right,
            top_limit: node_1.Node.frame.top,
            bottom_limit: node_1.Node.frame.bottom,
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 0.5,
            line_dash: [2, 2],
        });
    };
    class RangeTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
            this._nodes = node_1.Node.frame.freeze();
            this.tool_name = "Range Tool";
            this.tool_icon = icons_css_1.tool_icon_range;
        }
        initialize() {
            super.initialize();
            this.overlay.editable = this.active;
            const has_x = this.x_range != null && this.x_interaction;
            const has_y = this.y_range != null && this.y_interaction;
            if (has_x && has_y) {
                this.overlay.movable = "both";
                this.overlay.resizable = "all";
            }
            else if (has_x) {
                this.overlay.movable = "x";
                this.overlay.resizable = "x";
            }
            else if (has_y) {
                this.overlay.movable = "y";
                this.overlay.resizable = "y";
            }
            else {
                this.overlay.movable = "none";
                this.overlay.resizable = "none";
            }
        }
        update_ranges_from_overlay() {
            const { left, right, top, bottom } = this.overlay;
            if (this.x_range != null && this.x_interaction) {
                this.x_range.setv({ start: left, end: right });
            }
            if (this.y_range != null && this.y_interaction) {
                this.y_range.setv({ start: bottom, end: top });
            }
        }
        update_overlay_from_ranges() {
            const { x_range, y_range } = this;
            const has_x = x_range != null;
            const has_y = y_range != null;
            this.overlay.update({
                left: has_x ? x_range.start : this._nodes.left,
                right: has_x ? x_range.end : this._nodes.right,
                top: has_y ? y_range.end : this._nodes.top,
                bottom: has_y ? y_range.start : this._nodes.bottom,
            });
            if (!has_x && !has_y) {
                logging_1.logger.warn("RangeTool not configured with any Ranges.");
                this.overlay.clear();
            }
        }
        tool_button() {
            return new on_off_button_1.OnOffButton({ tool: this });
        }
    }
    exports.RangeTool = RangeTool;
    _a = RangeTool;
    RangeTool.__name__ = "RangeTool";
    (() => {
        _a.prototype.default_view = RangeToolView;
        _a.define(({ Boolean, Ref, Nullable }) => ({
            x_range: [Nullable(Ref(range_1.Range)), null],
            y_range: [Nullable(Ref(range_1.Range)), null],
            x_interaction: [Boolean, true],
            y_interaction: [Boolean, true],
            overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_RANGE_OVERLAY],
        }));
        _a.override({
            active: true,
        });
    })();
},
/* models/tools/gestures/tap_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const select_tool_1 = require(492) /* ./select_tool */;
    const events = tslib_1.__importStar(require(52) /* ../../../core/bokeh_events */);
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class TapToolView extends select_tool_1.SelectToolView {
        _tap(ev) {
            if (this.model.gesture == "tap")
                this._handle_tap(ev);
        }
        _doubletap(ev) {
            if (this.model.gesture == "doubletap")
                this._handle_tap(ev);
        }
        _handle_tap(ev) {
            const { modifiers } = this.model;
            if (modifiers.shift != null && modifiers.shift != ev.modifiers.shift)
                return;
            if (modifiers.ctrl != null && modifiers.ctrl != ev.modifiers.ctrl)
                return;
            if (modifiers.alt != null && modifiers.alt != ev.modifiers.alt)
                return;
            const { sx, sy } = ev;
            const { frame } = this.plot_view;
            if (!frame.bbox.contains(sx, sy))
                return;
            this._clear_other_overlays();
            const geometry = { type: "point", sx, sy };
            if (this.model.behavior == "select") {
                this._select(geometry, true, this._select_mode(ev.modifiers));
            }
            else {
                this._inspect(geometry, ev.modifiers);
            }
        }
        _select(geometry, final, mode) {
            const renderers_by_source = this._computed_renderers_by_data_source();
            for (const [, renderers] of renderers_by_source) {
                const sm = renderers[0].get_selection_manager();
                const r_views = renderers
                    .map((r) => this.plot_view.renderer_view(r))
                    .filter((rv) => rv != null);
                const did_hit = sm.select(r_views, geometry, final, mode);
                if (did_hit) {
                    const [rv] = r_views;
                    this._emit_callback(rv, geometry, sm.source);
                }
            }
            this._emit_selection_event(geometry);
            this.plot_view.state.push("tap", { selection: this.plot_view.get_selection() });
        }
        _inspect(geometry, modifiers) {
            for (const r of this.computed_renderers) {
                const rv = this.plot_view.renderer_view(r);
                if (rv == null)
                    continue;
                const sm = r.get_selection_manager();
                const did_hit = sm.inspect(rv, geometry);
                if (did_hit) {
                    this._emit_callback(rv, geometry, sm.source, modifiers);
                }
            }
        }
        _emit_callback(rv, geometry, source, modifiers) {
            const { callback } = this.model;
            if (callback != null) {
                const x = rv.coordinates.x_scale.invert(geometry.sx);
                const y = rv.coordinates.y_scale.invert(geometry.sy);
                const data = {
                    geometries: Object.assign(Object.assign({}, geometry), { x, y }),
                    source,
                    event: { modifiers },
                };
                callback.execute(this.model, data);
            }
        }
    }
    exports.TapToolView = TapToolView;
    TapToolView.__name__ = "TapToolView";
    class TapTool extends select_tool_1.SelectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Tap";
            this.tool_icon = icons_css_1.tool_icon_tap_select;
            this.event_type = "tap";
            this.default_order = 10;
        }
    }
    exports.TapTool = TapTool;
    _a = TapTool;
    TapTool.__name__ = "TapTool";
    (() => {
        _a.prototype.default_view = TapToolView;
        _a.define(({ Any, Nullable }) => ({
            behavior: [enums_1.TapBehavior, "select"],
            gesture: [enums_1.TapGesture, "tap"],
            modifiers: [events.KeyModifiers, {}],
            callback: [Nullable(Any /*TODO*/), null],
        }));
        _a.register_alias("click", () => new _a({ behavior: "inspect" }));
        _a.register_alias("tap", () => new _a());
        _a.register_alias("doubletap", () => new _a({ gesture: "doubletap" }));
    })();
},
/* models/tools/gestures/wheel_pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const gesture_tool_1 = require(280) /* ./gesture_tool */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    const pan_tool_1 = require(496) /* ./pan_tool */;
    class WheelPanToolView extends gesture_tool_1.GestureToolView {
        _scroll(ev) {
            let 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);
        }
        _update_ranges(factor) {
            var _b;
            const { frame } = this.plot_view;
            const hr = frame.bbox.h_range;
            const vr = frame.bbox.v_range;
            const [sx_low, sx_high] = [hr.start, hr.end];
            const [sy_low, sy_high] = [vr.start, vr.end];
            let sx0;
            let sx1;
            let sy0;
            let sy1;
            switch (this.model.dimension) {
                case "height": {
                    const 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": {
                    const 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;
                }
            }
            const { x_scales, y_scales } = frame;
            const xrs = (0, pan_tool_1.update_ranges)(x_scales, sx0, sx1);
            const 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.
            const pan_info = { xrs, yrs, 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_view.model, () => this.plot_view.trigger_ranges_update_event());
        }
    }
    exports.WheelPanToolView = WheelPanToolView;
    WheelPanToolView.__name__ = "WheelPanToolView";
    class WheelPanTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Wheel Pan";
            this.tool_icon = icons_css_1.tool_icon_wheel_pan;
            this.event_type = "scroll";
            this.default_order = 12;
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimension);
        }
    }
    exports.WheelPanTool = WheelPanTool;
    _a = WheelPanTool;
    WheelPanTool.__name__ = "WheelPanTool";
    (() => {
        _a.prototype.default_view = WheelPanToolView;
        _a.define(() => ({
            dimension: [enums_1.Dimension, "width"],
        }));
        _a.internal(({ Number }) => ({
            speed: [Number, 1 / 1000],
        }));
        _a.register_alias("xwheel_pan", () => new _a({ dimension: "width" }));
        _a.register_alias("ywheel_pan", () => new _a({ dimension: "height" }));
    })();
},
/* models/tools/gestures/wheel_zoom_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const gesture_tool_1 = require(280) /* ./gesture_tool */;
    const data_renderer_1 = require(202) /* ../../renderers/data_renderer */;
    const composite_scale_1 = require(94) /* ../../scales/composite_scale */;
    const zoom_1 = require(477) /* ../../../core/util/zoom */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const logging_1 = require(19) /* ../../../core/logging */;
    const platform_1 = require(27) /* ../../../core/util/platform */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    const kinds_1 = require(21) /* ../../../core/kinds */;
    const ZoomTogether = (0, kinds_1.Enum)("none", "cross", "all");
    const Renderers = (0, kinds_1.Or)((0, kinds_1.Array)((0, kinds_1.Ref)(data_renderer_1.DataRenderer)), kinds_1.Auto);
    class WheelZoomToolView extends gesture_tool_1.GestureToolView {
        _pinch(ev) {
            // TODO (bev) this can probably be done much better
            const { sx, sy, scale, modifiers } = ev;
            let delta;
            if (scale >= 1)
                delta = (scale - 1) * 20.0;
            else
                delta = -20.0 / scale;
            this._scroll({ type: "wheel", sx, sy, delta, modifiers });
        }
        _scroll(ev) {
            var _b;
            const { sx, sy } = ev;
            const axis_view = this.plot_view.axis_views.find((view) => view.bbox.contains(sx, sy));
            if (axis_view != null && !this.model.zoom_on_axis) {
                return;
            }
            const { frame } = this.plot_view;
            if (axis_view == null && !frame.bbox.contains(sx, sy)) {
                return;
            }
            const [x_frame_scales_, y_frame_scales_] = (() => {
                const x_frame = [...frame.x_scales.values()];
                const y_frame = [...frame.y_scales.values()];
                if (axis_view == null) {
                    return [x_frame, y_frame];
                }
                else {
                    const { zoom_together } = this.model;
                    if (zoom_together == "all") {
                        if (axis_view.dimension == 0)
                            return [x_frame, []];
                        else
                            return [[], y_frame];
                    }
                    else {
                        const { x_scale, y_scale } = axis_view.coordinates;
                        switch (zoom_together) {
                            case "cross": {
                                return [[x_scale], [y_scale]];
                            }
                            case "none": {
                                if (axis_view.dimension == 0)
                                    return [[x_scale], []];
                                else
                                    return [[], [y_scale]];
                            }
                        }
                    }
                }
            })();
            const x_frame_scales = new Set(x_frame_scales_);
            const y_frame_scales = new Set(y_frame_scales_);
            const x_renderer_scales = new Set();
            const y_renderer_scales = new Set();
            const { renderers } = this.model;
            const data_renderers = renderers != "auto" ? renderers : this.plot_view.model.data_renderers;
            for (const renderer of data_renderers) {
                if (renderer.coordinates == null) {
                    continue;
                }
                const rv = this.plot_view.renderer_view(renderer);
                (0, assert_1.assert)(rv != null);
                const { x_scale, y_scale } = rv.coordinates;
                if (x_scale instanceof composite_scale_1.CompositeScale) {
                    if (x_frame_scales.has(x_scale.target_scale)) {
                        x_renderer_scales.add(x_scale);
                    }
                }
                if (y_scale instanceof composite_scale_1.CompositeScale) {
                    if (y_frame_scales.has(y_scale.target_scale)) {
                        y_renderer_scales.add(y_scale);
                    }
                }
            }
            const [x_all_scales, y_all_scales] = (() => {
                if (renderers == "auto") {
                    return [
                        new Set([...x_frame_scales, ...x_renderer_scales]),
                        new Set([...y_frame_scales, ...y_renderer_scales]),
                    ];
                }
                else {
                    return [
                        x_renderer_scales,
                        y_renderer_scales,
                    ];
                }
            })();
            const subcoord = { x: false, y: false };
            const traverse = (scale, dim) => {
                const { level } = this.model;
                for (let i = 0; i < level; i++) {
                    if (scale instanceof composite_scale_1.CompositeScale) {
                        subcoord[dim] = true;
                        scale = scale.source_scale;
                    }
                    else {
                        logging_1.logger.warn(`can't reach sub-coordinate level ${level} for ${scale} in ${dim} dimension; stopped at ${i}`);
                        break;
                    }
                }
                if (scale instanceof composite_scale_1.CompositeScale) {
                    return scale.target_scale;
                }
                else {
                    return scale;
                }
            };
            const x_scales = new Set();
            const y_scales = new Set();
            for (const x_scale of x_all_scales) {
                x_scales.add(traverse(x_scale, "x"));
            }
            for (const y_scale of y_all_scales) {
                y_scales.add(traverse(y_scale, "y"));
            }
            const center = (() => {
                const x = subcoord.x ? null : sx;
                const y = subcoord.y ? null : sy;
                if (axis_view != null) {
                    return axis_view.dimension == 0 ? { x, y: null } : { x: null, y };
                }
                else {
                    return { x, y };
                }
            })();
            // restrict to axis configured in tool's dimensions property and if
            // zoom origin is inside of frame range/domain
            const dims = this.model.dimensions;
            const x_axis = dims == "width" || dims == "both";
            const y_axis = dims == "height" || dims == "both";
            const { x_target, y_target } = frame;
            const factor = this.model.speed * ev.delta;
            const zoom_info = (0, zoom_1.scale_range)(x_scales, y_scales, x_target, y_target, factor, x_axis, y_axis, center);
            this.plot_view.state.push("wheel_zoom", { range: zoom_info });
            const { maintain_focus } = this.model;
            this.plot_view.update_range(zoom_info, { scrolling: true, maintain_focus });
            (_b = this.model.document) === null || _b === void 0 ? void 0 : _b.interactive_start(this.plot_view.model, () => this.plot_view.trigger_ranges_update_event());
        }
    }
    exports.WheelZoomToolView = WheelZoomToolView;
    WheelZoomToolView.__name__ = "WheelZoomToolView";
    class WheelZoomTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Wheel Zoom";
            this.tool_icon = icons_css_1.tool_icon_wheel_zoom;
            this.event_type = platform_1.is_mobile ? "pinch" : "scroll";
            this.default_order = 10;
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.WheelZoomTool = WheelZoomTool;
    _a = WheelZoomTool;
    WheelZoomTool.__name__ = "WheelZoomTool";
    (() => {
        _a.prototype.default_view = WheelZoomToolView;
        _a.define(({ Boolean, Number, NonNegative, Int }) => ({
            dimensions: [enums_1.Dimensions, "both"],
            renderers: [Renderers, "auto"],
            level: [NonNegative(Int), 0],
            maintain_focus: [Boolean, true],
            zoom_on_axis: [Boolean, true],
            zoom_together: [ZoomTogether, "all"],
            speed: [Number, 1 / 600],
        }));
        _a.register_alias("wheel_zoom", () => new _a({ dimensions: "both" }));
        _a.register_alias("xwheel_zoom", () => new _a({ dimensions: "width" }));
        _a.register_alias("ywheel_zoom", () => new _a({ dimensions: "height" }));
    })();
},
/* models/tools/inspectors/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var crosshair_tool_1 = require(502) /* ./crosshair_tool */;
    __esExport("CrosshairTool", crosshair_tool_1.CrosshairTool);
    var customjs_hover_1 = require(503) /* ./customjs_hover */;
    __esExport("CustomJSHover", customjs_hover_1.CustomJSHover);
    var hover_tool_1 = require(504) /* ./hover_tool */;
    __esExport("HoverTool", hover_tool_1.HoverTool);
    var inspect_tool_1 = require(282) /* ./inspect_tool */;
    __esExport("InspectTool", inspect_tool_1.InspectTool);
},
/* models/tools/inspectors/crosshair_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const inspect_tool_1 = require(282) /* ./inspect_tool */;
    const span_1 = require(263) /* ../../annotations/span */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    class CrosshairToolView extends inspect_tool_1.InspectToolView {
        get overlays() {
            return [...super.overlays, ...this._spans];
        }
        initialize() {
            super.initialize();
            this._update_overlays();
        }
        connect_signals() {
            super.connect_signals();
            const { overlay, dimensions, line_color, line_width, line_alpha } = this.model.properties;
            this.on_change([overlay, dimensions, line_color, line_width, line_alpha], () => {
                this._update_overlays();
                // TODO: notify change
            });
        }
        _update_overlays() {
            const { overlay } = this.model;
            if (overlay == "auto") {
                const { dimensions, line_color, line_alpha, line_width } = this.model;
                function span(dimension) {
                    return new span_1.Span({
                        dimension,
                        location_units: "canvas",
                        level: "overlay",
                        line_color,
                        line_width,
                        line_alpha,
                    });
                }
                switch (dimensions) {
                    case "width": {
                        this._spans = [span("width")];
                        break;
                    }
                    case "height": {
                        this._spans = [span("height")];
                        break;
                    }
                    case "both": {
                        this._spans = [span("width"), span("height")];
                        break;
                    }
                }
            }
            else if ((0, types_1.isArray)(overlay)) {
                this._spans = [...overlay];
            }
            else {
                this._spans = [overlay];
            }
        }
        _move(ev) {
            if (!this.model.active)
                return;
            const { sx, sy } = ev;
            if (!this.plot_view.frame.bbox.contains(sx, sy))
                this._update_spans(NaN, NaN);
            else
                this._update_spans(sx, sy);
        }
        _move_exit(_e) {
            this._update_spans(NaN, NaN);
        }
        _update_spans(sx, sy) {
            const { frame } = this.plot_view;
            function invert(span, sx, sy) {
                const { dimension } = span;
                switch (span.location_units) {
                    case "canvas": {
                        return dimension == "width" ? sy : sx;
                    }
                    case "screen": {
                        const { xview, yview } = frame.bbox;
                        return dimension == "width" ? yview.invert(sy) : xview.invert(sx);
                    }
                    case "data": {
                        const { x_scale, y_scale } = frame;
                        return dimension == "width" ? y_scale.invert(sy) : x_scale.invert(sx);
                    }
                }
            }
            for (const span of this._spans) {
                span.location = invert(span, sx, sy);
            }
        }
    }
    exports.CrosshairToolView = CrosshairToolView;
    CrosshairToolView.__name__ = "CrosshairToolView";
    class CrosshairTool extends inspect_tool_1.InspectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Crosshair";
            this.tool_icon = icons_css_1.tool_icon_crosshair;
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.CrosshairTool = CrosshairTool;
    _a = CrosshairTool;
    CrosshairTool.__name__ = "CrosshairTool";
    (() => {
        _a.prototype.default_view = CrosshairToolView;
        _a.define(({ Alpha, Number, Color, Auto, Tuple, Ref, Or }) => ({
            overlay: [Or(Auto, Ref(span_1.Span), Tuple(Ref(span_1.Span), Ref(span_1.Span))), "auto"],
            dimensions: [enums_1.Dimensions, "both"],
            line_color: [Color, "black"],
            line_width: [Number, 1],
            line_alpha: [Alpha, 1],
        }));
        _a.register_alias("crosshair", () => new _a());
    })();
},
/* models/tools/inspectors/customjs_hover.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(50) /* ../../../model */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const string_1 = require(40) /* ../../../core/util/string */;
    class CustomJSHover extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        /*protected*/ _make_code(valname, formatname, varsname, fn) {
            // this relies on keys(args) and values(args) returning keys and values
            // in the same order
            return new Function(...(0, object_1.keys)(this.args), valname, formatname, varsname, (0, string_1.use_strict)(fn));
        }
        format(value, format, special_vars) {
            const formatter = this._make_code("value", "format", "special_vars", this.code);
            return formatter(...this.values, value, format, special_vars);
        }
    }
    exports.CustomJSHover = CustomJSHover;
    _a = CustomJSHover;
    CustomJSHover.__name__ = "CustomJSHover";
    (() => {
        _a.define(({ Unknown, String, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [String, ""],
        }));
    })();
},
/* models/tools/inspectors/hover_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const build_views_1 = require(59) /* ../../../core/build_views */;
    const dom_1 = require(56) /* ../../../core/dom */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const hittest = tslib_1.__importStar(require(212) /* ../../../core/hittest */);
    const signaling_1 = require(15) /* ../../../core/signaling */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    const color_1 = require(22) /* ../../../core/util/color */;
    const iterator_1 = require(34) /* ../../../core/util/iterator */;
    const object_1 = require(9) /* ../../../core/util/object */;
    const templating_1 = require(172) /* ../../../core/util/templating */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = require(278) /* ../../../styles/icons.css */;
    const styles = tslib_1.__importStar(require(463) /* ../../../styles/tooltips.css */);
    const tooltip_1 = require(461) /* ../../ui/tooltip */;
    const template_1 = require(505) /* ../../dom/template */;
    const harea_1 = require(217) /* ../../glyphs/harea */;
    const harea_step_1 = require(214) /* ../../glyphs/harea_step */;
    const image_base_1 = require(340) /* ../../glyphs/image_base */;
    const line_1 = require(203) /* ../../glyphs/line */;
    const multi_line_1 = require(344) /* ../../glyphs/multi_line */;
    const patch_1 = require(213) /* ../../glyphs/patch */;
    const varea_1 = require(219) /* ../../glyphs/varea */;
    const varea_step_1 = require(218) /* ../../glyphs/varea_step */;
    const data_renderer_1 = require(202) /* ../../renderers/data_renderer */;
    const glyph_renderer_1 = require(201) /* ../../renderers/glyph_renderer */;
    const graph_renderer_1 = require(422) /* ../../renderers/graph_renderer */;
    const util_1 = require(97) /* ../../util */;
    const customjs_hover_1 = require(503) /* ./customjs_hover */;
    const inspect_tool_1 = require(282) /* ./inspect_tool */;
    function _nearest_line_hit(i, geometry, dx, dy) {
        const p1 = { x: dx[i], y: dy[i] };
        const p2 = { x: dx[i + 1], y: dy[i + 1] };
        const { sx, sy } = geometry;
        const [d1, d2] = (function () {
            if (geometry.type == "span") {
                if (geometry.direction == "h")
                    return [Math.abs(p1.x - sx), Math.abs(p2.x - sx)];
                else
                    return [Math.abs(p1.y - sy), Math.abs(p2.y - sy)];
            }
            // point geometry case
            const s = { x: sx, y: sy };
            const d1 = hittest.dist_2_pts(p1, s);
            const d2 = hittest.dist_2_pts(p2, s);
            return [d1, d2];
        })();
        return d1 < d2 ? [[p1.x, p1.y], i] : [[p2.x, p2.y], i + 1];
    }
    exports._nearest_line_hit = _nearest_line_hit;
    function _line_hit(xs, ys, i) {
        return [[xs[i], ys[i]], i];
    }
    exports._line_hit = _line_hit;
    class HoverToolView extends inspect_tool_1.InspectToolView {
        constructor() {
            super(...arguments);
            this._current_sxy = null;
            this.ttmodels = new Map();
            this._ttviews = new Map();
        }
        *children() {
            yield* super.children();
            yield* this._ttviews.values();
            if (this._template_view != null)
                yield this._template_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._update_ttmodels();
            const { tooltips } = this.model;
            if (tooltips instanceof template_1.Template) {
                this._template_view = await (0, build_views_1.build_view)(tooltips, { parent: this.plot_view.canvas });
                this._template_view.render();
            }
        }
        remove() {
            var _b;
            (_b = this._template_view) === null || _b === void 0 ? void 0 : _b.remove();
            (0, build_views_1.remove_views)(this._ttviews);
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            const plot_renderers = this.plot_view.model.properties.renderers;
            const { renderers, tooltips } = this.model.properties;
            this.on_change(tooltips, () => delete this._template_el);
            this.on_change([plot_renderers, renderers, tooltips], async () => await this._update_ttmodels());
            this.connect(this.plot_view.repainted, () => {
                if (this.model.active && this._current_sxy != null) {
                    const [sx, sy] = this._current_sxy;
                    this._inspect(sx, sy);
                }
            });
        }
        async _update_ttmodels() {
            const { ttmodels } = this;
            ttmodels.clear();
            const { tooltips } = this.model;
            if (tooltips == null)
                return;
            const { computed_renderers } = this;
            for (const r of computed_renderers) {
                const tooltip = new tooltip_1.Tooltip({
                    content: document.createElement("div"),
                    attachment: this.model.attachment,
                    show_arrow: this.model.show_arrow,
                    interactive: false,
                    visible: true,
                    position: null,
                    target: this.parent.canvas.overlays_el,
                });
                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);
                }
            }
            await (0, build_views_1.build_views)(this._ttviews, [...ttmodels.values()], { parent: this.plot_view });
            const glyph_renderers = [...(function* () {
                    for (const r of computed_renderers) {
                        if (r instanceof glyph_renderer_1.GlyphRenderer)
                            yield r;
                        else if (r instanceof graph_renderer_1.GraphRenderer) {
                            yield r.node_renderer;
                            yield r.edge_renderer;
                        }
                    }
                })()];
            const slot = this._slots.get(this.update);
            if (slot != null) {
                const except = new Set(glyph_renderers.map((r) => r.data_source));
                signaling_1.Signal.disconnect_receiver(this, slot, except);
            }
            for (const r of glyph_renderers) {
                this.connect(r.data_source.inspect, this.update);
            }
        }
        get computed_renderers() {
            const { renderers } = this.model;
            const all_renderers = this.plot_view.model.data_renderers;
            return (0, util_1.compute_renderers)(renderers, all_renderers);
        }
        _clear() {
            this._inspect(Infinity, Infinity);
            for (const [, tooltip] of this.ttmodels) {
                tooltip.clear();
            }
        }
        _move(ev) {
            if (!this.model.active)
                return;
            const { sx, sy } = ev;
            if (!this.plot_view.frame.bbox.contains(sx, sy))
                this._clear();
            else {
                this._current_sxy = [sx, sy];
                this._inspect(sx, sy);
            }
        }
        _move_exit() {
            this._current_sxy = null;
            this._clear();
        }
        _inspect(sx, sy) {
            const geometry = (() => {
                if (this.model.mode == "mouse")
                    return { type: "point", sx, sy };
                else {
                    const direction = this.model.mode == "vline" ? "h" : "v";
                    return { type: "span", direction, sx, sy };
                }
            })();
            for (const r of this.computed_renderers) {
                const sm = r.get_selection_manager();
                const rview = this.plot_view.renderer_view(r);
                if (rview != null)
                    sm.inspect(rview, geometry);
            }
            this._emit_callback(geometry);
        }
        _update(renderer, geometry, tooltip) {
            var _b, _c;
            const selection_manager = renderer.get_selection_manager();
            const fullset_indices = selection_manager.inspectors.get(renderer);
            const subset_indices = renderer.view.convert_selection_to_subset(fullset_indices);
            // XXX: https://github.com/bokeh/bokeh/pull/11992#pullrequestreview-897552484
            if (fullset_indices.is_empty() && fullset_indices.view == null) {
                tooltip.clear();
                return;
            }
            const ds = selection_manager.source;
            const renderer_view = this.plot_view.renderer_view(renderer);
            if (renderer_view == null)
                return;
            const { sx, sy } = geometry;
            const xscale = renderer_view.coordinates.x_scale;
            const yscale = renderer_view.coordinates.y_scale;
            const x = xscale.invert(sx);
            const y = yscale.invert(sy);
            const { glyph } = renderer_view;
            const tooltips = [];
            if (glyph instanceof patch_1.PatchView) {
                const [snap_sx, snap_sy] = [sx, sy];
                const [snap_x, snap_y] = [x, y];
                const vars = {
                    index: null,
                    glyph_view: glyph,
                    type: glyph.model.type,
                    x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                    name: renderer.name,
                };
                const rendered = this._render_tooltips(ds, vars);
                tooltips.push([snap_sx, snap_sy, rendered]);
            }
            else if (glyph instanceof harea_step_1.HAreaStepView ||
                glyph instanceof harea_1.HAreaView ||
                glyph instanceof varea_step_1.VAreaStepView ||
                glyph instanceof varea_1.VAreaView) {
                for (const i of subset_indices.line_indices) {
                    const [snap_x, snap_y] = [x, y];
                    const [snap_sx, snap_sy] = [sx, sy];
                    const vars = {
                        index: i,
                        glyph_view: glyph,
                        type: glyph.model.type,
                        x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                        name: renderer.name,
                        indices: subset_indices.line_indices,
                    };
                    const rendered = this._render_tooltips(ds, vars);
                    tooltips.push([snap_sx, snap_sy, rendered]);
                }
            }
            else if (glyph instanceof line_1.LineView) {
                const { line_policy } = this.model;
                for (const i of subset_indices.line_indices) {
                    const [[snap_x, snap_y], [snap_sx, snap_sy], ii] = (() => {
                        const [x, y] = [glyph._x, glyph._y];
                        switch (line_policy) {
                            case "interp": {
                                const [snap_x, snap_y] = glyph.get_interpolation_hit(i, geometry);
                                const snap_sxy = [xscale.compute(snap_x), yscale.compute(snap_y)];
                                return [[snap_x, snap_y], snap_sxy, i];
                            }
                            case "prev": {
                                const [snap_sxy, ii] = _line_hit(glyph.sx, glyph.sy, i);
                                return [[x[i + 1], y[i + 1]], snap_sxy, ii];
                            }
                            case "next": {
                                const [snap_sxy, ii] = _line_hit(glyph.sx, glyph.sy, i + 1);
                                return [[x[i + 1], y[i + 1]], snap_sxy, ii];
                            }
                            case "nearest": {
                                const [snap_sxy, ii] = _nearest_line_hit(i, geometry, glyph.sx, glyph.sy);
                                return [[x[ii], y[ii]], snap_sxy, ii];
                            }
                            case "none": {
                                const xscale = renderer_view.coordinates.x_scale;
                                const yscale = renderer_view.coordinates.y_scale;
                                const x = xscale.invert(sx);
                                const y = yscale.invert(sy);
                                return [[x, y], [sx, sy], i];
                            }
                        }
                    })();
                    const vars = {
                        index: ii,
                        glyph_view: glyph,
                        type: glyph.model.type,
                        x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                        name: renderer.name,
                        indices: subset_indices.line_indices,
                    };
                    const rendered = this._render_tooltips(ds, vars);
                    tooltips.push([snap_sx, snap_sy, rendered]);
                }
            }
            else if (glyph instanceof image_base_1.ImageBaseView) {
                for (const image_index of fullset_indices.image_indices) {
                    const [snap_sx, snap_sy] = [sx, sy];
                    const [snap_x, snap_y] = [x, y];
                    const vars = {
                        index: image_index.index,
                        glyph_view: glyph,
                        type: glyph.model.type,
                        x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                        name: renderer.name,
                        image_index,
                    };
                    const rendered = this._render_tooltips(ds, vars);
                    tooltips.push([snap_sx, snap_sy, rendered]);
                }
            }
            else {
                for (const i of subset_indices.indices) {
                    // multiglyphs set additional indices, e.g. multiline_indices for different tooltips
                    if (glyph instanceof multi_line_1.MultiLineView && !(0, object_1.is_empty)(subset_indices.multiline_indices)) {
                        const { line_policy } = this.model;
                        for (const j of subset_indices.multiline_indices[i.toString()]) { // TODO: subset_indices.multiline_indices.get(i)
                            const [[snap_x, snap_y], [snap_sx, snap_sy], jj] = (function () {
                                if (line_policy == "interp") {
                                    const [snap_x, snap_y] = glyph.get_interpolation_hit(i, j, geometry);
                                    const snap_sxy = [xscale.compute(snap_x), yscale.compute(snap_y)];
                                    return [[snap_x, snap_y], snap_sxy, j];
                                }
                                const [xs, ys] = [glyph._xs.get(i), glyph._ys.get(i)];
                                if (line_policy == "prev") {
                                    const [snap_sxy, jj] = _line_hit(glyph.sxs.get(i), glyph.sys.get(i), j);
                                    return [[xs[j], ys[j]], snap_sxy, jj];
                                }
                                if (line_policy == "next") {
                                    const [snap_sxy, jj] = _line_hit(glyph.sxs.get(i), glyph.sys.get(i), j + 1);
                                    return [[xs[j], ys[j]], snap_sxy, jj];
                                }
                                if (line_policy == "nearest") {
                                    const [snap_sxy, jj] = _nearest_line_hit(j, geometry, glyph.sxs.get(i), glyph.sys.get(i));
                                    return [[xs[jj], ys[jj]], snap_sxy, jj];
                                }
                                throw new Error("shouldn't have happened");
                            })();
                            const index = renderer.view.convert_indices_from_subset([i])[0];
                            const vars = {
                                index,
                                glyph_view: glyph,
                                type: glyph.model.type,
                                x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                                name: renderer.name,
                                indices: subset_indices.multiline_indices,
                                segment_index: jj,
                            };
                            const rendered = this._render_tooltips(ds, vars);
                            tooltips.push([snap_sx, snap_sy, rendered]);
                        }
                    }
                    else {
                        // handle non-multiglyphs
                        const snap_x = (_b = glyph._x) === null || _b === void 0 ? void 0 : _b[i];
                        const snap_y = (_c = glyph._y) === null || _c === void 0 ? void 0 : _c[i];
                        const { point_policy, anchor } = this.model;
                        const [snap_sx, snap_sy] = (function () {
                            if (point_policy == "snap_to_data") {
                                const pt = glyph.get_anchor_point(anchor, i, [sx, sy]);
                                if (pt != null)
                                    return [pt.x, pt.y];
                                const ptc = glyph.get_anchor_point("center", i, [sx, sy]);
                                if (ptc != null)
                                    return [ptc.x, ptc.y];
                                return [sx, sy];
                            }
                            return [sx, sy];
                        })();
                        const index = renderer.view.convert_indices_from_subset([i])[0];
                        const vars = {
                            index,
                            glyph_view: glyph,
                            type: glyph.model.type,
                            x, y, sx, sy, snap_x, snap_y, snap_sx, snap_sy,
                            name: renderer.name,
                            indices: subset_indices.indices,
                        };
                        const rendered = this._render_tooltips(ds, vars);
                        tooltips.push([snap_sx, snap_sy, rendered]);
                    }
                }
            }
            const { bbox } = this.plot_view.frame;
            const in_frame = tooltips.filter(([sx, sy]) => bbox.contains(sx, sy));
            if (in_frame.length == 0)
                tooltip.clear();
            else {
                const { content } = tooltip;
                (0, assert_1.assert)(content instanceof Element);
                (0, dom_1.empty)(content);
                for (const [, , node] of in_frame) {
                    if (node != null)
                        content.appendChild(node);
                }
                const [x, y] = in_frame[in_frame.length - 1];
                tooltip.setv({ position: [x, y] }, { check_eq: false }); // XXX: force update
            }
        }
        update([renderer, { geometry }]) {
            if (!this.model.active)
                return;
            if (!(geometry.type == "point" || geometry.type == "span"))
                return;
            if (this.model.muted_policy == "ignore" && renderer.muted)
                return;
            const tooltip = this.ttmodels.get(renderer);
            if ((0, types_1.is_undefined)(tooltip))
                return;
            this._update(renderer, geometry, tooltip);
        }
        _emit_callback(geometry) {
            const { callback } = this.model;
            if (callback == null)
                return;
            for (const renderer of this.computed_renderers) {
                if (!(renderer instanceof glyph_renderer_1.GlyphRenderer))
                    continue;
                const glyph_renderer_view = this.plot_view.renderer_view(renderer);
                if (glyph_renderer_view == null)
                    continue;
                const { x_scale, y_scale } = glyph_renderer_view.coordinates;
                const x = x_scale.invert(geometry.sx);
                const y = y_scale.invert(geometry.sy);
                const index = renderer.data_source.inspected;
                callback.execute(this.model, {
                    geometry: Object.assign({ x, y }, geometry),
                    renderer,
                    index,
                });
            }
        }
        _create_template(tooltips) {
            const rows = (0, dom_1.div)({ style: { display: "table", borderSpacing: "2px" } });
            for (const [label] of tooltips) {
                const row = (0, dom_1.div)({ style: { display: "table-row" } });
                rows.appendChild(row);
                const label_cell = (0, dom_1.div)({ style: { display: "table-cell" }, class: styles.tooltip_row_label }, label.length != 0 ? `${label}: ` : "");
                row.appendChild(label_cell);
                const value_el = (0, dom_1.span)();
                value_el.dataset.value = "";
                const swatch_el = (0, dom_1.span)({ class: styles.tooltip_color_block }, " ");
                swatch_el.dataset.swatch = "";
                (0, dom_1.undisplay)(swatch_el);
                const value_cell = (0, dom_1.div)({ style: { display: "table-cell" }, class: styles.tooltip_row_value }, value_el, swatch_el);
                row.appendChild(value_cell);
            }
            return rows;
        }
        _render_template(template, tooltips, ds, vars) {
            const el = template.cloneNode(true);
            // if we have an image_index, that is what replace_placeholders needs
            const i = (0, types_1.is_undefined)(vars.image_index) ? vars.index : vars.image_index;
            const value_els = el.querySelectorAll("[data-value]");
            const swatch_els = el.querySelectorAll("[data-swatch]");
            const color_re = /\$color(\[.*\])?:(\w*)/;
            const swatch_re = /\$swatch:(\w*)/;
            for (const [[, value], j] of (0, iterator_1.enumerate)(tooltips)) {
                const swatch_match = value.match(swatch_re);
                const color_match = value.match(color_re);
                if (swatch_match == null && color_match == null) {
                    const 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 {
                        for (const el of content) {
                            value_els[j].appendChild(el);
                        }
                    }
                    continue;
                }
                if (swatch_match != null) {
                    const [, colname] = swatch_match;
                    const column = ds.get_column(colname);
                    if (column == null) {
                        value_els[j].textContent = `${colname} unknown`;
                    }
                    else {
                        const 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) {
                    const [, opts = "", colname] = color_match;
                    const column = ds.get_column(colname); // XXX: change to columnar ds
                    if (column == null) {
                        value_els[j].textContent = `${colname} unknown`;
                        continue;
                    }
                    const hex = opts.indexOf("hex") >= 0;
                    const swatch = opts.indexOf("swatch") >= 0;
                    const 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]);
                    }
                }
            }
            return el;
        }
        _render_tooltips(ds, vars) {
            var _b;
            const { tooltips } = this.model;
            const i = vars.index;
            if ((0, types_1.isString)(tooltips)) {
                const content = (0, templating_1.replace_placeholders)({ html: tooltips }, ds, i, this.model.formatters, vars);
                return (0, dom_1.div)(content);
            }
            if ((0, types_1.isFunction)(tooltips))
                return tooltips(ds, vars);
            if (tooltips instanceof template_1.Template) {
                this._template_view.update(ds, i, vars);
                return this._template_view.el;
            }
            if (tooltips != null) {
                const template = (_b = this._template_el) !== null && _b !== void 0 ? _b : (this._template_el = this._create_template(tooltips));
                return this._render_template(template, tooltips, ds, vars);
            }
            return null;
        }
    }
    exports.HoverToolView = HoverToolView;
    HoverToolView.__name__ = "HoverToolView";
    class HoverTool extends inspect_tool_1.InspectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Hover";
            this.tool_icon = icons_css_1.tool_icon_hover;
        }
    }
    exports.HoverTool = HoverTool;
    _a = HoverTool;
    HoverTool.__name__ = "HoverTool";
    (() => {
        _a.prototype.default_view = HoverToolView;
        _a.define(({ Any, Boolean, String, Array, Tuple, Dict, Or, Ref, Function, Auto, Nullable }) => ({
            tooltips: [Nullable(Or(Ref(template_1.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"],
            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*/), null],
        }));
        _a.register_alias("hover", () => new _a());
    })();
},
/* models/dom/template.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const dom_element_1 = require(506) /* ./dom_element */;
    const action_1 = require(507) /* ./action */;
    const placeholder_1 = require(508) /* ./placeholder */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    class TemplateView extends dom_element_1.DOMElementView {
        constructor() {
            super(...arguments);
            this.action_views = new Map();
        }
        *children() {
            yield* super.children();
            yield* this.action_views.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await (0, build_views_1.build_views)(this.action_views, this.model.actions, { parent: this });
        }
        remove() {
            (0, build_views_1.remove_views)(this.action_views);
            super.remove();
        }
        update(source, i, vars = {} /*, formatters?: Formatters*/) {
            function descend(obj) {
                for (const child of obj.child_views.values()) {
                    if (child instanceof placeholder_1.PlaceholderView) {
                        child.update(source, i, vars);
                    }
                    else if (child instanceof dom_element_1.DOMElementView) {
                        descend(child);
                    }
                }
            }
            descend(this);
            for (const action of this.action_views.values()) {
                action.update(source, i, vars);
            }
        }
    }
    exports.TemplateView = TemplateView;
    TemplateView.__name__ = "TemplateView";
    TemplateView.tag_name = "div";
    class Template extends dom_element_1.DOMElement {
    }
    exports.Template = Template;
    _a = Template;
    Template.__name__ = "Template";
    (() => {
        _a.prototype.default_view = TemplateView;
        _a.define(({ Array, Ref }) => ({
            actions: [Array(Ref(action_1.Action)), []],
        }));
    })();
},
/* models/dom/dom_element.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const dom_node_1 = require(455) /* ./dom_node */;
    const styles_1 = require(267) /* ./styles */;
    const ui_element_1 = require(266) /* ../ui/ui_element */;
    const build_views_1 = require(59) /* ../../core/build_views */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    class DOMElementView extends dom_node_1.DOMNodeView {
        constructor() {
            super(...arguments);
            this.child_views = new Map();
        }
        *children() {
            yield* super.children();
            yield* this.child_views.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const children = this.model.children.filter((obj) => !(0, types_1.isString)(obj));
            await (0, build_views_1.build_views)(this.child_views, children, { parent: this });
        }
        remove() {
            (0, build_views_1.remove_views)(this.child_views);
            super.remove();
        }
        render() {
            const { style } = this.model;
            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) {
                    for (const prop of style) {
                        const value = prop.get_value();
                        if ((0, types_1.isString)(value)) {
                            const name = prop.attr.replace(/_/g, "-");
                            if (this.el.style.hasOwnProperty(name)) {
                                this.el.style.setProperty(name, value);
                            }
                        }
                    }
                }
                else {
                    for (const [key, value] of (0, object_1.entries)(style)) {
                        const name = key.replace(/_/g, "-");
                        if (this.el.style.hasOwnProperty(name)) {
                            this.el.style.setProperty(name, value);
                        }
                    }
                }
            }
            for (const child of this.model.children) {
                if ((0, types_1.isString)(child)) {
                    const node = document.createTextNode(child);
                    this.el.appendChild(node);
                }
                else {
                    const child_view = this.child_views.get(child);
                    child_view.render_to(this.el);
                }
            }
            this.finish();
        }
    }
    exports.DOMElementView = DOMElementView;
    DOMElementView.__name__ = "DOMElementView";
    class DOMElement extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DOMElement = DOMElement;
    _a = DOMElement;
    DOMElement.__name__ = "DOMElement";
    (() => {
        _a.define(({ String, Array, Dict, Or, Nullable, Ref }) => ({
            style: [Nullable(Or(Ref(styles_1.Styles), Dict(String))), null],
            children: [Array(Or(String, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))), []],
        }));
    })();
},
/* models/dom/action.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(50) /* ../../model */;
    const view_1 = require(54) /* ../../core/view */;
    class ActionView extends view_1.View {
    }
    exports.ActionView = ActionView;
    ActionView.__name__ = "ActionView";
    class Action extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Action = Action;
    Action.__name__ = "Action";
    Action.__module__ = "bokeh.models.dom";
},
/* models/dom/placeholder.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_node_1 = require(455) /* ./dom_node */;
    class PlaceholderView extends dom_node_1.DOMNodeView {
        render() {
            // XXX: no implementation?
        }
    }
    exports.PlaceholderView = PlaceholderView;
    PlaceholderView.__name__ = "PlaceholderView";
    PlaceholderView.tag_name = "span";
    class Placeholder extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Placeholder = Placeholder;
    Placeholder.__name__ = "Placeholder";
},
/* models/dom/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var action_1 = require(507) /* ./action */;
    __esExport("Action", action_1.Action);
    var color_ref_1 = require(510) /* ./color_ref */;
    __esExport("ColorRef", color_ref_1.ColorRef);
    var dom_element_1 = require(506) /* ./dom_element */;
    __esExport("DOMElement", dom_element_1.DOMElement);
    var dom_node_1 = require(455) /* ./dom_node */;
    __esExport("DOMNode", dom_node_1.DOMNode);
    var elements_1 = require(512) /* ./elements */;
    __esExport("Span", elements_1.Span);
    __esExport("Div", elements_1.Div);
    __esExport("Table", elements_1.Table);
    __esExport("TableRow", elements_1.TableRow);
    var html_1 = require(462) /* ./html */;
    __esExport("HTML", html_1.HTML);
    var index_1 = require(513) /* ./index_ */;
    __esExport("Index", index_1.Index);
    var placeholder_1 = require(508) /* ./placeholder */;
    __esExport("Placeholder", placeholder_1.Placeholder);
    var styles_1 = require(267) /* ./styles */;
    __esExport("Styles", styles_1.Styles);
    var stylesheets_1 = require(268) /* ./stylesheets */;
    __esExport("InlineStyleSheet", stylesheets_1.InlineStyleSheet);
    __esExport("GlobalInlineStyleSheet", stylesheets_1.GlobalInlineStyleSheet);
    __esExport("ImportedStyleSheet", stylesheets_1.ImportedStyleSheet);
    __esExport("GlobalImportedStyleSheet", stylesheets_1.GlobalImportedStyleSheet);
    var template_1 = require(505) /* ./template */;
    __esExport("Template", template_1.Template);
    var text_1 = require(456) /* ./text */;
    __esExport("Text", text_1.Text);
    var toggle_group_1 = require(514) /* ./toggle_group */;
    __esExport("ToggleGroup", toggle_group_1.ToggleGroup);
    var value_of_1 = require(515) /* ./value_of */;
    __esExport("ValueOf", value_of_1.ValueOf);
    var value_ref_1 = require(511) /* ./value_ref */;
    __esExport("ValueRef", value_ref_1.ValueRef);
},
/* models/dom/color_ref.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const value_ref_1 = require(511) /* ./value_ref */;
    const templating_1 = require(172) /* ../../core/util/templating */;
    const dom_1 = require(56) /* ../../core/dom */;
    const styles = tslib_1.__importStar(require(463) /* ../../styles/tooltips.css */);
    class ColorRefView extends value_ref_1.ValueRefView {
        render() {
            super.render();
            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);
        }
        update(source, i, _vars /*, formatters?: Formatters*/) {
            const value = (0, templating_1._get_column_value)(this.model.field, source, i);
            const text = value == null ? "???" : `${value}`; //.toString()
            this.el.textContent = text;
        }
    }
    exports.ColorRefView = ColorRefView;
    ColorRefView.__name__ = "ColorRefView";
    class ColorRef extends value_ref_1.ValueRef {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ColorRef = ColorRef;
    _a = ColorRef;
    ColorRef.__name__ = "ColorRef";
    (() => {
        _a.prototype.default_view = ColorRefView;
        _a.define(({ Boolean }) => ({
            hex: [Boolean, true],
            swatch: [Boolean, true],
        }));
    })();
},
/* models/dom/value_ref.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const placeholder_1 = require(508) /* ./placeholder */;
    const templating_1 = require(172) /* ../../core/util/templating */;
    class ValueRefView extends placeholder_1.PlaceholderView {
        update(source, i, _vars /*, formatters?: Formatters*/) {
            const value = (0, templating_1._get_column_value)(this.model.field, source, i);
            const text = value == null ? "???" : `${value}`; //.toString()
            this.el.textContent = text;
        }
    }
    exports.ValueRefView = ValueRefView;
    ValueRefView.__name__ = "ValueRefView";
    class ValueRef extends placeholder_1.Placeholder {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ValueRef = ValueRef;
    _a = ValueRef;
    ValueRef.__name__ = "ValueRef";
    (() => {
        _a.prototype.default_view = ValueRefView;
        _a.define(({ String }) => ({
            field: [String],
        }));
    })();
},
/* models/dom/elements.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c, _d;
    __esModule();
    const dom_element_1 = require(506) /* ./dom_element */;
    class SpanView extends dom_element_1.DOMElementView {
    }
    exports.SpanView = SpanView;
    SpanView.__name__ = "SpanView";
    SpanView.tag_name = "span";
    class Span extends dom_element_1.DOMElement {
    }
    exports.Span = Span;
    _a = Span;
    Span.__name__ = "Span";
    (() => {
        _a.prototype.default_view = SpanView;
    })();
    class DivView extends dom_element_1.DOMElementView {
    }
    exports.DivView = DivView;
    DivView.__name__ = "DivView";
    DivView.tag_name = "div";
    class Div extends dom_element_1.DOMElement {
    }
    exports.Div = Div;
    _b = Div;
    Div.__name__ = "Div";
    (() => {
        _b.prototype.default_view = DivView;
    })();
    class TableView extends dom_element_1.DOMElementView {
    }
    exports.TableView = TableView;
    TableView.__name__ = "TableView";
    TableView.tag_name = "table";
    class Table extends dom_element_1.DOMElement {
    }
    exports.Table = Table;
    _c = Table;
    Table.__name__ = "Table";
    (() => {
        _c.prototype.default_view = TableView;
    })();
    class TableRowView extends dom_element_1.DOMElementView {
    }
    exports.TableRowView = TableRowView;
    TableRowView.__name__ = "TableRowView";
    TableRowView.tag_name = "tr";
    class TableRow extends dom_element_1.DOMElement {
    }
    exports.TableRow = TableRow;
    _d = TableRow;
    TableRow.__name__ = "TableRow";
    (() => {
        _d.prototype.default_view = TableRowView;
    })();
},
/* models/dom/index_.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const placeholder_1 = require(508) /* ./placeholder */;
    class IndexView extends placeholder_1.PlaceholderView {
        update(_source, i, _vars /*, formatters?: Formatters*/) {
            this.el.textContent = i == null ? "(null)" : i.toString();
        }
    }
    exports.IndexView = IndexView;
    IndexView.__name__ = "IndexView";
    class Index extends placeholder_1.Placeholder {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Index = Index;
    _a = Index;
    Index.__name__ = "Index";
    (() => {
        _a.prototype.default_view = IndexView;
    })();
},
/* models/dom/toggle_group.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const action_1 = require(507) /* ./action */;
    const renderer_1 = require(74) /* ../renderers/renderer */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    class ToggleGroupView extends action_1.ActionView {
        update(_source, i, _vars /*, formatters?: Formatters*/) {
            for (const [group, j] of (0, iterator_1.enumerate)(this.model.groups)) {
                group.visible = i == j;
            }
        }
    }
    exports.ToggleGroupView = ToggleGroupView;
    ToggleGroupView.__name__ = "ToggleGroupView";
    class ToggleGroup extends action_1.Action {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ToggleGroup = ToggleGroup;
    _a = ToggleGroup;
    ToggleGroup.__name__ = "ToggleGroup";
    (() => {
        _a.prototype.default_view = ToggleGroupView;
        _a.define(({ Array, Ref }) => ({
            groups: [Array(Ref(renderer_1.RendererGroup)), []],
        }));
    })();
},
/* models/dom/value_of.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const dom_node_1 = require(455) /* ./dom_node */;
    const has_props_1 = require(14) /* ../../core/has_props */;
    const dom_1 = require(56) /* ../../core/dom */;
    const pretty_1 = require(42) /* ../../core/util/pretty */;
    class ValueOfView extends dom_node_1.DOMNodeView {
        connect_signals() {
            super.connect_signals();
            const { obj, attr } = this.model;
            if (attr in obj.properties) {
                this.on_change(obj.properties[attr], () => this.render());
            }
        }
        render() {
            (0, dom_1.empty)(this.el);
            this.el.style.display = "contents";
            const text = (() => {
                const { obj, attr } = this.model;
                if (attr in obj.properties) {
                    const value = obj.properties[attr].get_value();
                    return (0, pretty_1.to_string)(value);
                }
                else
                    return `<not found: ${obj.type}.${attr}>`;
            })();
            this.el.textContent = text;
        }
    }
    exports.ValueOfView = ValueOfView;
    ValueOfView.__name__ = "ValueOfView";
    class ValueOf extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ValueOf = ValueOf;
    _a = ValueOf;
    ValueOf.__name__ = "ValueOf";
    (() => {
        _a.prototype.default_view = ValueOfView;
        _a.define(({ String, Ref }) => ({
            obj: [Ref(has_props_1.HasProps)],
            attr: [String],
        }));
    })();
},
], 0, {"main":0,"tslib":1,"index":2,"version":3,"embed/index":4,"document/index":5,"document/document":6,"base":7,"core/util/types":8,"core/util/object":9,"core/util/array":10,"core/util/math":11,"core/util/assert":12,"core/util/arrayable":13,"core/has_props":14,"core/signaling":15,"core/util/defer":16,"core/util/refs":17,"core/properties":18,"core/logging":19,"core/enums":20,"core/kinds":21,"core/util/color":22,"core/util/svg_colors":23,"core/types":24,"core/util/bitset":25,"core/util/eq":26,"core/util/platform":27,"core/vectorization":28,"core/settings":29,"core/util/ndarray":30,"core/util/cloneable":31,"core/serialization/index":32,"core/serialization/serializer":33,"core/util/iterator":34,"core/serialization/buffer":35,"core/util/buffer":36,"core/serialization/reps":37,"core/diagnostics":38,"core/uniforms":39,"core/util/string":40,"document/events":41,"core/util/pretty":42,"core/patching":43,"core/util/set":44,"core/util/typed_array":45,"core/resolvers":46,"core/serialization/deserializer":47,"core/util/slice":48,"core/util/version":49,"model":50,"document/defs":51,"core/bokeh_events":52,"embed/standalone":53,"core/view":54,"core/dom_view":55,"core/dom":56,"core/util/bbox":57,"styles/base.css":58,"core/build_views":59,"embed/server":60,"client/connection":61,"protocol/message":62,"protocol/receiver":63,"client/session":64,"embed/dom":65,"embed/notebook":66,"protocol/index":67,"testing":68,"safely":69,"models/main":70,"models/index":71,"models/annotations/index":72,"models/annotations/annotation":73,"models/renderers/renderer":74,"core/visuals/index":75,"core/visuals/line":76,"core/visuals/visual":77,"core/property_mixins":78,"core/visuals/fill":79,"core/visuals/text":80,"core/visuals/hatch":81,"core/visuals/patterns":82,"core/visuals/image":83,"models/coordinates/coordinate_mapping":84,"models/scales/scale":85,"models/transforms/transform":86,"models/ranges/range":87,"models/ranges/range1d":88,"models/ranges/numerical_range":89,"models/scales/linear_scale":90,"models/scales/continuous_scale":91,"models/scales/log_scale":92,"models/scales/categorical_scale":93,"models/scales/composite_scale":94,"models/ranges/data_range1d":95,"models/ranges/data_range":96,"models/util":97,"models/ranges/factor_range":98,"models/annotations/arrow":99,"models/annotations/data_annotation":100,"models/sources/columnar_data_source":101,"core/selection_manager":102,"models/selections/selection":103,"models/selections/interaction_policy":104,"models/sources/data_source":105,"models/sources/column_data_source":106,"core/util/projections":107,"models/annotations/arrow_head":141,"models/graphics/marking":142,"models/annotations/base_color_bar":143,"models/annotations/title":144,"models/annotations/text_annotation":145,"core/layout/side_panel":146,"core/layout/types":147,"core/layout/layoutable":148,"models/text/base_text":149,"models/text/utils":150,"models/text/math_text":151,"core/util/image":152,"core/graphics":153,"core/util/text":154,"core/util/affine":155,"models/text/providers":156,"core/util/modules":157,"models/text/plain_text":158,"models/canvas/cartesian_frame":159,"models/axes/index":160,"models/axes/axis":161,"models/renderers/guide_renderer":162,"models/tickers/ticker":163,"models/formatters/tick_formatter":164,"models/policies/labeling":165,"models/axes/categorical_axis":166,"models/tickers/categorical_ticker":167,"models/formatters/categorical_tick_formatter":168,"models/axes/continuous_axis":169,"models/axes/datetime_axis":170,"models/formatters/datetime_tick_formatter":171,"core/util/templating":172,"models/tickers/util":176,"models/tickers/datetime_ticker":177,"models/tickers/adaptive_ticker":178,"models/tickers/continuous_ticker":179,"models/tickers/composite_ticker":180,"models/tickers/days_ticker":181,"models/tickers/single_interval_ticker":182,"models/tickers/months_ticker":183,"models/tickers/years_ticker":184,"models/tickers/basic_ticker":185,"models/axes/linear_axis":186,"models/formatters/basic_tick_formatter":187,"models/axes/log_axis":188,"models/formatters/log_tick_formatter":189,"models/tickers/log_ticker":190,"models/axes/mercator_axis":191,"models/formatters/mercator_tick_formatter":192,"models/tickers/mercator_ticker":193,"models/tickers/index":194,"models/tickers/fixed_ticker":195,"models/tickers/binned_ticker":196,"models/mappers/scanning_color_mapper":197,"models/mappers/continuous_color_mapper":198,"models/mappers/color_mapper":199,"models/mappers/mapper":200,"models/renderers/glyph_renderer":201,"models/renderers/data_renderer":202,"models/glyphs/line":203,"models/glyphs/xy_glyph":204,"models/glyphs/glyph":205,"core/util/ragged_array":206,"core/util/spatial":207,"models/graphics/decoration":210,"models/glyphs/utils":211,"core/hittest":212,"models/glyphs/patch":213,"models/glyphs/harea_step":214,"models/glyphs/area":215,"core/util/flip_step_mode":216,"models/glyphs/harea":217,"models/glyphs/varea_step":218,"models/glyphs/varea":219,"models/sources/cds_view":220,"models/filters/filter":221,"models/filters/all_indices":222,"models/filters/intersection_filter":223,"models/formatters/index":224,"models/formatters/customjs_tick_formatter":225,"models/formatters/numeral_tick_formatter":226,"models/formatters/printf_tick_formatter":227,"models/scales/index":228,"models/scales/linear_interpolation_scale":229,"models/ranges/index":230,"core/layout/index":231,"core/layout/alignments":232,"core/layout/grid":233,"core/layout/border":234,"models/annotations/band":235,"models/annotations/upper_lower":236,"models/annotations/box_annotation":237,"models/common/kinds":238,"models/common/painting":239,"models/common/resolve":240,"models/coordinates/node":241,"models/coordinates/coordinate":242,"models/annotations/color_bar":243,"models/mappers/index":244,"models/mappers/categorical_color_mapper":245,"models/mappers/categorical_mapper":246,"models/mappers/categorical_marker_mapper":247,"models/mappers/categorical_pattern_mapper":248,"models/mappers/linear_color_mapper":249,"models/mappers/log_color_mapper":250,"models/mappers/eqhist_color_mapper":251,"models/mappers/stack_color_mapper":252,"models/mappers/weighted_stack_color_mapper":253,"models/annotations/contour_color_bar":254,"models/annotations/label":255,"models/annotations/label_set":256,"models/annotations/legend":257,"models/annotations/legend_item":258,"models/annotations/poly_annotation":259,"models/annotations/scale_bar":260,"models/annotations/dimensional":261,"models/annotations/slope":262,"models/annotations/span":263,"models/annotations/toolbar_panel":264,"models/tools/toolbar":265,"models/ui/ui_element":266,"models/dom/styles":267,"models/dom/stylesheets":268,"core/util/canvas":269,"core/util/svg":270,"core/util/random":271,"styles/ui.css":272,"models/tools/tool":273,"models/tools/tool_proxy":274,"models/tools/tool_button":275,"core/util/menus":276,"styles/menus.css":277,"styles/icons.css":278,"styles/tool_button.css":279,"models/tools/gestures/gesture_tool":280,"models/tools/on_off_button":281,"models/tools/inspectors/inspect_tool":282,"models/tools/actions/action_tool":283,"models/tools/click_button":284,"models/tools/actions/help_tool":285,"styles/toolbar.css":286,"styles/logo.css":287,"models/annotations/whisker":288,"models/annotations/html/index":289,"models/annotations/html/label":290,"models/annotations/html/text_annotation":291,"models/annotations/html/label_set":292,"models/annotations/html/title":293,"models/callbacks/index":294,"models/callbacks/customjs":295,"models/callbacks/callback":296,"models/callbacks/open_url":297,"models/callbacks/set_value":298,"models/canvas/index":299,"models/canvas/canvas":300,"core/ui_events":301,"core/util/wheel":303,"styles/canvas.css":304,"models/coordinates/index":305,"models/expressions/index":306,"models/expressions/expression":307,"models/expressions/customjs_expr":308,"models/expressions/stack":309,"models/expressions/cumsum":310,"models/expressions/minimum":311,"models/expressions/maximum":312,"models/expressions/coordinate_transform":313,"models/expressions/polar":314,"models/filters/index":315,"models/filters/boolean_filter":316,"models/filters/customjs_filter":317,"models/filters/group_filter":318,"models/filters/index_filter":319,"models/filters/inversion_filter":320,"models/filters/union_filter":321,"models/filters/difference_filter":322,"models/filters/symmetric_difference_filter":323,"models/glyphs/index":324,"models/glyphs/annular_wedge":325,"models/glyphs/annulus":326,"models/glyphs/arc":327,"models/glyphs/bezier":328,"core/util/algorithms":329,"models/glyphs/block":330,"models/glyphs/lrtb":331,"models/glyphs/circle":332,"models/glyphs/ellipse":333,"models/glyphs/center_rotatable":334,"models/glyphs/hbar":335,"models/glyphs/hspan":336,"models/glyphs/hstrip":337,"models/glyphs/hex_tile":338,"models/glyphs/image":339,"models/glyphs/image_base":340,"models/glyphs/image_rgba":341,"models/glyphs/image_stack":342,"models/glyphs/image_url":343,"models/glyphs/multi_line":344,"models/glyphs/multi_polygons":345,"models/glyphs/patches":346,"models/glyphs/quad":347,"models/glyphs/quadratic":348,"models/glyphs/ray":349,"models/glyphs/rect":350,"models/glyphs/scatter":351,"models/glyphs/marker":352,"models/glyphs/defs":353,"models/glyphs/segment":354,"models/glyphs/spline":355,"core/util/interpolation":356,"models/glyphs/step":357,"models/glyphs/text":358,"models/glyphs/vbar":359,"models/glyphs/vspan":360,"models/glyphs/vstrip":361,"models/glyphs/wedge":362,"models/graphics/index":363,"models/graphs/index":364,"models/graphs/graph_hit_test_policy":365,"models/graphs/layout_provider":366,"models/graphs/static_layout_provider":367,"models/grids/index":368,"models/grids/grid":369,"models/layouts/index":370,"models/layouts/column":371,"models/layouts/flex_box":372,"models/layouts/layout_dom":373,"models/menus/menu":374,"models/menus/menu_item":375,"models/layouts/alignments":376,"models/layouts/grid_box":377,"models/layouts/css_grid_box":378,"models/layouts/group_box":379,"styles/group_box.css":380,"models/layouts/hbox":381,"models/layouts/row":382,"models/layouts/scroll_box":383,"models/layouts/spacer":384,"models/layouts/tab_panel":385,"models/layouts/tabs":386,"styles/tabs.css":387,"models/layouts/vbox":388,"models/menus/index":389,"models/menus/action":390,"models/ui/icons/icon":391,"models/menus/check_action":392,"models/menus/section":393,"models/menus/divider":394,"models/text/index":395,"models/transforms/index":396,"models/transforms/customjs_transform":397,"models/transforms/dodge":398,"models/transforms/range_transform":399,"models/transforms/interpolator":400,"models/transforms/jitter":401,"models/random/random_generator":402,"models/transforms/linear_interpolator":403,"models/transforms/step_interpolator":404,"models/plots/index":405,"models/plots/gmap_plot":406,"models/plots/plot":407,"models/plots/plot_canvas":408,"core/util/throttle":409,"models/plots/range_manager":410,"models/plots/state_manager":411,"styles/plots.css":412,"models/plots/gmap_plot_canvas":413,"models/plots/gmap":414,"models/plots/grid_plot":415,"models/plots/figure":416,"models/policies/index":417,"models/random/index":418,"models/random/park_miller_lcg":419,"models/renderers/index":420,"models/renderers/contour_renderer":421,"models/renderers/graph_renderer":422,"models/selections/index":423,"models/selectors/index":424,"models/selectors/by_id":425,"models/selectors/selector":426,"models/selectors/by_class":427,"models/selectors/by_css":428,"models/selectors/by_xpath":429,"models/sources/index":430,"models/sources/server_sent_data_source":431,"models/sources/web_data_source":432,"models/sources/ajax_data_source":433,"models/sources/geojson_data_source":434,"models/tiles/index":435,"models/tiles/bbox_tile_source":436,"models/tiles/mercator_tile_source":437,"models/tiles/tile_source":438,"models/tiles/tile_utils":439,"models/tiles/quadkey_tile_source":440,"models/tiles/tile_renderer":441,"models/tiles/wmts_tile_source":442,"styles/attribution.css":443,"models/tiles/tms_tile_source":444,"models/textures/index":445,"models/textures/canvas_texture":446,"models/textures/texture":447,"models/textures/image_url_texture":448,"models/ui/index":449,"models/ui/icons/index":450,"models/ui/icons/builtin_icon":451,"models/ui/icons/svg_icon":452,"models/ui/icons/tabler_icon":453,"models/ui/dialog":454,"models/dom/dom_node":455,"models/dom/text":456,"styles/dialogs.css":457,"models/ui/examiner":458,"styles/examiner.css":459,"models/ui/pane":460,"models/ui/tooltip":461,"models/dom/html":462,"styles/tooltips.css":463,"models/tools/index":464,"models/tools/actions/index":465,"models/tools/actions/copy_tool":466,"models/tools/actions/custom_action":467,"models/tools/actions/fullscreen_tool":468,"models/tools/actions/examine_tool":469,"models/tools/actions/redo_tool":470,"models/tools/actions/plot_action_tool":471,"models/tools/actions/reset_tool":472,"models/tools/actions/save_tool":473,"models/tools/actions/undo_tool":474,"models/tools/actions/zoom_in_tool":475,"models/tools/actions/zoom_base_tool":476,"core/util/zoom":477,"models/tools/actions/zoom_out_tool":478,"models/tools/edit/index":479,"models/tools/edit/edit_tool":480,"models/tools/edit/box_edit_tool":481,"models/tools/edit/freehand_draw_tool":482,"models/tools/edit/line_edit_tool":483,"models/tools/edit/line_tool":484,"models/tools/edit/point_draw_tool":485,"models/tools/edit/poly_draw_tool":486,"models/tools/edit/poly_tool":487,"models/tools/edit/poly_edit_tool":488,"models/tools/gestures/index":489,"models/tools/gestures/box_select_tool":490,"models/tools/gestures/region_select_tool":491,"models/tools/gestures/select_tool":492,"models/tools/gestures/box_zoom_tool":493,"models/tools/gestures/lasso_select_tool":494,"models/tools/gestures/poly_select_tool":495,"models/tools/gestures/pan_tool":496,"models/tools/gestures/range_tool":497,"models/tools/gestures/tap_tool":498,"models/tools/gestures/wheel_pan_tool":499,"models/tools/gestures/wheel_zoom_tool":500,"models/tools/inspectors/index":501,"models/tools/inspectors/crosshair_tool":502,"models/tools/inspectors/customjs_hover":503,"models/tools/inspectors/hover_tool":504,"models/dom/template":505,"models/dom/dom_element":506,"models/dom/action":507,"models/dom/placeholder":508,"models/dom/index":509,"models/dom/color_ref":510,"models/dom/value_ref":511,"models/dom/elements":512,"models/dom/index_":513,"models/dom/toggle_group":514,"models/dom/value_of":515}, {});});
//# sourceMappingURL=bokeh.js.map
