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

  var cache = {};

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

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

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

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

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

    return name;
  }

  var require = function(name) {
    var mod = cache[name];
    if (!mod) {
      var 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) {}
          }

          var 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 ""
  }

  var 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 (var name in plugin_modules) {
      modules[name] = plugin_modules[name];
    }

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

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

    var plugin = require(plugin_entry);

    for (var 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);
},
/* 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) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    exports.__extends = __extends;
    var __assign = function () {
        exports.__assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s)
                    if (Object.prototype.hasOwnProperty.call(s, p))
                        t[p] = s[p];
            }
            return t;
        };
        return exports.__assign.apply(this, arguments);
    };
    exports.__assign = __assign;
    function __rest(s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }
    exports.__rest = __rest;
    function __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }
    exports.__decorate = __decorate;
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    exports.__param = __param;
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    exports.__metadata = __metadata;
    function __awaiter(thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) {
                try {
                    step(generator.next(value));
                }
                catch (e) {
                    reject(e);
                }
            }
            function rejected(value) {
                try {
                    step(generator["throw"](value));
                }
                catch (e) {
                    reject(e);
                }
            }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    }
    exports.__awaiter = __awaiter;
    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function () {
                if (t[0] & 1)
                    throw t[1];
                return t[1];
            }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f)
                throw new TypeError("Generator is already executing.");
            while (_)
                try {
                    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
                        return t;
                    if (y = 0, t)
                        op = [op[0] & 2, t.value];
                    switch (op[0]) {
                        case 0:
                        case 1:
                            t = op;
                            break;
                        case 4:
                            _.label++;
                            return { value: op[1], done: false };
                        case 5:
                            _.label++;
                            y = op[1];
                            op = [0];
                            continue;
                        case 7:
                            op = _.ops.pop();
                            _.trys.pop();
                            continue;
                        default:
                            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                                _ = 0;
                                continue;
                            }
                            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                                _.label = op[1];
                                break;
                            }
                            if (op[0] === 6 && _.label < t[1]) {
                                _.label = t[1];
                                t = op;
                                break;
                            }
                            if (t && _.label < t[2]) {
                                _.label = t[2];
                                _.ops.push(op);
                                break;
                            }
                            if (t[2])
                                _.ops.pop();
                            _.trys.pop();
                            continue;
                    }
                    op = body.call(thisArg, _);
                }
                catch (e) {
                    op = [6, e];
                    y = 0;
                }
                finally {
                    f = t = 0;
                }
            if (op[0] & 5)
                throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
        }
    }
    exports.__generator = __generator;
    exports.__createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                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;
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    exports.__spread = __spread;
    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 __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    exports.__await = __await;
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) {
            if (g[n])
                i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); };
        }
        function resume(n, v) {
            try {
                step(g[n](v));
            }
            catch (e) {
                settle(q[0][3], e);
            }
        }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) {
            if (f(v), q.shift(), q.length)
                resume(q[0][0], q[0][1]);
        }
    }
    exports.__asyncGenerator = __asyncGenerator;
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
    }
    exports.__asyncDelegator = __asyncDelegator;
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    exports.__asyncValues = __asyncValues;
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    exports.__makeTemplateObject = __makeTemplateObject;
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    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, privateMap) {
        if (!privateMap.has(receiver)) {
            throw new TypeError("attempted to get private field on non-instance");
        }
        return privateMap.get(receiver);
    }
    exports.__classPrivateFieldGet = __classPrivateFieldGet;
    function __classPrivateFieldSet(receiver, privateMap, value) {
        if (!privateMap.has(receiver)) {
            throw new TypeError("attempted to set private field on non-instance");
        }
        privateMap.set(receiver, value);
        return value;
    }
    exports.__classPrivateFieldSet = __classPrivateFieldSet;
},
/* 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(404) /* ./protocol */);
    exports._testing = tslib_1.__importStar(require(405) /* ./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(28) /* ./core/settings */;
    __esExport("settings", settings_1.settings);
    var base_1 = require(7) /* ./base */;
    __esExport("Models", base_1.Models);
    var document_1 = require(5) /* ./document */;
    __esExport("documents", document_1.documents);
    var safely_1 = require(406) /* ./safely */;
    __esExport("safely", safely_1.safely);
},
/* version.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.version = "2.3.0";
},
/* embed/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const document_1 = require(5) /* ../document */;
    const logging_1 = require(19) /* ../core/logging */;
    const string_1 = require(34) /* ../core/util/string */;
    const object_1 = require(13) /* ../core/util/object */;
    const types_1 = require(8) /* ../core/util/types */;
    const defer_1 = require(16) /* ../core/util/defer */;
    const standalone_1 = require(395) /* ./standalone */;
    const server_1 = require(397) /* ./server */;
    const dom_1 = require(396) /* ./dom */;
    var standalone_2 = require(395) /* ./standalone */;
    __esExport("add_document_standalone", standalone_2.add_document_standalone);
    __esExport("index", standalone_2.index);
    var server_2 = require(397) /* ./server */;
    __esExport("add_document_from_session", server_2.add_document_from_session);
    var notebook_1 = require(402) /* ./notebook */;
    __esExport("embed_items_notebook", notebook_1.embed_items_notebook);
    __esExport("kernels", notebook_1.kernels);
    var dom_2 = require(396) /* ./dom */;
    __esExport("BOKEH_ROOT", dom_2.BOKEH_ROOT);
    async function embed_item(item, target_id) {
        const docs_json = {};
        const doc_id = string_1.uuid4();
        docs_json[doc_id] = item.doc;
        if (target_id == null)
            target_id = item.target_id;
        const element = document.getElementById(target_id);
        if (element != null)
            element.classList.add(dom_1.BOKEH_ROOT);
        const roots = { [item.root_id]: target_id };
        const render_item = { roots, root_ids: [item.root_id], docid: doc_id };
        await 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 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 (types_1.isString(docs_json))
            docs_json = JSON.parse(string_1.unescape(docs_json));
        const docs = {};
        for (const [docid, doc_json] of object_1.entries(docs_json)) {
            docs[docid] = document_1.Document.from_json(doc_json);
        }
        const views = [];
        for (const item of render_items) {
            const element = dom_1._resolve_element(item);
            const roots = dom_1._resolve_root_elements(item);
            if (item.docid != null) {
                views.push(await standalone_1.add_document_standalone(docs[item.docid], element, roots, item.use_for_title));
            }
            else if (item.token != null) {
                const websocket_url = server_1._get_ws_url(app_path, absolute_url);
                logging_1.logger.debug(`embed: computed ws url: ${websocket_url}`);
                try {
                    views.push(await 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) {
                    console.log("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(35) /* ./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 bokeh_events_1 = require(264) /* ../core/bokeh_events */;
    const has_props_1 = require(14) /* ../core/has_props */;
    const serializer_1 = require(30) /* ../core/serializer */;
    const signaling_1 = require(15) /* ../core/signaling */;
    const refs_1 = require(17) /* ../core/util/refs */;
    const serialization_1 = require(31) /* ../core/util/serialization */;
    const array_1 = require(9) /* ../core/util/array */;
    const object_1 = require(13) /* ../core/util/object */;
    const sets = tslib_1.__importStar(require(132) /* ../core/util/set */);
    const eq_1 = require(26) /* ../core/util/eq */;
    const types_1 = require(8) /* ../core/util/types */;
    const layout_dom_1 = require(319) /* ../models/layouts/layout_dom */;
    const column_data_source_1 = require(130) /* ../models/sources/column_data_source */;
    const model_1 = require(53) /* ../model */;
    const defs_1 = require(394) /* ./defs */;
    const events_1 = require(35) /* ./events */;
    // Dispatches events to the subscribed models
    class EventManager {
        constructor(document) {
            this.document = document;
            this.session = null;
            this.subscribed_models = new Set();
        }
        send_event(bokeh_event) {
            const event = new events_1.MessageSentEvent(this.document, "bokeh_event", bokeh_event.to_json());
            this.document._trigger_on_change(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() {
            exports.documents.push(this);
            this._init_timestamp = Date.now();
            this._title = exports.DEFAULT_TITLE;
            this._roots = [];
            this._all_models = new Map();
            this._all_models_freeze_count = 0;
            this._callbacks = new Map();
            this._message_callbacks = new Map();
            this.event_manager = new EventManager(this);
            this.idle = new signaling_1.Signal0(this, "idle");
            this._idle_roots = new WeakMap(); // TODO: WeakSet would be better
            this._interactive_timestamp = null;
            this._interactive_plot = null;
        }
        get layoutables() {
            return this._roots.filter((root) => root instanceof layout_dom_1.LayoutDOM);
        }
        get is_idle() {
            for (const root of this.layoutables) {
                if (!this._idle_roots.has(root))
                    return false;
            }
            return true;
        }
        notify_idle(model) {
            this._idle_roots.set(model, true);
            if (this.is_idle) {
                logging_1.logger.info(`document idle at ${Date.now() - this._init_timestamp} ms`);
                this.event_manager.send_event(new bokeh_events_1.DocumentReady());
                this.idle.emit();
            }
        }
        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) {
            if (this._interactive_plot == null) {
                this._interactive_plot = plot;
                this._interactive_plot.trigger_event(new bokeh_events_1.LODStart());
            }
            this._interactive_timestamp = Date.now();
        }
        interactive_stop() {
            if (this._interactive_plot != null) {
                this._interactive_plot.trigger_event(new bokeh_events_1.LODEnd());
            }
            this._interactive_plot = null;
            this._interactive_timestamp = 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 = 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 a of to_attach) {
                a.attach_document(this);
            }
            this._all_models = recomputed;
        }
        roots() {
            return this._roots;
        }
        add_root(model, setter_id) {
            logging_1.logger.debug(`Adding root: ${model}`);
            if (array_1.includes(this._roots, model))
                return;
            this._push_all_models_freeze();
            try {
                this._roots.push(model);
            }
            finally {
                this._pop_all_models_freeze();
            }
            this._trigger_on_change(new events_1.RootAddedEvent(this, model, setter_id));
        }
        remove_root(model, setter_id) {
            const i = this._roots.indexOf(model);
            if (i < 0)
                return;
            this._push_all_models_freeze();
            try {
                this._roots.splice(i, 1);
            }
            finally {
                this._pop_all_models_freeze();
            }
            this._trigger_on_change(new events_1.RootRemovedEvent(this, model, setter_id));
        }
        title() {
            return this._title;
        }
        set_title(title, setter_id) {
            if (title !== this._title) {
                this._title = title;
                this._trigger_on_change(new events_1.TitleChangedEvent(this, title, setter_id));
            }
        }
        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
                }
            }
        }
        _notify_change(model, attr, old_value, new_value, options) {
            this._trigger_on_change(new events_1.ModelChangedEvent(this, model, attr, old_value, new_value, options === null || options === void 0 ? void 0 : options.setter_id, options === null || options === void 0 ? void 0 : options.hint));
        }
        static _instantiate_object(obj_id, obj_type, obj_attrs) {
            const full_attrs = Object.assign(Object.assign({}, obj_attrs), { id: obj_id, __deferred__: true });
            const model = base_1.Models(obj_type);
            return new model(full_attrs);
        }
        // given a JSON representation of all models in a graph, return a
        // dict of new model objects
        static _instantiate_references_json(references_json, existing_models) {
            var _a;
            // Create all instances, but without setting their props
            const references = new Map();
            for (const obj of references_json) {
                const obj_id = obj.id;
                const obj_type = obj.type;
                const obj_attrs = (_a = obj.attributes) !== null && _a !== void 0 ? _a : {};
                let instance = existing_models.get(obj_id);
                if (instance == null) {
                    instance = Document._instantiate_object(obj_id, obj_type, obj_attrs);
                    if (obj.subtype != null)
                        instance.set_subtype(obj.subtype);
                }
                references.set(instance.id, instance);
            }
            return references;
        }
        // if v looks like a ref, or a collection, resolve it, otherwise return it unchanged
        // recurse into collections but not into HasProps
        static _resolve_refs(value, old_references, new_references, buffers) {
            function resolve_ref(v) {
                if (refs_1.is_ref(v)) {
                    if (old_references.has(v.id))
                        return old_references.get(v.id);
                    else if (new_references.has(v.id))
                        return new_references.get(v.id);
                    else
                        throw new Error(`reference ${JSON.stringify(v)} isn't known (not in Document?)`);
                }
                else if (serialization_1.is_NDArray_ref(v)) {
                    return serialization_1.decode_NDArray(v, buffers);
                }
                else if (types_1.isArray(v))
                    return resolve_array(v);
                else if (types_1.isPlainObject(v))
                    return resolve_dict(v);
                else
                    return v;
            }
            function resolve_array(array) {
                const results = [];
                for (const v of array) {
                    results.push(resolve_ref(v));
                }
                return results;
            }
            function resolve_dict(dict) {
                const resolved = {};
                for (const [k, v] of object_1.entries(dict)) {
                    resolved[k] = resolve_ref(v);
                }
                return resolved;
            }
            return resolve_ref(value);
        }
        // given a JSON representation of all models in a graph and new
        // model instances, set the properties on the models from the
        // JSON
        static _initialize_references_json(references_json, old_references, new_references, buffers) {
            const to_update = new Map();
            for (const { id, attributes } of references_json) {
                const is_new = !old_references.has(id);
                const instance = is_new ? new_references.get(id) : old_references.get(id);
                // replace references with actual instances in obj_attrs
                const resolved_attrs = Document._resolve_refs(attributes, old_references, new_references, buffers);
                instance.setv(resolved_attrs, { silent: true });
                to_update.set(id, { instance, is_new });
            }
            const ordered_instances = [];
            const handled = new Set();
            function finalize_all_by_dfs(v) {
                if (v instanceof has_props_1.HasProps) {
                    // note that we ignore instances that aren't updated (not in to_update)
                    if (to_update.has(v.id) && !handled.has(v.id)) {
                        handled.add(v.id);
                        const { instance, is_new } = to_update.get(v.id);
                        const { attributes } = instance;
                        for (const value of object_1.values(attributes)) {
                            finalize_all_by_dfs(value);
                        }
                        if (is_new) {
                            // Finalizing here just to avoid iterating
                            // over `ordered_instances` twice.
                            instance.finalize();
                            // Preserving an ordered collection of instances
                            // to avoid having to go through DFS again.
                            ordered_instances.push(instance);
                        }
                    }
                }
                else if (types_1.isArray(v)) {
                    for (const e of v)
                        finalize_all_by_dfs(e);
                }
                else if (types_1.isPlainObject(v)) {
                    for (const value of object_1.values(v))
                        finalize_all_by_dfs(value);
                }
            }
            for (const item of to_update.values()) {
                finalize_all_by_dfs(item.instance);
            }
            // `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 ordered_instances) {
                instance.connect_signals();
            }
        }
        //////
        ///{{{
        static _event_for_attribute_change(changed_obj, key, new_value, doc, value_refs) {
            const changed_model = doc.get_model_by_id(changed_obj.id); // XXX!
            if (!changed_model.property(key).syncable)
                return null;
            else {
                const event = {
                    kind: "ModelChanged",
                    model: { id: changed_obj.id },
                    attr: key,
                    new: new_value,
                };
                has_props_1.HasProps._json_record_references(doc, new_value, value_refs, { recursive: true });
                return event;
            }
        }
        static _events_to_sync_objects(from_obj, to_obj, to_doc, value_refs) {
            const from_keys = Object.keys(from_obj.attributes); //XXX!
            const to_keys = Object.keys(to_obj.attributes); //XXX!
            const removed = array_1.difference(from_keys, to_keys);
            const added = array_1.difference(to_keys, from_keys);
            const shared = array_1.intersection(from_keys, to_keys);
            const events = [];
            for (const key of removed) {
                // we don't really have a "remove" event - not sure this ever
                // happens even. One way this could happen is if the server
                // does include_defaults=True and we do
                // include_defaults=false ... in that case it'd be best to
                // just ignore this probably. Warn about it, could mean
                // there's a bug if we don't have a key that the server sent.
                logging_1.logger.warn(`Server sent key ${key} but we don't seem to have it in our JSON`);
            }
            for (const key of added) {
                const new_value = to_obj.attributes[key]; // XXX!
                events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
            }
            for (const key of shared) {
                const old_value = from_obj.attributes[key]; // XXX!
                const new_value = to_obj.attributes[key]; // XXX!
                if (old_value == null && new_value == null) {
                }
                else if (old_value == null || new_value == null) {
                    events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
                }
                else {
                    if (!eq_1.is_equal(old_value, new_value))
                        events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
                }
            }
            return events.filter((e) => e != null);
        }
        // we use this to detect changes during document deserialization
        // (in model constructors and initializers)
        static _compute_patch_since_json(from_json, to_doc) {
            const to_json = to_doc.to_json(false); // include_defaults=false
            function refs(json) {
                const result = new Map();
                for (const obj of json.roots.references)
                    result.set(obj.id, obj);
                return result;
            }
            const from_references = refs(from_json);
            const from_roots = new Map();
            const from_root_ids = [];
            for (const r of from_json.roots.root_ids) {
                from_roots.set(r, from_references.get(r));
                from_root_ids.push(r);
            }
            const to_references = refs(to_json);
            const to_roots = new Map();
            const to_root_ids = [];
            for (const r of to_json.roots.root_ids) {
                to_roots.set(r, to_references.get(r));
                to_root_ids.push(r);
            }
            from_root_ids.sort();
            to_root_ids.sort();
            if (array_1.difference(from_root_ids, to_root_ids).length > 0 ||
                array_1.difference(to_root_ids, from_root_ids).length > 0) {
                // this would arise if someone does add_root/remove_root during
                // document deserialization, hopefully they won't ever do so.
                throw new Error("Not implemented: computing add/remove of document roots");
            }
            const value_refs = new Set();
            let events = [];
            for (const id of to_doc._all_models.keys()) {
                if (from_references.has(id)) {
                    const update_model_events = Document._events_to_sync_objects(from_references.get(id), to_references.get(id), to_doc, value_refs);
                    events = events.concat(update_model_events);
                }
            }
            const serializer = new serializer_1.Serializer({ include_defaults: false });
            serializer.to_serializable([...value_refs]);
            return {
                references: [...serializer.definitions],
                events,
            };
        }
        ///}}}
        //////
        to_json_string(include_defaults = true) {
            return JSON.stringify(this.to_json(include_defaults));
        }
        to_json(include_defaults = true) {
            const serializer = new serializer_1.Serializer({ include_defaults });
            const roots = serializer.to_serializable(this._roots);
            return {
                version: version_1.version,
                title: this._title,
                roots: {
                    root_ids: roots.map((r) => r.id),
                    references: [...serializer.definitions],
                },
            };
        }
        static from_json_string(s) {
            const json = JSON.parse(s);
            return Document.from_json(json);
        }
        static from_json(json) {
            logging_1.logger.debug("Creating Document from JSON");
            function pyify(version) {
                return version.replace(/-(dev|rc)\./, "$1");
            }
            const py_version = json.version; // XXX!
            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 && pyify(version_1.version) != py_version) {
                logging_1.logger.warn("JS/Python version mismatch");
                logging_1.logger.warn(versions_string);
            }
            else
                logging_1.logger.debug(versions_string);
            if (json.defs != null) {
                defs_1.resolve_defs(json.defs);
            }
            const roots_json = json.roots;
            const root_ids = roots_json.root_ids;
            const references_json = roots_json.references;
            const references = Document._instantiate_references_json(references_json, new Map());
            Document._initialize_references_json(references_json, new Map(), references, new Map());
            const doc = new Document();
            for (const id of root_ids) {
                const root = references.get(id);
                if (root != null) {
                    doc.add_root(root); // XXX: HasProps
                }
            }
            doc.set_title(json.title); // XXX!
            return doc;
        }
        replace_with_json(json) {
            const replacement = Document.from_json(json);
            replacement.destructively_move(this);
        }
        create_json_patch_string(events) {
            return JSON.stringify(this.create_json_patch(events));
        }
        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 serializer = new serializer_1.Serializer();
            return {
                events: serializer.to_serializable(events),
                references: [...serializer.definitions],
            };
        }
        apply_json_patch(patch, buffers = new Map(), setter_id) {
            const references_json = patch.references;
            const events_json = patch.events;
            const references = Document._instantiate_references_json(references_json, this._all_models);
            if (!(buffers instanceof Map)) {
                buffers = new Map(buffers);
            }
            // The model being changed isn't always in references so add it in
            for (const event_json of events_json) {
                switch (event_json.kind) {
                    case "RootAdded":
                    case "RootRemoved":
                    case "ModelChanged": {
                        const model_id = event_json.model.id;
                        const model = this._all_models.get(model_id);
                        if (model != null) {
                            references.set(model_id, model);
                        }
                        else if (!references.has(model_id)) {
                            logging_1.logger.warn(`Got an event for unknown model ${event_json.model}"`);
                            throw new Error("event model wasn't known");
                        }
                        break;
                    }
                }
            }
            // split references into old and new so we know whether to initialize or update
            const old_references = new Map();
            const new_references = new Map();
            for (const [id, value] of references) {
                if (this._all_models.has(id))
                    old_references.set(id, value);
                else
                    new_references.set(id, value);
            }
            Document._initialize_references_json(references_json, old_references, new_references, buffers);
            for (const event_json of events_json) {
                switch (event_json.kind) {
                    case 'MessageSent': {
                        const { msg_type, msg_data } = event_json;
                        let data;
                        if (msg_data === undefined) {
                            if (buffers.size == 1) {
                                const [[, buffer]] = buffers;
                                data = buffer;
                            }
                            else {
                                throw new Error("expected exactly one buffer");
                            }
                        }
                        else {
                            data = Document._resolve_refs(msg_data, old_references, new_references, buffers);
                        }
                        this._trigger_on_message(msg_type, data);
                        break;
                    }
                    case 'ModelChanged': {
                        const patched_id = event_json.model.id;
                        const patched_obj = this._all_models.get(patched_id);
                        if (patched_obj == null) {
                            throw new Error(`Cannot apply patch to ${patched_id} which is not in the document`);
                        }
                        const attr = event_json.attr;
                        const value = Document._resolve_refs(event_json.new, old_references, new_references, buffers);
                        patched_obj.setv({ [attr]: value }, { setter_id });
                        break;
                    }
                    case 'ColumnDataChanged': {
                        const column_source_id = event_json.column_source.id;
                        const column_source = this._all_models.get(column_source_id);
                        if (column_source == null) {
                            throw new Error(`Cannot stream to ${column_source_id} which is not in the document`);
                        }
                        const data = Document._resolve_refs(event_json.new, new Map(), new Map(), buffers);
                        if (event_json.cols != null) {
                            for (const k in column_source.data) {
                                if (!(k in data)) {
                                    data[k] = column_source.data[k];
                                }
                            }
                        }
                        column_source.setv({ data }, { setter_id, check_eq: false });
                        break;
                    }
                    case 'ColumnsStreamed': {
                        const column_source_id = event_json.column_source.id;
                        const column_source = this._all_models.get(column_source_id);
                        if (column_source == null) {
                            throw new Error(`Cannot stream to ${column_source_id} which is not in the document`);
                        }
                        if (!(column_source instanceof column_data_source_1.ColumnDataSource)) {
                            throw new Error("Cannot stream to non-ColumnDataSource");
                        }
                        const data = event_json.data;
                        const rollover = event_json.rollover;
                        column_source.stream(data, rollover, setter_id);
                        break;
                    }
                    case 'ColumnsPatched': {
                        const column_source_id = event_json.column_source.id;
                        const column_source = this._all_models.get(column_source_id);
                        if (column_source == null) {
                            throw new Error(`Cannot patch ${column_source_id} which is not in the document`);
                        }
                        if (!(column_source instanceof column_data_source_1.ColumnDataSource)) {
                            throw new Error("Cannot patch non-ColumnDataSource");
                        }
                        const patches = event_json.patches;
                        column_source.patch(patches, setter_id);
                        break;
                    }
                    case 'RootAdded': {
                        const root_id = event_json.model.id;
                        const root_obj = references.get(root_id);
                        this.add_root(root_obj, setter_id); // XXX: HasProps
                        break;
                    }
                    case 'RootRemoved': {
                        const root_id = event_json.model.id;
                        const root_obj = references.get(root_id);
                        this.remove_root(root_obj, setter_id); // XXX: HasProps
                        break;
                    }
                    case 'TitleChanged': {
                        this.set_title(event_json.title, setter_id);
                        break;
                    }
                    default:
                        throw new Error("Unknown patch event " + JSON.stringify(event_json));
                }
            }
        }
    }
    exports.Document = Document;
    Document.__name__ = "Document";
},
/* base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const types_1 = require(8) /* ./core/util/types */;
    const object_1 = require(13) /* ./core/util/object */;
    const has_props_1 = require(14) /* ./core/has_props */;
    exports.overrides = {};
    const _all_models = new Map();
    exports.Models = ((name) => {
        const model = exports.Models.get(name);
        if (model != null)
            return model;
        else
            throw new Error(`Model '${name}' does not exist. This could be due to a widget or a custom model not being registered before first usage.`);
    });
    exports.Models.get = (name) => {
        var _a;
        return (_a = exports.overrides[name]) !== null && _a !== void 0 ? _a : _all_models.get(name);
    };
    exports.Models.register = (name, model) => {
        exports.overrides[name] = model;
    };
    exports.Models.unregister = (name) => {
        delete exports.overrides[name];
    };
    function is_HasProps(obj) {
        return types_1.isObject(obj) && obj.prototype instanceof has_props_1.HasProps;
    }
    exports.Models.register_models = (models, force = false, errorFn) => {
        if (models == null)
            return;
        for (const model of types_1.isArray(models) ? models : object_1.values(models)) {
            if (is_HasProps(model)) {
                const qualified = model.__qualified__;
                if (force || !_all_models.has(qualified))
                    _all_models.set(qualified, model);
                else if (errorFn != null)
                    errorFn(qualified);
                else
                    console.warn(`Model '${qualified}' was already registered`);
            }
        }
    };
    exports.register_models = exports.Models.register_models;
    exports.Models.registered_names = () => [..._all_models.keys()];
    // TODO: this doesn't belong here, but it's easier this way for backwards compatibility
    const AllModels = tslib_1.__importStar(require(38) /* ./models */);
    exports.register_models(AllModels);
},
/* 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 array_1 = require(9) /* ./array */;
    const toString = Object.prototype.toString;
    function isBoolean(obj) {
        return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
    }
    exports.isBoolean = isBoolean;
    function isNumber(obj) {
        return toString.call(obj) === "[object Number]";
    }
    exports.isNumber = isNumber;
    function isInteger(obj) {
        return isNumber(obj) && Number.isInteger(obj);
    }
    exports.isInteger = isInteger;
    function isString(obj) {
        return toString.call(obj) === "[object String]";
    }
    exports.isString = isString;
    function isPrimitive(obj) {
        return obj === null || isBoolean(obj) || isNumber(obj) || isString(obj);
    }
    exports.isPrimitive = isPrimitive;
    function isFunction(obj) {
        return toString.call(obj) === "[object Function]";
    }
    exports.isFunction = isFunction;
    function isArray(obj) {
        return Array.isArray(obj);
    }
    exports.isArray = isArray;
    function isArrayOf(arr, predicate) {
        return array_1.every(arr, predicate);
    }
    exports.isArrayOf = isArrayOf;
    function isArrayableOf(arr, predicate) {
        for (let i = 0, end = arr.length; i < end; i++) {
            if (!predicate(arr[i]))
                return false;
        }
        return true;
    }
    exports.isArrayableOf = isArrayableOf;
    function isTypedArray(obj) {
        return ArrayBuffer.isView(obj) && !(obj instanceof DataView);
    }
    exports.isTypedArray = isTypedArray;
    function isObject(obj) {
        const tp = typeof obj;
        return tp === 'function' || tp === 'object' && !!obj;
    }
    exports.isObject = isObject;
    function isPlainObject(obj) {
        return isObject(obj) && (obj.constructor == null || obj.constructor === Object);
    }
    exports.isPlainObject = isPlainObject;
    function isIterable(obj) {
        return isObject(obj) && obj[Symbol.iterator] !== undefined;
    }
    exports.isIterable = isIterable;
    function isArrayable(obj) {
        return isIterable(obj) && "length" in obj;
    }
    exports.isArrayable = isArrayable;
},
/* core/util/array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    //     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(10) /* ./math */;
    const assert_1 = require(11) /* ./assert */;
    const arrayable_1 = require(12) /* ./arrayable */;
    __esExport("map", arrayable_1.map);
    __esExport("reduce", arrayable_1.reduce);
    __esExport("min", arrayable_1.min);
    __esExport("min_by", arrayable_1.min_by);
    __esExport("max", arrayable_1.max);
    __esExport("max_by", arrayable_1.max_by);
    __esExport("sum", arrayable_1.sum);
    __esExport("cumsum", arrayable_1.cumsum);
    __esExport("every", arrayable_1.every);
    __esExport("some", arrayable_1.some);
    __esExport("find", arrayable_1.find);
    __esExport("find_last", arrayable_1.find_last);
    __esExport("find_index", arrayable_1.find_index);
    __esExport("find_last_index", arrayable_1.find_last_index);
    __esExport("sorted_index", arrayable_1.sorted_index);
    __esExport("is_empty", arrayable_1.is_empty);
    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 includes(array, value) {
        return array.indexOf(value) !== -1;
    }
    exports.includes = includes;
    exports.contains = includes;
    function nth(array, index) {
        return array[index >= 0 ? index : array.length + index];
    }
    exports.nth = nth;
    function zip(...arrays) {
        if (arrays.length == 0)
            return [];
        const n = 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;
        const k = 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) {
        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 = (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 arrayable_1.min_by(range(array.length), (i) => array[i]);
    }
    exports.argmin = argmin;
    function argmax(array) {
        return arrayable_1.max_by(range(array.length), (i) => array[i]);
    }
    exports.argmax = argmax;
    function sort_by(array, key) {
        const tmp = array.map((value, index) => {
            return { value, index, key: key(value) };
        });
        tmp.sort((left, right) => {
            const a = left.key;
            const b = right.key;
            if (a !== b) {
                if (a > b || a === undefined)
                    return 1;
                if (a < b || b === undefined)
                    return -1;
            }
            return left.index - right.index;
        });
        return tmp.map((item) => item.value);
    }
    exports.sort_by = sort_by;
    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 (!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 intersection(array, ...arrays) {
        const result = [];
        top: for (const item of array) {
            if (includes(result, item))
                continue;
            for (const other of arrays) {
                if (!includes(other, item))
                    continue top;
            }
            result.push(item);
        }
        return result;
    }
    exports.intersection = intersection;
    function difference(array, ...arrays) {
        const rest = concat(arrays);
        return array.filter((value) => !includes(rest, value));
    }
    exports.difference = difference;
    function remove_at(array, i) {
        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;
    // 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 = 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);
        for (let i = 0; i < n; i++) {
            result[i] = value;
        }
        return result;
    }
    exports.repeat = repeat;
},
/* core/util/math.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const { PI } = 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 random() {
        return Math.random();
    }
    exports.random = random;
    function randomIn(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        return min + Math.floor(Math.random() * (max - min + 1));
    }
    exports.randomIn = randomIn;
    function atan2(start, end) {
        /*
         * Calculate the angle between a line containing start and end points (composed
         * of [x, y] arrays) and the positive x-axis.
         */
        return Math.atan2(end[1] - start[1], end[0] - start[0]);
    }
    exports.atan2 = atan2;
    function radians(degrees) {
        return degrees * (PI / 180);
    }
    exports.radians = radians;
    function degrees(radians) {
        return radians / (PI / 180);
    }
    exports.degrees = degrees;
    function resolve_angle(angle, units) {
        /** Convert CCW angle with units to CW radians (canvas). */
        return -to_radians_coeff(units) * angle;
    }
    exports.resolve_angle = resolve_angle;
    function to_radians_coeff(units) {
        switch (units) {
            case "deg": return PI / 180;
            case "rad": return 1;
            case "grad": return PI / 200;
            case "turn": return 2 * PI;
        }
    }
    exports.to_radians_coeff = to_radians_coeff;
    // http://www2.econ.osaka-u.ac.jp/~tanizaki/class/2013/econome3/13.pdf (Page 432)
    function rnorm(mu, sigma) {
        // Generate a random normal with a mean of 0 and a sigma of 1
        let r1;
        let r2;
        while (true) {
            r1 = random();
            r2 = random();
            r2 = (2 * r2 - 1) * Math.sqrt(2 * (1 / Math.E));
            if (-4 * r1 * r1 * Math.log(r1) >= r2 * r2)
                break;
        }
        let rn = r2 / r1;
        // Transform the standard normal to meet the characteristics that we want (mu, sigma)
        rn = mu + sigma * rn;
        return rn;
    }
    exports.rnorm = rnorm;
    function clamp(val, min, max) {
        return val < min ? min : (val > max ? max : val);
    }
    exports.clamp = clamp;
    function log(x, base = Math.E) {
        return Math.log(x) / Math.log(base);
    }
    exports.log = log;
},
/* core/util/assert.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class AssertionError extends Error {
    }
    exports.AssertionError = AssertionError;
    AssertionError.__name__ = "AssertionError";
    function assert(condition, message) {
        if (condition === true || (condition !== false && condition()))
            return;
        throw new AssertionError(message !== null && message !== void 0 ? message : "Assertion failed");
    }
    exports.assert = assert;
    function unreachable() {
        throw new Error("unreachable code");
    }
    exports.unreachable = unreachable;
},
/* core/util/arrayable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const math_1 = require(10) /* ./math */;
    function is_empty(array) {
        return array.length == 0;
    }
    exports.is_empty = is_empty;
    function copy(array) {
        if (Array.isArray(array))
            return array.slice();
        else
            return new array.constructor(array);
    }
    exports.copy = copy;
    function splice(array, start, k, ...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 indexOf(array, item) {
        for (let i = 0, n = array.length; i < n; i++) {
            if (array[i] === item)
                return i;
        }
        return -1;
    }
    exports.indexOf = indexOf;
    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 min(array) {
        let value;
        let result = Infinity;
        for (let i = 0, length = array.length; i < length; i++) {
            value = array[i];
            if (!isNaN(value) && value < result) {
                result = value;
            }
        }
        return result;
    }
    exports.min = min;
    function max(array) {
        let value;
        let result = -Infinity;
        for (let i = 0, length = array.length; i < length; i++) {
            value = array[i];
            if (!isNaN(value) && value > result) {
                result = value;
            }
        }
        return result;
    }
    exports.max = max;
    function minmax(array) {
        let value;
        let min = +Infinity;
        let max = -Infinity;
        for (let i = 0, length = array.length; i < length; i++) {
            value = array[i];
            if (!isNaN(value)) {
                if (value < min) {
                    min = value;
                }
                if (value > max) {
                    max = value;
                }
            }
        }
        return [min, max];
    }
    exports.minmax = minmax;
    function min_by(array, key) {
        if (array.length == 0)
            throw new Error("min_by() called with an empty array");
        let result = array[0];
        let resultComputed = key(result);
        for (let i = 1, length = array.length; i < length; i++) {
            const value = array[i];
            const computed = key(value);
            if (computed < resultComputed) {
                result = value;
                resultComputed = computed;
            }
        }
        return result;
    }
    exports.min_by = min_by;
    function max_by(array, key) {
        if (array.length == 0)
            throw new Error("max_by() called with an empty array");
        let result = array[0];
        let resultComputed = key(result);
        for (let i = 1, length = array.length; i < length; i++) {
            const value = array[i];
            const computed = key(value);
            if (computed > resultComputed) {
                result = value;
                resultComputed = 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(array, predicate) {
        for (let i = 0, length = array.length; i < length; i++) {
            if (!predicate(array[i]))
                return false;
        }
        return true;
    }
    exports.every = every;
    function some(array, predicate) {
        for (let i = 0, length = array.length; i < length; i++) {
            if (predicate(array[i]))
                return true;
        }
        return false;
    }
    exports.some = some;
    function index_of(array, value) {
        for (let i = 0, length = array.length; i < length; i++) {
            if (array[i] === value)
                return i;
        }
        return -1;
    }
    exports.index_of = index_of;
    function _find_index(dir) {
        return function (array, predicate) {
            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 = exports.find_index(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    exports.find = find;
    function find_last(array, predicate) {
        const index = exports.find_last_index(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    exports.find_last = find_last;
    function sorted_index(array, value) {
        let low = 0;
        let high = array.length;
        while (low < high) {
            const mid = Math.floor((low + high) / 2);
            if (array[mid] < value)
                low = mid + 1;
            else
                high = mid;
        }
        return low;
    }
    exports.sorted_index = sorted_index;
    function bin_counts(data, bin_edges) {
        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 = sorted_index(bin_edges, sample);
            const bin = 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)) {
                results[i] = point;
                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;
        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/util/object.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(9) /* ./array */;
    const { hasOwnProperty } = Object.prototype;
    exports.keys = Object.keys, exports.values = Object.values, exports.entries = Object.entries, exports.extend = Object.assign;
    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 = 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] = array_1.union(arr1, arr2);
        }
        return result;
    }
    exports.merge = merge;
    function size(obj) {
        return Object.keys(obj).length;
    }
    exports.size = size;
    function isEmpty(obj) {
        return size(obj) == 0;
    }
    exports.isEmpty = isEmpty;
    function to_object(map) {
        const obj = {};
        for (const [key, val] of map) {
            obj[key] = val;
        }
        return obj;
    }
    exports.to_object = to_object;
},
/* core/has_props.js */ function _(require, module, exports, __esModule, __esExport) {
    __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 string_1 = require(34) /* ./util/string */;
    const object_1 = require(13) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    const eq_1 = require(26) /* ./util/eq */;
    const serializer_1 = require(30) /* ./serializer */;
    const events_1 = require(35) /* ../document/events */;
    const eq_2 = require(26) /* ./util/eq */;
    const pretty_1 = require(36) /* ./util/pretty */;
    const cloneable_1 = require(37) /* ./util/cloneable */;
    const kinds = tslib_1.__importStar(require(21) /* ./kinds */);
    class HasProps extends signaling_1.Signalable() {
        constructor(attrs = {}) {
            var _a, _b;
            super();
            this._subtype = undefined;
            this.document = null;
            this.destroyed = new signaling_1.Signal0(this, "destroyed");
            this.change = new signaling_1.Signal0(this, "change");
            this.transformchange = new signaling_1.Signal0(this, "transformchange");
            this.exprchange = new signaling_1.Signal0(this, "exprchange");
            this.properties = {};
            this._pending = false;
            this._changing = false;
            const get = attrs instanceof Map ? attrs.get.bind(attrs) : (name) => attrs[name];
            this.id = (_a = get("id")) !== null && _a !== void 0 ? _a : string_1.uniqueId();
            for (const [name, { type, default_value, options }] of 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, get(name), options);
                    else
                        property = new type(this, name, k.Any, default_value, get(name), 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 (!((_b = get("__deferred__")) !== null && _b !== void 0 ? _b : false)) {
                this.finalize();
                this.connect_signals();
            }
        }
        get is_syncable() {
            return true;
        }
        // XXX: setter is only required for backwards compatibility
        set type(name) {
            console.warn("prototype.type = 'ModelName' is deprecated, use static __name__ instead");
            this.constructor.__name__ = name;
        }
        get type() {
            return this.constructor.__qualified__;
        }
        static get __qualified__() {
            const { __module__, __name__ } = this;
            return __module__ != null ? `${__module__}.${__name__}` : __name__;
        }
        static get [Symbol.toStringTag]() {
            return this.__name__;
        }
        static init_HasProps() {
            this.prototype._props = {};
            this.prototype._mixins = [];
        }
        static _fix_default(default_value, _attr) {
            if (default_value === undefined || types_1.isFunction(default_value))
                return default_value;
            else if (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 object_1.entries(types_1.isFunction(obj) ? obj(kinds) : obj)) {
                if (this.prototype._props[name] != null)
                    throw new Error(`attempted to redefine property '${this.prototype.type}.${name}'`);
                if (this.prototype[name] != null)
                    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,
                };
                const props = Object.assign({}, this.prototype._props);
                props[name] = refined_prop;
                this.prototype._props = props;
            }
        }
        static internal(obj) {
            const _object = {};
            for (const [name, prop] of object_1.entries(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 object_1.entries(mixin)) {
                    result[prefix + name] = prop;
                }
                return result;
            }
            const mixin_defs = {};
            const mixins = [];
            for (const def of types_1.isArray(defs) ? defs : [defs]) {
                if (types_1.isArray(def)) {
                    const [prefix, mixin] = def;
                    object_1.extend(mixin_defs, rename(prefix, mixin));
                    mixins.push([prefix, mixin]);
                }
                else {
                    const mixin = def;
                    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 object_1.entries(obj)) {
                const default_value = this._fix_default(prop, name);
                const value = this.prototype._props[name];
                if (value == null)
                    throw new Error(`attempted to override nonexistent '${this.prototype.type}.${name}'`);
                const props = Object.assign({}, this.prototype._props);
                props[name] = Object.assign(Object.assign({}, value), { default_value });
                this.prototype._props = props;
            }
        }
        toString() {
            return `${this.type}(${this.id})`;
        }
        property(name) {
            const prop = this.properties[name];
            if (prop != null)
                return prop;
            else
                throw new Error(`unknown property ${this.type}.${name}`);
        }
        get attributes() {
            const attrs = {};
            for (const prop of this) {
                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(")")}`;
        }
        [serializer_1.serialize](serializer) {
            const ref = this.ref();
            serializer.add_ref(this, ref);
            const struct = this.struct();
            for (const prop of this) {
                if (prop.syncable && (serializer.include_defaults || prop.dirty)) {
                    struct.attributes[prop.attr] = serializer.to_serializable(prop.get_value());
                }
            }
            serializer.add_def(this, struct);
            return ref;
        }
        finalize() {
            for (const prop of this) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                    continue;
                const value = prop.get_value(); // XXX: T -> any under instanceof
                if (value != null) {
                    const { transform, expr } = value;
                    if (transform != null)
                        this.connect(transform.change, () => this.transformchange.emit());
                    if (expr != null)
                        this.connect(expr.change, () => this.exprchange.emit());
                }
            }
            this.initialize();
        }
        initialize() { }
        connect_signals() { }
        disconnect_signals() {
            signaling_1.Signal.disconnectReceiver(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);
        }
        // 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) {
            // Extract attributes and options.
            const check_eq = options.check_eq;
            const changed = [];
            const changing = this._changing;
            this._changing = true;
            for (const [prop, value] of changes) {
                if (check_eq === false || !eq_1.is_equal(prop.get_value(), value)) {
                    prop.set_value(value);
                    changed.push(prop);
                }
            }
            // Trigger all relevant attribute changes.
            if (changed.length > 0)
                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)
                return;
            if (!options.no_change) {
                while (this._pending) {
                    this._pending = false;
                    this.change.emit();
                }
            }
            this._pending = false;
            this._changing = false;
        }
        setv(changed_attrs, options = {}) {
            const changes = object_1.entries(changed_attrs);
            if (changes.length == 0)
                return;
            if (options.silent === true) {
                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.get_value());
            }
            this._setv(changed, options);
            const { document } = this;
            if (document != null) {
                const changed = [];
                for (const [prop, value] of previous) {
                    changed.push([prop, value, prop.get_value()]);
                }
                for (const [, old_value, new_value] of changed) {
                    if (this._needs_invalidate(old_value, new_value)) {
                        document._invalidate_all_models();
                        break;
                    }
                }
                this._push_changes(changed, options);
            }
        }
        /** @deprecated */
        getv(name) {
            return this.property(name).get_value();
        }
        ref() {
            return { id: this.id };
        }
        struct() {
            const struct = {
                type: this.type,
                id: this.id,
                attributes: {},
            };
            if (this._subtype != null) {
                struct.subtype = this._subtype;
            }
            return struct;
        }
        // we only keep the subtype so we match Python;
        // only Python cares about this
        set_subtype(subtype) {
            this._subtype = subtype;
        }
        *[Symbol.iterator]() {
            yield* object_1.values(this.properties);
        }
        *syncable_properties() {
            for (const prop of this) {
                if (prop.syncable)
                    yield prop;
            }
        }
        /** @deprecated */
        serializable_attributes() {
            const attrs = {};
            for (const prop of this.syncable_properties()) {
                attrs[prop.attr] = prop.get_value();
            }
            return attrs;
        }
        // this is like _value_record_references but expects to find refs
        // instead of models, and takes a doc to look up the refs in
        static _json_record_references(doc, v, refs, options) {
            const { recursive } = options;
            if (refs_1.is_ref(v)) {
                const model = doc.get_model_by_id(v.id);
                if (model != null && !refs.has(model)) {
                    HasProps._value_record_references(model, refs, { recursive });
                }
            }
            else if (types_1.isArray(v)) {
                for (const elem of v)
                    HasProps._json_record_references(doc, elem, refs, { recursive });
            }
            else if (types_1.isPlainObject(v)) {
                for (const elem of object_1.values(v)) {
                    HasProps._json_record_references(doc, elem, refs, { recursive });
                }
            }
        }
        // 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(v, refs, options) {
            const { recursive } = options;
            if (v instanceof HasProps) {
                if (!refs.has(v)) {
                    refs.add(v);
                    if (recursive) {
                        for (const prop of v.syncable_properties()) {
                            const value = prop.get_value();
                            HasProps._value_record_references(value, refs, { recursive });
                        }
                    }
                }
            }
            else if (types_1.isArray(v)) {
                for (const elem of v)
                    HasProps._value_record_references(elem, refs, { recursive });
            }
            else if (types_1.isPlainObject(v)) {
                for (const elem of object_1.values(v)) {
                    HasProps._value_record_references(elem, refs, { recursive });
                }
            }
        }
        references() {
            const refs = new Set();
            HasProps._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 && this.document != doc)
                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();
            HasProps._value_record_references(new_value, new_refs, { recursive: false });
            const old_refs = new Set();
            HasProps._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, options = {}) {
            if (!this.is_syncable)
                return;
            const { document } = this;
            if (document == null)
                return;
            const { setter_id } = options;
            const events = [];
            for (const [prop, old_value, new_value] of changes) {
                if (prop.syncable)
                    events.push(new events_1.ModelChangedEvent(document, this, prop.attr, old_value, new_value, setter_id));
            }
            if (events.length != 0) {
                let event;
                if (events.length == 1)
                    [event] = events;
                else
                    event = new events_1.DocumentEventBatch(document, events, setter_id);
                document._trigger_on_change(event);
            }
        }
        on_change(properties, fn) {
            for (const property of types_1.isArray(properties) ? properties : [properties]) {
                this.connect(property.change, fn);
            }
        }
    }
    exports.HasProps = HasProps;
    HasProps.init_HasProps();
},
/* 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(9) /* ./util/array */;
    class Signal {
        constructor(sender, name) {
            this.sender = sender;
            this.name = name;
        }
        connect(slot, context = null) {
            if (!receiversForSender.has(this.sender)) {
                receiversForSender.set(this.sender, []);
            }
            const receivers = receiversForSender.get(this.sender);
            if (find_connection(receivers, this, slot, context) != null) {
                return false;
            }
            const receiver = context !== null && context !== void 0 ? context : slot;
            if (!sendersForReceiver.has(receiver)) {
                sendersForReceiver.set(receiver, []);
            }
            const senders = sendersForReceiver.get(receiver);
            const connection = { signal: this, slot, context };
            receivers.push(connection);
            senders.push(connection);
            return true;
        }
        disconnect(slot, context = null) {
            const receivers = receiversForSender.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 = sendersForReceiver.get(receiver);
            connection.signal = null;
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
            return true;
        }
        emit(args) {
            var _a;
            const receivers = (_a = receiversForSender.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 = receiversForSender.get(sender);
            if (receivers == null || receivers.length === 0)
                return;
            const senders = sendersForReceiver.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 = receiversForSender.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(sendersForReceiver.get(receiver));
            }
            schedule_cleanup(receivers);
        }
        Signal.disconnect_sender = disconnect_sender;
        function disconnect_receiver(receiver, slot, except_senders) {
            const senders = sendersForReceiver.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(receiversForSender.get(sender));
            }
            schedule_cleanup(senders);
        }
        Signal.disconnect_receiver = disconnect_receiver;
        function disconnect_all(obj) {
            const receivers = receiversForSender.get(obj);
            if (receivers != null && receivers.length !== 0) {
                for (const connection of receivers) {
                    connection.signal = null;
                }
                schedule_cleanup(receivers);
            }
            const senders = sendersForReceiver.get(obj);
            if (senders != null && senders.length !== 0) {
                for (const connection of senders) {
                    connection.signal = null;
                }
                schedule_cleanup(senders);
            }
        }
        Signal.disconnect_all = disconnect_all;
        /** @deprecated */
        Signal.disconnectBetween = disconnect_between;
        /** @deprecated */
        Signal.disconnectSender = disconnect_sender;
        /** @deprecated */
        Signal.disconnectReceiver = disconnect_receiver;
        /** @deprecated */
        Signal.disconnectAll = disconnect_all;
    })(Signal || (exports.Signal = Signal = {}));
    function Signalable() {
        return class {
            connect(signal, slot) {
                return signal.connect(slot, this);
            }
            disconnect(signal, slot) {
                return signal.disconnect(slot, this);
            }
        };
    }
    exports.Signalable = Signalable;
    const receiversForSender = new WeakMap();
    const sendersForReceiver = new WeakMap();
    function find_connection(conns, signal, slot, context) {
        return 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 defer_1.defer();
                cleanup_dirty_set();
            })();
        }
        dirty_set.add(connections);
    }
    function cleanup_dirty_set() {
        for (const connections of dirty_set) {
            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;
},
/* core/util/refs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ./types */;
    const object_1 = require(13) /* ./object */;
    // Determine whether an object has the proper format of a Bokeh reference
    //
    // @param arg [Object] the object to test
    // @return [bool] whether the object is a reference
    //
    // @note this function does not check that the id and types are valid,
    //   only that the format is correct (all required keys are present)
    //
    function is_ref(arg) {
        if (types_1.isPlainObject(arg)) {
            const attrs = object_1.keys(arg);
            return attrs.length == 1 && attrs[0] == "id";
        }
        return false;
    }
    exports.is_ref = is_ref;
},
/* core/properties.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.YCoordinateSeqSeqSeqSpec = exports.XCoordinateSeqSeqSeqSpec = exports.YCoordinateSeqSpec = exports.XCoordinateSeqSpec = exports.YCoordinateSpec = exports.XCoordinateSpec = exports.CoordinateSeqSeqSeqSpec = exports.CoordinateSeqSpec = exports.CoordinateSpec = exports.BaseCoordinateSpec = exports.NumberUnitsSpec = exports.UnitsSpec = exports.DataSpec = exports.VectorSpec = exports.TextBaselineScalar = exports.TextAlignScalar = exports.FontStyleScalar = exports.FontSizeScalar = exports.FontScalar = exports.LineDashScalar = exports.LineCapScalar = exports.LineJoinScalar = exports.ArrayScalar = exports.NullStringScalar = exports.StringScalar = exports.NumberScalar = exports.ColorScalar = exports.AnyScalar = exports.ScalarSpec = exports.VerticalAlign = exports.UpdateMode = exports.TooltipAttachment = exports.TickLabelOrientation = exports.TextureRepetition = exports.TextBaseline = exports.TextAlign = exports.TapBehavior = exports.StepMode = exports.StartEnd = exports.SpatialUnits = exports.Sort = exports.SizingMode = exports.Side = exports.RoundingFunction = exports.ResetPolicy = exports.RenderMode = exports.RenderLevel = exports.RadiusDimension = exports.PointPolicy = exports.Place = void 0;
    exports.TextBaselineSpec = exports.TextAlignSpec = exports.FontStyleSpec = exports.FontSizeSpec = exports.FontSpec = exports.LineDashSpec = exports.LineCapSpec = exports.LineJoinSpec = exports.MarkerSpec = exports.ArraySpec = exports.NullStringSpec = exports.StringSpec = exports.AnySpec = exports.NDArraySpec = exports.ColorSpec = exports.NumberSpec = exports.BooleanSpec = exports.ScreenDistanceSpec = exports.NullDistanceSpec = exports.DistanceSpec = exports.AngleSpec = 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(9) /* ./util/array */;
    const arrayable_1 = require(12) /* ./util/arrayable */;
    const math_1 = require(10) /* ./util/math */;
    const color_1 = require(22) /* ./util/color */;
    const platform_1 = require(27) /* ./util/platform */;
    const types_2 = require(8) /* ./util/types */;
    const settings_1 = require(28) /* ./settings */;
    const ndarray_1 = require(29) /* ./util/ndarray */;
    const uniforms_1 = require(33) /* ./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 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;
    class Property {
        constructor(obj, attr, kind, default_value, initial_value, options = {}) {
            var _a;
            this.obj = obj;
            this.attr = attr;
            this.kind = kind;
            this.default_value = default_value;
            this._dirty = false;
            this.change = new signaling_1.Signal0(this.obj, "change");
            this.internal = (_a = options.internal) !== null && _a !== void 0 ? _a : false;
            this.on_update = options.on_update;
            let attr_value;
            if (initial_value !== undefined) {
                attr_value = initial_value;
                this._dirty = true;
            }
            else {
                const value = this._default_override();
                if (value !== undefined)
                    attr_value = value;
                else if (default_value !== undefined)
                    attr_value = default_value(obj);
                else {
                    // XXX: temporary and super sketchy, but affects only "readonly" and a few internal properties
                    // console.warn(`${this.obj}.${this.attr} has no value nor default`)
                    this.spec = { value: null };
                    return;
                }
            }
            this._update(attr_value);
        }
        get is_value() {
            return this.spec.value !== undefined;
        }
        get syncable() {
            return !this.internal;
        }
        get_value() {
            return this.spec.value;
        }
        set_value(val) {
            this._update(val);
            this._dirty = true;
        }
        // abstract _intrinsic_default(): T
        _default_override() {
            return undefined;
        }
        get dirty() {
            return this._dirty;
        }
        //protected abstract _update(attr_value: T): void
        _update(attr_value) {
            var _a;
            this.validate(attr_value);
            this.spec = { 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}, spec: ${valueToString(this.spec)})`;
        }
        // ----- 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);
        }
        // ----- property accessors
        _value(do_spec_transform = true) {
            if (!this.is_value)
                throw new Error("attempted to retrieve property value for property without value specification");
            let ret = this.normalize([this.spec.value])[0];
            if (this.spec.transform != null && do_spec_transform)
                ret = this.spec.transform.compute(ret);
            return ret;
        }
    }
    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";
    /** @deprecated */
    class Any extends Property {
    }
    exports.Any = Any;
    Any.__name__ = "Any";
    /** @deprecated */
    class Array extends Property {
        valid(value) {
            return types_2.isArray(value) || types_2.isTypedArray(value);
        }
    }
    exports.Array = Array;
    Array.__name__ = "Array";
    /** @deprecated */
    class Boolean extends Property {
        valid(value) {
            return types_2.isBoolean(value);
        }
    }
    exports.Boolean = Boolean;
    Boolean.__name__ = "Boolean";
    /** @deprecated */
    class Color extends Property {
        valid(value) {
            return color_1.is_Color(value);
        }
    }
    exports.Color = Color;
    Color.__name__ = "Color";
    /** @deprecated */
    class Instance extends Property {
    }
    exports.Instance = Instance;
    Instance.__name__ = "Instance";
    /** @deprecated */
    class Number extends Property {
        valid(value) {
            return types_2.isNumber(value);
        }
    }
    exports.Number = Number;
    Number.__name__ = "Number";
    /** @deprecated */
    class Int extends Number {
        valid(value) {
            return types_2.isNumber(value) && (value | 0) == value;
        }
    }
    exports.Int = Int;
    Int.__name__ = "Int";
    /** @deprecated */
    class Angle extends Number {
    }
    exports.Angle = Angle;
    Angle.__name__ = "Angle";
    /** @deprecated */
    class Percent extends Number {
        valid(value) {
            return types_2.isNumber(value) && 0 <= value && value <= 1.0;
        }
    }
    exports.Percent = Percent;
    Percent.__name__ = "Percent";
    /** @deprecated */
    class String extends Property {
        valid(value) {
            return types_2.isString(value);
        }
    }
    exports.String = String;
    String.__name__ = "String";
    /** @deprecated */
    class NullString extends Property {
        valid(value) {
            return value === null || types_2.isString(value);
        }
    }
    exports.NullString = NullString;
    NullString.__name__ = "NullString";
    /** @deprecated */
    class FontSize extends String {
    }
    exports.FontSize = FontSize;
    FontSize.__name__ = "FontSize";
    /** @deprecated */
    class Font extends String {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : undefined;
        }
    }
    exports.Font = Font;
    Font.__name__ = "Font";
    //
    // Enum properties
    //
    /** @deprecated */
    class EnumProperty extends Property {
        valid(value) {
            return types_2.isString(value) && array_1.includes(this.enum_values, value);
        }
    }
    exports.EnumProperty = EnumProperty;
    EnumProperty.__name__ = "EnumProperty";
    /** @deprecated */
    function Enum(values) {
        return class extends EnumProperty {
            get enum_values() {
                return [...values];
            }
        };
    }
    exports.Enum = Enum;
    class Direction extends EnumProperty {
        get enum_values() {
            return [...enums.Direction];
        }
        normalize(values) {
            const result = new Uint8Array(values.length);
            for (let i = 0; i < values.length; i++) {
                switch (values[i]) {
                    case "clock":
                        result[i] = 0;
                        break;
                    case "anticlock":
                        result[i] = 1;
                        break;
                }
            }
            return result;
        }
    }
    exports.Direction = Direction;
    Direction.__name__ = "Direction";
    /** @deprecated */ exports.Anchor = Enum(enums.Anchor);
    /** @deprecated */ exports.AngleUnits = Enum(enums.AngleUnits);
    /** @deprecated */ exports.BoxOrigin = Enum(enums.BoxOrigin);
    /** @deprecated */ exports.ButtonType = Enum(enums.ButtonType);
    /** @deprecated */ exports.CalendarPosition = Enum(enums.CalendarPosition);
    /** @deprecated */ exports.Dimension = Enum(enums.Dimension);
    /** @deprecated */ exports.Dimensions = Enum(enums.Dimensions);
    /** @deprecated */ exports.Distribution = Enum(enums.Distribution);
    /** @deprecated */ exports.FontStyle = Enum(enums.FontStyle);
    /** @deprecated */ exports.HatchPatternType = Enum(enums.HatchPatternType);
    /** @deprecated */ exports.HTTPMethod = Enum(enums.HTTPMethod);
    /** @deprecated */ exports.HexTileOrientation = Enum(enums.HexTileOrientation);
    /** @deprecated */ exports.HoverMode = Enum(enums.HoverMode);
    /** @deprecated */ exports.LatLon = Enum(enums.LatLon);
    /** @deprecated */ exports.LegendClickPolicy = Enum(enums.LegendClickPolicy);
    /** @deprecated */ exports.LegendLocation = Enum(enums.LegendLocation);
    /** @deprecated */ exports.LineCap = Enum(enums.LineCap);
    /** @deprecated */ exports.LineJoin = Enum(enums.LineJoin);
    /** @deprecated */ exports.LinePolicy = Enum(enums.LinePolicy);
    /** @deprecated */ exports.Location = Enum(enums.Location);
    /** @deprecated */ exports.Logo = Enum(enums.Logo);
    /** @deprecated */ exports.MarkerType = Enum(enums.MarkerType);
    /** @deprecated */ exports.MutedPolicy = Enum(enums.MutedPolicy);
    /** @deprecated */ exports.Orientation = Enum(enums.Orientation);
    /** @deprecated */ exports.OutputBackend = Enum(enums.OutputBackend);
    /** @deprecated */ exports.PaddingUnits = Enum(enums.PaddingUnits);
    /** @deprecated */ exports.Place = Enum(enums.Place);
    /** @deprecated */ exports.PointPolicy = Enum(enums.PointPolicy);
    /** @deprecated */ exports.RadiusDimension = Enum(enums.RadiusDimension);
    /** @deprecated */ exports.RenderLevel = Enum(enums.RenderLevel);
    /** @deprecated */ exports.RenderMode = Enum(enums.RenderMode);
    /** @deprecated */ exports.ResetPolicy = Enum(enums.ResetPolicy);
    /** @deprecated */ exports.RoundingFunction = Enum(enums.RoundingFunction);
    /** @deprecated */ exports.Side = Enum(enums.Side);
    /** @deprecated */ exports.SizingMode = Enum(enums.SizingMode);
    /** @deprecated */ exports.Sort = Enum(enums.Sort);
    /** @deprecated */ exports.SpatialUnits = Enum(enums.SpatialUnits);
    /** @deprecated */ exports.StartEnd = Enum(enums.StartEnd);
    /** @deprecated */ exports.StepMode = Enum(enums.StepMode);
    /** @deprecated */ exports.TapBehavior = Enum(enums.TapBehavior);
    /** @deprecated */ exports.TextAlign = Enum(enums.TextAlign);
    /** @deprecated */ exports.TextBaseline = Enum(enums.TextBaseline);
    /** @deprecated */ exports.TextureRepetition = Enum(enums.TextureRepetition);
    /** @deprecated */ exports.TickLabelOrientation = Enum(enums.TickLabelOrientation);
    /** @deprecated */ exports.TooltipAttachment = Enum(enums.TooltipAttachment);
    /** @deprecated */ exports.UpdateMode = Enum(enums.UpdateMode);
    /** @deprecated */ exports.VerticalAlign = Enum(enums.VerticalAlign);
    //
    // DataSpec properties
    //
    class ScalarSpec extends Property {
        get_value() {
            // XXX: denormalize value for serialization, because bokeh doens't support scalar properties
            const { value, expr, transform } = this.spec;
            return (expr != null || transform != null ? this.spec : value);
            // XXX: allow obj.x = null; obj.x == null
            // return this.spec.value === null ? null : this.spec as any
        }
        _update(attr_value) {
            if (isSpec(attr_value))
                this.spec = attr_value;
            else
                this.spec = { value: attr_value };
            if (this.spec.value != null)
                this.validate(this.spec.value);
        }
        materialize(value) {
            return value;
        }
        scalar(value, n) {
            return new uniforms_1.UniformScalar(value, n);
        }
        uniform(source) {
            var _a;
            const { expr, value, transform } = this.spec;
            const n = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            if (expr != null) {
                let result = expr.compute(source);
                if (transform != null)
                    result = transform.compute(result);
                result = this.materialize(result);
                return this.scalar(result, n);
            }
            else {
                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" : undefined;
        }
    }
    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 {
        get_value() {
            // XXX: allow obj.x = null; obj.x == null
            return this.spec.value === null ? null : this.spec;
        }
        _update(attr_value) {
            if (isSpec(attr_value))
                this.spec = attr_value;
            else
                this.spec = { value: attr_value };
            if (this.spec.value != null)
                this.validate(this.spec.value);
        }
        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 { field, expr, value, transform } = this.spec;
            const n = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            if (field != null) {
                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 (expr != null) {
                let array = expr.v_compute(source);
                if (transform != null)
                    array = transform.v_compute(array);
                array = this.v_materialize(array);
                return this.vector(array);
            }
            else {
                let result = value;
                if (transform != null)
                    result = transform.compute(result);
                result = this.materialize(result);
                return this.scalar(result, n);
            }
        }
        array(source) {
            var _a;
            let array;
            const length = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            if (this.spec.field != null) {
                const column = source.get_column(this.spec.field);
                if (column != null)
                    array = this.normalize(column);
                else {
                    logging_1.logger.warn(`attempted to retrieve property array for nonexistent field '${this.spec.field}'`);
                    const missing = new Float64Array(length);
                    missing.fill(NaN);
                    array = missing;
                }
            }
            else if (this.spec.expr != null) {
                array = this.normalize(this.spec.expr.v_compute(source));
            }
            else {
                const value = this._value(false); // don't apply any spec transform
                if (types_2.isNumber(value)) {
                    const values = new Float64Array(length);
                    values.fill(value);
                    array = values;
                }
                else
                    array = array_1.repeat(value, length);
            }
            if (this.spec.transform != null)
                array = this.spec.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 {
        _update(attr_value) {
            super._update(attr_value);
            const { units } = this.spec;
            if (units != null && !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 (_a = this.spec.units) !== null && _a !== void 0 ? _a : this.default_units;
        }
        set units(units) {
            if (units != this.default_units)
                this.spec.units = units;
            else
                delete this.spec.units;
        }
    }
    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 = -math_1.to_radians_coeff(this.units);
            return value * coeff;
        }
        v_materialize(values) {
            const coeff = -math_1.to_radians_coeff(this.units);
            const result = new Float32Array(values.length);
            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 ScreenDistanceSpec extends DistanceSpec {
        get default_units() { return "screen"; }
    }
    exports.ScreenDistanceSpec = ScreenDistanceSpec;
    ScreenDistanceSpec.__name__ = "ScreenDistanceSpec";
    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 NumberSpec extends DataSpec {
        v_materialize(values) {
            return types_2.isTypedArray(values) ? values : new Float64Array(values);
        }
        array(source) {
            return new Float64Array(super.array(source));
        }
    }
    exports.NumberSpec = NumberSpec;
    NumberSpec.__name__ = "NumberSpec";
    class ColorSpec extends DataSpec {
        materialize(color) {
            return color_1.encode_rgba(color_1.color2rgba(color));
        }
        v_materialize(colors) {
            if (ndarray_1.is_NDArray(colors)) {
                if (colors.dtype == "uint32" && colors.dimension == 1) {
                    return 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 {
                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] = color_1.color2rgba(color);
                    array[j++] = r;
                    array[j++] = g;
                    array[j++] = b;
                    array[j++] = a;
                }
                return new types_1.ColorArray(array.buffer);
            }
            throw new Error("invalid color array");
        }
        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" : undefined;
        }
    }
    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(13) /* ./util/object */;
    const _loggers = {};
    class LogLevel {
        constructor(name, level) {
            this.name = name;
            this.level = level;
        }
    }
    exports.LogLevel = LogLevel;
    LogLevel.__name__ = "LogLevel";
    class Logger {
        constructor(name, level = Logger.INFO) {
            this._name = name;
            this.set_level(level);
        }
        static get levels() {
            return Object.keys(Logger.log_levels);
        }
        static get(name, level = Logger.INFO) {
            if (name.length > 0) {
                let logger = _loggers[name];
                if (logger == null)
                    _loggers[name] = logger = new Logger(name, level);
                return logger;
            }
            else
                throw new TypeError("Logger.get() expects a non-empty string name and an optional log-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 (types_1.isString(log_level) && Logger.log_levels[log_level] != null)
                this._log_level = Logger.log_levels[log_level];
            else
                throw new Error("Logger.set_level() expects a log-level object or a string name of a log-level");
            const logger_name = `[${this._name}]`;
            for (const [name, log_level] of 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 if (console.log != null)
            return console.log.bind(console, logger_name);
        else
            return function () { };
    }
    exports.logger = Logger.get("bokeh");
    function set_log_level(level) {
        const previous_level = exports.logger.level;
        if (types_1.isString(level) && Logger.log_levels[level] == null) {
            console.log(`[bokeh] unrecognized logging level '${level}' passed to Bokeh.set_log_level(), ignoring`);
            console.log(`[bokeh] valid log levels are: ${Logger.levels.join(', ')}`);
        }
        else {
            console.log(`[bokeh] setting log level to: '${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.VerticalAlign = void 0;
    const kinds_1 = require(21) /* ./kinds */;
    exports.Align = kinds_1.Enum("start", "center", "end");
    exports.Anchor = 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 = kinds_1.Enum("deg", "rad", "grad", "turn");
    exports.BoxOrigin = kinds_1.Enum("corner", "center");
    exports.ButtonType = kinds_1.Enum("default", "primary", "success", "warning", "danger", "light");
    exports.CalendarPosition = kinds_1.Enum("auto", "above", "below");
    exports.Dimension = kinds_1.Enum("width", "height");
    exports.Dimensions = kinds_1.Enum("width", "height", "both");
    exports.Direction = kinds_1.Enum("clock", "anticlock");
    exports.Distribution = kinds_1.Enum("uniform", "normal");
    exports.FontStyle = kinds_1.Enum("normal", "italic", "bold", "bold italic");
    exports.HatchPatternType = 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 = kinds_1.Enum("POST", "GET");
    exports.HexTileOrientation = kinds_1.Enum("pointytop", "flattop");
    exports.HoverMode = kinds_1.Enum("mouse", "hline", "vline");
    exports.LatLon = kinds_1.Enum("lat", "lon");
    exports.LegendClickPolicy = kinds_1.Enum("none", "hide", "mute");
    exports.LegendLocation = exports.Anchor;
    exports.LineCap = kinds_1.Enum("butt", "round", "square");
    exports.LineJoin = kinds_1.Enum("miter", "round", "bevel");
    exports.LineDash = kinds_1.Enum("solid", "dashed", "dotted", "dotdash", "dashdot");
    exports.LinePolicy = kinds_1.Enum("prev", "next", "nearest", "interp", "none");
    exports.Location = kinds_1.Enum("above", "below", "left", "right");
    exports.Logo = kinds_1.Enum("normal", "grey");
    exports.MarkerType = 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 = kinds_1.Enum("show", "ignore");
    exports.Orientation = kinds_1.Enum("vertical", "horizontal");
    exports.OutputBackend = kinds_1.Enum("canvas", "svg", "webgl");
    exports.PaddingUnits = kinds_1.Enum("percent", "absolute");
    exports.Place = kinds_1.Enum("above", "below", "left", "right", "center");
    exports.PointPolicy = kinds_1.Enum("snap_to_data", "follow_mouse", "none");
    exports.RadiusDimension = kinds_1.Enum("x", "y", "max", "min");
    exports.RenderLevel = kinds_1.Enum("image", "underlay", "glyph", "guide", "annotation", "overlay");
    exports.RenderMode = kinds_1.Enum("canvas", "css");
    exports.ResetPolicy = kinds_1.Enum("standard", "event_only");
    exports.RoundingFunction = kinds_1.Enum("round", "nearest", "floor", "rounddown", "ceil", "roundup");
    exports.SelectionMode = kinds_1.Enum("replace", "append", "intersect", "subtract");
    exports.Side = kinds_1.Enum("above", "below", "left", "right");
    exports.SizingMode = kinds_1.Enum("stretch_width", "stretch_height", "stretch_both", "scale_width", "scale_height", "scale_both", "fixed");
    exports.Sort = kinds_1.Enum("ascending", "descending");
    exports.SpatialUnits = kinds_1.Enum("screen", "data");
    exports.StartEnd = kinds_1.Enum("start", "end");
    exports.StepMode = kinds_1.Enum("after", "before", "center");
    exports.TapBehavior = kinds_1.Enum("select", "inspect");
    exports.TextAlign = kinds_1.Enum("left", "right", "center");
    exports.TextBaseline = kinds_1.Enum("top", "middle", "bottom", "alphabetic", "hanging", "ideographic");
    exports.TextureRepetition = kinds_1.Enum("repeat", "repeat_x", "repeat_y", "no_repeat");
    exports.TickLabelOrientation = kinds_1.Enum("vertical", "horizontal", "parallel", "normal");
    exports.TooltipAttachment = kinds_1.Enum("horizontal", "vertical", "left", "right", "above", "below");
    exports.UpdateMode = kinds_1.Enum("replace", "append");
    exports.VerticalAlign = kinds_1.Enum("top", "middle", "bottom");
},
/* 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(13) /* ./util/object */;
    const ESMap = window.Map;
    const { hasOwnProperty } = Object.prototype;
    class Kind {
    }
    exports.Kind = Kind;
    Kind.__name__ = "Kind";
    (function (Kinds) {
        class Any extends Kind {
            valid(_value) {
                return true;
            }
        }
        Any.__name__ = "Any";
        Kinds.Any = Any;
        class Unknown extends Kind {
            valid(_value) {
                return true;
            }
        }
        Unknown.__name__ = "Unknown";
        Kinds.Unknown = Unknown;
        class Boolean extends Kind {
            valid(value) {
                return tp.isBoolean(value);
            }
        }
        Boolean.__name__ = "Boolean";
        Kinds.Boolean = Boolean;
        class Ref extends Kind {
            constructor(obj_type) {
                super();
                this.obj_type = obj_type;
            }
            valid(_value) {
                // XXX: disable validation for now, because object graph initialization depends on this.
                // return value instanceof this.obj_type
                return true;
            }
        }
        Ref.__name__ = "Ref";
        Kinds.Ref = Ref;
        class AnyRef extends Kind {
            valid(_value) {
                // XXX: disable validation for now, because object graph initialization depends on this.
                // return tp.isObject(value)
                return true;
            }
        }
        AnyRef.__name__ = "AnyRef";
        Kinds.AnyRef = AnyRef;
        class Number extends Kind {
            valid(value) {
                return tp.isNumber(value);
            }
        }
        Number.__name__ = "Number";
        Kinds.Number = Number;
        class Int extends Number {
            valid(value) {
                return super.valid(value) && tp.isInteger(value);
            }
        }
        Int.__name__ = "Int";
        Kinds.Int = Int;
        class Percent extends Number {
            valid(value) {
                return super.valid(value) && 0 <= value && value <= 1;
            }
        }
        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));
            }
        }
        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;
            }
        }
        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;
                if (object_1.size(struct_type) != object_1.size(value))
                    return false;
                for (const key in struct_type) {
                    if (hasOwnProperty.call(struct_type, key)) {
                        if (!hasOwnProperty.call(value, key))
                            return false;
                        const item_type = struct_type[key];
                        const item = value[key];
                        if (!item_type.valid(item))
                            return false;
                    }
                }
                return true;
            }
        }
        Struct.__name__ = "Struct";
        Kinds.Struct = Struct;
        class Arrayable extends Kind {
            valid(value) {
                return tp.isArray(value) || tp.isTypedArray(value); // TODO: too specific
            }
        }
        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));
            }
        }
        Array.__name__ = "Array";
        Kinds.Array = Array;
        class Null extends Kind {
            valid(value) {
                return value === 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);
            }
        }
        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);
            }
        }
        Opt.__name__ = "Opt";
        Kinds.Opt = Opt;
        class String extends Kind {
            valid(value) {
                return tp.isString(value);
            }
        }
        String.__name__ = "String";
        Kinds.String = String;
        class Enum extends Kind {
            constructor(values) {
                super();
                this.values = new Set(values);
            }
            valid(value) {
                return this.values.has(value);
            }
            *[Symbol.iterator]() {
                yield* this.values;
            }
        }
        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;
            }
        }
        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;
            }
        }
        Map.__name__ = "Map";
        Kinds.Map = Map;
        class Color extends Kind {
            valid(value) {
                return color_1.is_Color(value);
            }
        }
        Color.__name__ = "Color";
        Kinds.Color = Color;
        class Function extends Kind {
            valid(value) {
                return tp.isFunction(value);
            }
        }
        Function.__name__ = "Function";
        Kinds.Function = Function;
    })(exports.Kinds || (exports.Kinds = {}));
    exports.Any = new exports.Kinds.Any();
    exports.Unknown = new exports.Kinds.Unknown();
    exports.Boolean = new exports.Kinds.Boolean();
    exports.Number = new exports.Kinds.Number();
    exports.Int = new exports.Kinds.Int();
    exports.String = new exports.Kinds.String();
    exports.Null = new exports.Kinds.Null();
    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;
    exports.Arrayable = new exports.Kinds.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 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.Percent = new exports.Kinds.Percent();
    exports.Alpha = exports.Percent;
    exports.Color = new exports.Kinds.Color();
    exports.Auto = exports.Enum("auto");
    exports.FontSize = exports.String;
    exports.Font = exports.String;
    exports.Angle = exports.Number;
},
/* core/util/color.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const svg_colors_1 = require(23) /* ./svg_colors */;
    const math_1 = require(10) /* ./math */;
    const types_1 = require(8) /* ./types */;
    const { round } = Math;
    function byte(v) {
        return math_1.clamp(round(v), 0, 255);
    }
    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 compose_alpha(color, alpha) {
        if ((color & 0xff) == 255)
            return (color & 0xffffff00) | byte(alpha * 255);
        else
            return color;
    }
    exports.compose_alpha = compose_alpha;
    function color2rgba(color, alpha) {
        var _a;
        let r, g, b, a;
        if (color == null)
            [r, g, b, a] = transparent();
        else if (types_1.isInteger(color))
            [r, g, b, a] = decode_rgba(color);
        else if (types_1.isString(color))
            [r, g, b, a] = (_a = css4_parse(color)) !== null && _a !== void 0 ? _a : transparent();
        else {
            [r, g, b, a = 1.0] = color;
            a = byte(a * 255);
        }
        if (a == 255 && alpha != null)
            a = byte(alpha * 255);
        return [r, g, b, 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;
    /*
    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*([^\s,]+?)\s+([^\s,]+?)\s+([^\s,]+?)(?:\s*\/\s*([^\s,]+?))?\s*\)$/;
    const rgb_legacy = /^rgba?\(\s*([^\s,]+?)\s*,\s*([^\s,]+?)\s*,\s*([^\s,]+?)(?:\s*,\s*([^\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 (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.substr(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) {
                let [, r, g, b, a = "1"] = result; // XXX: use groups when IE is dropped
                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 (types_1.isInteger(value))
            return true;
        if (types_1.isString(value) && css4_parse(value) != null)
            return true;
        if (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;
},
/* 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();
    exports.GeneratorFunction = Object.getPrototypeOf(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 new Float32Array(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) {
    __esModule();
    const eq_1 = require(26) /* ./eq */;
    const assert_1 = require(11) /* ./assert */;
    class BitSet {
        constructor(size, init = 0) {
            this.size = size;
            this[Symbol.toStringTag] = "BitSet";
            this._count = null;
            this._nwords = Math.ceil(size / 32);
            if (init == 0 || init == 1) {
                this._array = new Uint32Array(this._nwords);
                if (init == 1) {
                    this._array.fill(0xffffffff);
                }
            }
            else {
                assert_1.assert(init.length == this._nwords, "Initializer size mismatch");
                this._array = init;
            }
        }
        clone() {
            return new BitSet(this.size, new Uint32Array(this._array));
        }
        [eq_1.equals](that, cmp) {
            if (!cmp.eq(this.size, that.size))
                return false;
            const { _nwords } = this;
            const trailing = this.size % _nwords;
            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);
            const n = Math.min(size, booleans.length);
            for (let i = 0; i < n; i++) {
                if (booleans[i])
                    bits.set(i);
            }
            return bits;
        }
        _check_bounds(k) {
            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) & 0x1);
        }
        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] |= 0x1 << j;
            else
                this._array[i] &= ~(0x1 << 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 += 32;
                }
                else {
                    for (let j = 0; j < 32 && k < size; j++, k++) {
                        if ((word >>> j) & 0x1)
                            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 += 32;
                    continue;
                }
                for (let j = 0; j < 32 && k < size; j++, k++) {
                    if ((word >>> j) & 0x1)
                        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 += 32;
                    continue;
                }
                for (let j = 0; j < 32 && k < size; j++, k++) {
                    if (!((word >>> j) & 0x1))
                        yield k;
                }
            }
        }
        _check_size(other) {
            assert_1.assert(this.size == other.size, "Size mismatch");
        }
        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;
            }
        }
        union(other) {
            this._check_size(other);
            const result = this.clone();
            for (let i = 0; i < this._nwords; i++) {
                result._array[i] |= other._array[i];
            }
            return result;
        }
        intersection(other) {
            this._check_size(other);
            const result = this.clone();
            for (let i = 0; i < this._nwords; i++) {
                result._array[i] &= other._array[i];
            }
            return result;
        }
        difference(other) {
            this._check_size(other);
            const result = this.clone();
            for (let i = 0; i < this._nwords; i++) {
                const a = this._array[i];
                const b = other._array[i];
                result._array[i] = (a ^ b) & a;
            }
            return result;
        }
        select(array) {
            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";
},
/* 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 types_1.isObject(obj) && obj[exports.equals] !== undefined;
    }
    exports.wildcard = Symbol("wildcard");
    const toString = Object.prototype.toString;
    class Comparator {
        constructor() {
            this.a_stack = [];
            this.b_stack = [];
        }
        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 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--) {
                // 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 (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) {
            const ai = a[Symbol.iterator]();
            const bi = b[Symbol.iterator]();
            while (true) {
                const an = ai.next();
                const bn = bi.next();
                if (an.done && bn.done)
                    return true;
                if (an.done || bn.done)
                    return false;
                if (!this.eq(an.value, bn.value))
                    return false;
            }
        }
        maps(a, b) {
            if (a.size != b.size)
                return false;
            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;
            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_similar(a, b, tolerance) {
        const comparator = new SimilarComparator(tolerance);
        return comparator.eq(a, b);
    }
    exports.is_similar = is_similar;
    /** @deprecated */
    exports.isEqual = is_equal;
},
/* core/util/platform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_windows = (() => {
        return navigator.appVersion.includes("Windows");
    })();
    exports.is_ie = (() => {
        const ua = navigator.userAgent;
        return ua.includes("MSIE") || ua.includes("Trident") || ua.includes("Edge");
    })();
    exports.is_mobile = (() => {
        return typeof window !== "undefined" && ("ontouchstart" in window || 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/settings.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class Settings {
        constructor() {
            this._dev = false;
            this._wireframe = false;
        }
        set dev(dev) {
            this._dev = dev;
        }
        get dev() {
            return this._dev;
        }
        set wireframe(wireframe) {
            this._wireframe = wireframe;
        }
        get wireframe() {
            return this._wireframe;
        }
    }
    exports.Settings = Settings;
    Settings.__name__ = "Settings";
    exports.settings = new Settings();
},
/* core/util/ndarray.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const types_1 = require(8) /* ./types */;
    const assert_1 = require(11) /* ./assert */;
    const eq_1 = require(26) /* ./eq */;
    const serializer_1 = require(30) /* ../serializer */;
    const serialization_1 = require(31) /* ./serialization */;
    const __ndarray__ = Symbol("__ndarray__");
    class Uint8NDArray extends Uint8Array {
        constructor(seq, shape) {
            super(seq);
            this[_a] = true;
            this.dtype = "uint8";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_a = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [serializer_1.serialize](_serializer) {
            return serialization_1.encode_NDArray(this);
        }
    }
    exports.Uint8NDArray = Uint8NDArray;
    Uint8NDArray.__name__ = "Uint8NDArray";
    class Int8NDArray extends Int8Array {
        constructor(seq, shape) {
            super(seq);
            this[_b] = true;
            this.dtype = "int8";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_b = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [serializer_1.serialize](_serializer) {
            return serialization_1.encode_NDArray(this);
        }
    }
    exports.Int8NDArray = Int8NDArray;
    Int8NDArray.__name__ = "Int8NDArray";
    class Uint16NDArray extends Uint16Array {
        constructor(seq, shape) {
            super(seq);
            this[_c] = true;
            this.dtype = "uint16";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_c = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [serializer_1.serialize](_serializer) {
            return serialization_1.encode_NDArray(this);
        }
    }
    exports.Uint16NDArray = Uint16NDArray;
    Uint16NDArray.__name__ = "Uint16NDArray";
    class Int16NDArray extends Int16Array {
        constructor(seq, shape) {
            super(seq);
            this[_d] = true;
            this.dtype = "int16";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_d = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [serializer_1.serialize](_serializer) {
            return serialization_1.encode_NDArray(this);
        }
    }
    exports.Int16NDArray = Int16NDArray;
    Int16NDArray.__name__ = "Int16NDArray";
    class Uint32NDArray extends Uint32Array {
        constructor(seq, shape) {
            super(seq);
            this[_e] = true;
            this.dtype = "uint32";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_e = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [serializer_1.serialize](_serializer) {
            return serialization_1.encode_NDArray(this);
        }
    }
    exports.Uint32NDArray = Uint32NDArray;
    Uint32NDArray.__name__ = "Uint32NDArray";
    class Int32NDArray extends Int32Array {
        constructor(seq, shape) {
            super(seq);
            this[_f] = true;
            this.dtype = "int32";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_f = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [serializer_1.serialize](_serializer) {
            return serialization_1.encode_NDArray(this);
        }
    }
    exports.Int32NDArray = Int32NDArray;
    Int32NDArray.__name__ = "Int32NDArray";
    class Float32NDArray extends Float32Array {
        constructor(seq, shape) {
            super(seq);
            this[_g] = true;
            this.dtype = "float32";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_g = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [serializer_1.serialize](_serializer) {
            return serialization_1.encode_NDArray(this);
        }
    }
    exports.Float32NDArray = Float32NDArray;
    Float32NDArray.__name__ = "Float32NDArray";
    class Float64NDArray extends Float64Array {
        constructor(seq, shape) {
            super(seq);
            this[_h] = true;
            this.dtype = "float64";
            this.shape = shape !== null && shape !== void 0 ? shape : (is_NDArray(seq) ? seq.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_h = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [serializer_1.serialize](_serializer) {
            return serialization_1.encode_NDArray(this);
        }
    }
    exports.Float64NDArray = Float64NDArray;
    Float64NDArray.__name__ = "Float64NDArray";
    function is_NDArray(v) {
        return types_1.isObject(v) && v[__ndarray__] !== undefined;
    }
    exports.is_NDArray = is_NDArray;
    function ndarray(array, options = {}) {
        let { dtype } = options;
        if (dtype == null) {
            if (array instanceof ArrayBuffer || types_1.isArray(array)) {
                dtype = "float64";
            }
            else {
                dtype = (() => {
                    switch (true) {
                        case array instanceof Uint8Array: return "uint8";
                        case array instanceof Int8Array: return "int8";
                        case array instanceof Uint16Array: return "uint16";
                        case array instanceof Int16Array: return "int16";
                        case array instanceof Uint32Array: return "uint32";
                        case array instanceof Int32Array: return "int32";
                        case array instanceof Float32Array: return "float32";
                        case array instanceof Float64Array: return "float64";
                        default:
                            assert_1.unreachable();
                    }
                })();
            }
        }
        const { shape } = options;
        switch (dtype) {
            case "uint8": return new Uint8NDArray(array, shape);
            case "int8": return new Int8NDArray(array, shape);
            case "uint16": return new Uint16NDArray(array, shape);
            case "int16": return new Int16NDArray(array, shape);
            case "uint32": return new Uint32NDArray(array, shape);
            case "int32": return new Int32NDArray(array, shape);
            case "float32": return new Float32NDArray(array, shape);
            case "float64": return new Float64NDArray(array, shape);
        }
    }
    exports.ndarray = ndarray;
},
/* core/serializer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const assert_1 = require(11) /* ./util/assert */;
    const object_1 = require(13) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    //| Map<SerializableType, SerializableType>
    //| Set<SerializableType>
    //| ArrayBuffer
    // TypedArray?
    exports.serialize = Symbol("serialize");
    function is_Serializable(obj) {
        return types_1.isObject(obj) && obj[exports.serialize] !== undefined;
    }
    class SerializationError extends Error {
    }
    exports.SerializationError = SerializationError;
    SerializationError.__name__ = "SerializationError";
    class Serializer {
        constructor(options) {
            var _a;
            this._references = new Map();
            this._definitions = new Map();
            this._refmap = new Map();
            this.include_defaults = (_a = options === null || options === void 0 ? void 0 : options.include_defaults) !== null && _a !== void 0 ? _a : true;
        }
        get_ref(obj) {
            return this._references.get(obj);
        }
        add_ref(obj, ref) {
            assert_1.assert(!this._references.has(obj));
            this._references.set(obj, ref);
        }
        add_def(obj, def) {
            const ref = this.get_ref(obj);
            assert_1.assert(ref != null);
            this._definitions.set(obj, def);
            this._refmap.set(ref, def);
        }
        get objects() {
            return new Set(this._references.keys());
        }
        get references() {
            return new Set(this._references.values());
        }
        get definitions() {
            return new Set(this._definitions.values());
        }
        resolve_ref(ref) {
            return this._refmap.get(ref);
        }
        remove_ref(obj) {
            return this._references.delete(obj);
        }
        remove_def(obj) {
            return this._definitions.delete(obj);
        }
        to_serializable(obj) {
            const ref = this.get_ref(obj);
            if (ref != null)
                return ref;
            else if (is_Serializable(obj))
                return obj[exports.serialize](this);
            else if (types_1.isArray(obj) || types_1.isTypedArray(obj)) {
                const n = obj.length;
                const result = new Array(n);
                for (let i = 0; i < n; i++) {
                    const value = obj[i];
                    result[i] = this.to_serializable(value);
                }
                return result;
            }
            else if (types_1.isPlainObject(obj)) {
                const result = {};
                for (const [key, value] of object_1.entries(obj)) {
                    result[key] = this.to_serializable(value);
                }
                return result;
            }
            else if (obj === null || types_1.isBoolean(obj) || types_1.isNumber(obj) || types_1.isString(obj)) {
                return obj;
            }
            else
                throw new SerializationError(`${Object.prototype.toString.call(obj)} is not serializable`);
        }
    }
    exports.Serializer = Serializer;
    Serializer.__name__ = "Serializer";
},
/* core/util/serialization.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const types_1 = require(8) /* ./types */;
    const ndarray = tslib_1.__importStar(require(29) /* ./ndarray */);
    const platform_1 = require(27) /* ./platform */;
    const buffer_1 = require(32) /* ./buffer */;
    function is_NDArray_ref(v) {
        return types_1.isPlainObject(v) && ("__buffer__" in v || "__ndarray__" in v);
    }
    exports.is_NDArray_ref = is_NDArray_ref;
    function decode_NDArray(ref, buffers) {
        const { shape, dtype, order } = ref;
        let bytes;
        if ("__buffer__" in ref) {
            const buffer = buffers.get(ref.__buffer__);
            if (buffer != null)
                bytes = buffer;
            else
                throw new Error(`buffer for ${ref.__buffer__} not found`);
        }
        else {
            bytes = buffer_1.base64_to_buffer(ref.__ndarray__);
        }
        const array = (() => {
            switch (dtype) {
                case "uint8": return new ndarray.Uint8NDArray(bytes, shape);
                case "int8": return new ndarray.Int8NDArray(bytes, shape);
                case "uint16": return new ndarray.Uint16NDArray(bytes, shape);
                case "int16": return new ndarray.Int16NDArray(bytes, shape);
                case "uint32": return new ndarray.Uint32NDArray(bytes, shape);
                case "int32": return new ndarray.Int32NDArray(bytes, shape);
                case "float32": return new ndarray.Float32NDArray(bytes, shape);
                case "float64": return new ndarray.Float64NDArray(bytes, shape);
            }
        })();
        if (order !== platform_1.BYTE_ORDER) {
            buffer_1.swap(array);
        }
        return array;
    }
    exports.decode_NDArray = decode_NDArray;
    function encode_NDArray(array, buffers) {
        const data = {
            order: platform_1.BYTE_ORDER,
            dtype: array.dtype,
            shape: array.shape,
        };
        if (buffers != null) {
            const __buffer__ = `${buffers.size}`;
            buffers.set(__buffer__, array.buffer);
            return Object.assign({ __buffer__ }, data);
        }
        else {
            const __ndarray__ = buffer_1.buffer_to_base64(array.buffer);
            return Object.assign({ __ndarray__ }, data);
        }
    }
    exports.encode_NDArray = encode_NDArray;
},
/* 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;
    function swap16(a) {
        const x = new Uint8Array(a.buffer, a.byteOffset, a.length * 2);
        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(a) {
        const x = new Uint8Array(a.buffer, a.byteOffset, a.length * 4);
        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(a) {
        const x = new Uint8Array(a.buffer, a.byteOffset, a.length * 8);
        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(array) {
        switch (array.BYTES_PER_ELEMENT) {
            case 2:
                swap16(array);
                break;
            case 4:
                swap32(array);
                break;
            case 8:
                swap64(array);
                break;
        }
    }
    exports.swap = swap;
},
/* core/uniforms.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(26) /* ./util/eq */;
    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.value = value;
            this.length = length;
            this.is_scalar = true;
        }
        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.array = array;
            this.is_scalar = false;
            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";
},
/* core/util/string.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const settings_1 = require(28) /* ../settings */;
    function startsWith(str, searchString, position = 0) {
        return str.substr(position, searchString.length) == searchString;
    }
    exports.startsWith = startsWith;
    function uuid4() {
        // from ipython project
        // http://www.ietf.org/rfc/rfc4122.txt
        const s = new Array(32);
        const hexDigits = "0123456789ABCDEF";
        for (let i = 0; i < 32; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[16] = hexDigits.substr((s[16].charCodeAt(0) & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        return s.join("");
    }
    exports.uuid4 = uuid4;
    let counter = 1000;
    function uniqueId(prefix) {
        const id = settings_1.settings.dev ? `j${counter++}` : uuid4();
        if (prefix != null)
            return `${prefix}-${id}`;
        else
            return id;
    }
    exports.uniqueId = uniqueId;
    function escape(s) {
        return s.replace(/(?:[&<>"'`])/g, (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;
},
/* document/events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const serializer_1 = require(30) /* ../core/serializer */;
    class DocumentEvent {
        constructor(document) {
            this.document = document;
        }
    }
    exports.DocumentEvent = DocumentEvent;
    DocumentEvent.__name__ = "DocumentEvent";
    class DocumentEventBatch extends DocumentEvent {
        constructor(document, events, setter_id) {
            super(document);
            this.events = events;
            this.setter_id = setter_id;
        }
    }
    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.msg_type = msg_type;
            this.msg_data = msg_data;
        }
        [serializer_1.serialize](serializer) {
            const value = this.msg_data;
            const value_serialized = serializer.to_serializable(value);
            return {
                kind: "MessageSent",
                msg_type: this.msg_type,
                msg_data: value_serialized,
            };
        }
    }
    exports.MessageSentEvent = MessageSentEvent;
    MessageSentEvent.__name__ = "MessageSentEvent";
    class ModelChangedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, old, new_, setter_id, hint) {
            super(document);
            this.model = model;
            this.attr = attr;
            this.old = old;
            this.new_ = new_;
            this.setter_id = setter_id;
            this.hint = hint;
        }
        [serializer_1.serialize](serializer) {
            if (this.hint != null)
                return serializer.to_serializable(this.hint);
            const value = this.new_;
            const value_serialized = serializer.to_serializable(value);
            if (this.model != value) {
                // we know we don't want a whole new copy of the obj we're
                // patching unless it's also the value itself
                serializer.remove_def(this.model);
            }
            return {
                kind: "ModelChanged",
                model: this.model.ref(),
                attr: this.attr,
                new: value_serialized,
            };
        }
    }
    exports.ModelChangedEvent = ModelChangedEvent;
    ModelChangedEvent.__name__ = "ModelChangedEvent";
    class ColumnsPatchedEvent extends DocumentChangedEvent {
        constructor(document, column_source, patches) {
            super(document);
            this.column_source = column_source;
            this.patches = patches;
        }
        [serializer_1.serialize](_serializer) {
            return {
                kind: "ColumnsPatched",
                column_source: this.column_source,
                patches: this.patches,
            };
        }
    }
    exports.ColumnsPatchedEvent = ColumnsPatchedEvent;
    ColumnsPatchedEvent.__name__ = "ColumnsPatchedEvent";
    class ColumnsStreamedEvent extends DocumentChangedEvent {
        constructor(document, column_source, data, rollover) {
            super(document);
            this.column_source = column_source;
            this.data = data;
            this.rollover = rollover;
        }
        [serializer_1.serialize](_serializer) {
            return {
                kind: "ColumnsStreamed",
                column_source: this.column_source,
                data: this.data,
                rollover: this.rollover,
            };
        }
    }
    exports.ColumnsStreamedEvent = ColumnsStreamedEvent;
    ColumnsStreamedEvent.__name__ = "ColumnsStreamedEvent";
    class TitleChangedEvent extends DocumentChangedEvent {
        constructor(document, title, setter_id) {
            super(document);
            this.title = title;
            this.setter_id = setter_id;
        }
        [serializer_1.serialize](_serializer) {
            return {
                kind: "TitleChanged",
                title: this.title,
            };
        }
    }
    exports.TitleChangedEvent = TitleChangedEvent;
    TitleChangedEvent.__name__ = "TitleChangedEvent";
    class RootAddedEvent extends DocumentChangedEvent {
        constructor(document, model, setter_id) {
            super(document);
            this.model = model;
            this.setter_id = setter_id;
        }
        [serializer_1.serialize](serializer) {
            return {
                kind: "RootAdded",
                model: serializer.to_serializable(this.model),
            };
        }
    }
    exports.RootAddedEvent = RootAddedEvent;
    RootAddedEvent.__name__ = "RootAddedEvent";
    class RootRemovedEvent extends DocumentChangedEvent {
        constructor(document, model, setter_id) {
            super(document);
            this.model = model;
            this.setter_id = setter_id;
        }
        [serializer_1.serialize](_serializer) {
            return {
                kind: "RootRemoved",
                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(13) /* ./object */;
    exports.pretty = Symbol("pretty");
    function is_Printable(obj) {
        return types_1.isObject(obj) && obj[exports.pretty] !== undefined;
    }
    class Printer {
        constructor(options) {
            this.precision = options === null || options === void 0 ? void 0 : options.precision;
        }
        to_string(obj) {
            if (is_Printable(obj))
                return obj[exports.pretty](this);
            else if (types_1.isBoolean(obj))
                return this.boolean(obj);
            else if (types_1.isNumber(obj))
                return this.number(obj);
            else if (types_1.isString(obj))
                return this.string(obj);
            else if (types_1.isArray(obj))
                return this.array(obj);
            else if (types_1.isIterable(obj))
                return this.iterable(obj);
            else if (types_1.isPlainObject(obj))
                return this.object(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) {
            return `"${val.replace(/'/g, "\\'")}"`; // lgtm [js/incomplete-sanitization]
        }
        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 object_1.entries(obj)) {
                items.push(`${key}${T(":")} ${this.to_string(val)}`);
            }
            return `${T("{")}${items.join(`${T(",")} `)}${T("}")}`;
        }
    }
    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/util/cloneable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const object_1 = require(13) /* ./object */;
    const types_1 = require(8) /* ./types */;
    //| Map<CloneableType, CloneableType>
    //| Set<CloneableType>
    exports.clone = Symbol("clone");
    function is_Cloneable(obj) {
        return types_1.isObject(obj) && obj[exports.clone] !== undefined;
    }
    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 (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 (types_1.isPlainObject(obj)) {
                const result = {};
                for (const [key, value] of object_1.entries(obj)) {
                    result[key] = this.clone(value);
                }
                return result;
            }
            else if (obj === null || types_1.isBoolean(obj) || types_1.isNumber(obj) || types_1.isString(obj)) {
                return obj;
            }
            else
                throw new CloningError(`${Object.prototype.toString.call(obj)} is not cloneable`);
        }
    }
    exports.Cloner = Cloner;
    Cloner.__name__ = "Cloner";
},
/* models/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(39) /* ./annotations */, exports);
    tslib_1.__exportStar(require(162) /* ./axes */, exports);
    tslib_1.__exportStar(require(257) /* ./callbacks */, exports);
    tslib_1.__exportStar(require(261) /* ./canvas */, exports);
    tslib_1.__exportStar(require(266) /* ./expressions */, exports);
    tslib_1.__exportStar(require(272) /* ./filters */, exports);
    tslib_1.__exportStar(require(205) /* ./formatters */, exports);
    tslib_1.__exportStar(require(277) /* ./glyphs */, exports);
    tslib_1.__exportStar(require(313) /* ./graphs */, exports);
    tslib_1.__exportStar(require(315) /* ./grids */, exports);
    tslib_1.__exportStar(require(317) /* ./layouts */, exports);
    tslib_1.__exportStar(require(209) /* ./mappers */, exports);
    tslib_1.__exportStar(require(147) /* ./transforms */, exports);
    tslib_1.__exportStar(require(330) /* ./plots */, exports);
    tslib_1.__exportStar(require(338) /* ./policies */, exports);
    tslib_1.__exportStar(require(220) /* ./ranges */, exports);
    tslib_1.__exportStar(require(339) /* ./renderers */, exports);
    tslib_1.__exportStar(require(217) /* ./scales */, exports);
    tslib_1.__exportStar(require(340) /* ./selections */, exports);
    tslib_1.__exportStar(require(341) /* ./sources */, exports);
    tslib_1.__exportStar(require(198) /* ./tickers */, exports);
    tslib_1.__exportStar(require(346) /* ./tiles */, exports);
    tslib_1.__exportStar(require(356) /* ./textures */, exports);
    tslib_1.__exportStar(require(360) /* ./tools */, exports);
},
/* models/annotations/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var annotation_1 = require(40) /* ./annotation */;
    __esExport("Annotation", annotation_1.Annotation);
    var arrow_1 = require(55) /* ./arrow */;
    __esExport("Arrow", arrow_1.Arrow);
    var arrow_head_1 = require(133) /* ./arrow_head */;
    __esExport("ArrowHead", arrow_head_1.ArrowHead);
    var arrow_head_2 = require(133) /* ./arrow_head */;
    __esExport("OpenHead", arrow_head_2.OpenHead);
    var arrow_head_3 = require(133) /* ./arrow_head */;
    __esExport("NormalHead", arrow_head_3.NormalHead);
    var arrow_head_4 = require(133) /* ./arrow_head */;
    __esExport("TeeHead", arrow_head_4.TeeHead);
    var arrow_head_5 = require(133) /* ./arrow_head */;
    __esExport("VeeHead", arrow_head_5.VeeHead);
    var band_1 = require(134) /* ./band */;
    __esExport("Band", band_1.Band);
    var box_annotation_1 = require(136) /* ./box_annotation */;
    __esExport("BoxAnnotation", box_annotation_1.BoxAnnotation);
    var color_bar_1 = require(137) /* ./color_bar */;
    __esExport("ColorBar", color_bar_1.ColorBar);
    var label_1 = require(226) /* ./label */;
    __esExport("Label", label_1.Label);
    var label_set_1 = require(227) /* ./label_set */;
    __esExport("LabelSet", label_set_1.LabelSet);
    var legend_1 = require(228) /* ./legend */;
    __esExport("Legend", legend_1.Legend);
    var legend_item_1 = require(229) /* ./legend_item */;
    __esExport("LegendItem", legend_item_1.LegendItem);
    var poly_annotation_1 = require(231) /* ./poly_annotation */;
    __esExport("PolyAnnotation", poly_annotation_1.PolyAnnotation);
    var slope_1 = require(232) /* ./slope */;
    __esExport("Slope", slope_1.Slope);
    var span_1 = require(233) /* ./span */;
    __esExport("Span", span_1.Span);
    var text_annotation_1 = require(139) /* ./text_annotation */;
    __esExport("TextAnnotation", text_annotation_1.TextAnnotation);
    var title_1 = require(138) /* ./title */;
    __esExport("Title", title_1.Title);
    var toolbar_panel_1 = require(234) /* ./toolbar_panel */;
    __esExport("ToolbarPanel", toolbar_panel_1.ToolbarPanel);
    var tooltip_1 = require(254) /* ./tooltip */;
    __esExport("Tooltip", tooltip_1.Tooltip);
    var whisker_1 = require(256) /* ./whisker */;
    __esExport("Whisker", whisker_1.Whisker);
},
/* models/annotations/annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const renderer_1 = require(41) /* ../renderers/renderer */;
    class AnnotationView extends renderer_1.RendererView {
        get_size() {
            if (this.model.visible) {
                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() {
            const state = super.serializable_state();
            return this.layout == null ? state : Object.assign(Object.assign({}, state), { bbox: this.layout.bbox.box });
        }
    }
    exports.AnnotationView = AnnotationView;
    AnnotationView.__name__ = "AnnotationView";
    class Annotation extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        static init_Annotation() {
            this.override({
                level: 'annotation',
            });
        }
    }
    exports.Annotation = Annotation;
    Annotation.__name__ = "Annotation";
    Annotation.init_Annotation();
},
/* models/renderers/renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const view_1 = require(42) /* ../../core/view */;
    const visuals = tslib_1.__importStar(require(45) /* ../../core/visuals */);
    const enums_1 = require(20) /* ../../core/enums */;
    const model_1 = require(53) /* ../../model */;
    const coordinates_1 = require(54) /* ../canvas/coordinates */;
    class RendererView extends view_1.View {
        get coordinates() {
            const { _coordinates } = this;
            if (_coordinates != null)
                return _coordinates;
            else
                return this._coordinates = this._initialize_coordinates();
        }
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
            this.needs_webgl_blit = false;
        }
        connect_signals() {
            super.connect_signals();
            const { x_range_name, y_range_name } = this.model.properties;
            this.on_change([x_range_name, y_range_name], () => this._initialize_coordinates());
        }
        _initialize_coordinates() {
            const { x_range_name, y_range_name } = this.model;
            const { frame } = this.plot_view;
            const x_scale = frame.x_scales.get(x_range_name);
            const y_scale = frame.y_scales.get(y_range_name);
            return new coordinates_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);
        }
        notify_finished() {
            this.plot_view.notify_finished();
        }
        get needs_clip() {
            return false;
        }
        get has_webgl() {
            return false;
        }
        render() {
            if (this.model.visible) {
                this._render();
            }
            this._has_finished = true;
        }
        renderer_view(_renderer) {
            return undefined;
        }
    }
    exports.RendererView = RendererView;
    RendererView.__name__ = "RendererView";
    class Renderer extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_Renderer() {
            this.define(({ Boolean, String }) => ({
                level: [enums_1.RenderLevel, "image"],
                visible: [Boolean, true],
                x_range_name: [String, "default"],
                y_range_name: [String, "default"],
            }));
        }
    }
    exports.Renderer = Renderer;
    Renderer.__name__ = "Renderer";
    Renderer.init_Renderer();
},
/* core/view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const signaling_1 = require(15) /* ./signaling */;
    const dom_1 = require(43) /* ./dom */;
    const types_1 = require(8) /* ./util/types */;
    const root_css_1 = tslib_1.__importDefault(require(44) /* ../styles/root.css */);
    class View {
        constructor(options) {
            this.removed = new signaling_1.Signal0(this, "removed");
            this._ready = Promise.resolve(undefined);
            /** @internal */
            this._slots = new WeakMap();
            const { model, parent } = options;
            this.model = model;
            this.parent = parent;
            this.root = parent == null ? this : parent.root;
            this.removed.emit();
        }
        get ready() {
            return this._ready;
        }
        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);
                };
                this._slots.set(slot, new_slot);
            }
            return signal.connect(new_slot, this);
        }
        disconnect(signal, slot) {
            return signal.disconnect(slot, this);
        }
        initialize() {
            this._has_finished = false;
            if (this.is_root) {
                this._stylesheet = dom_1.stylesheet;
            }
            for (const style of this.styles()) {
                this.stylesheet.append(style);
            }
        }
        async lazy_initialize() { }
        remove() {
            this.disconnect_signals();
            this.removed.emit();
        }
        toString() {
            return `${this.model.type}View(${this.model.id})`;
        }
        serializable_state() {
            return { type: this.model.type };
        }
        get is_root() {
            return this.parent == null;
        }
        assert_root() {
            if (!this.is_root)
                throw new Error(`${this.toString()} is not a root layout`);
        }
        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 types_1.isArray(properties) ? properties : [properties]) {
                this.connect(property.change, fn);
            }
        }
        cursor(_sx, _sy) {
            return null;
        }
        get stylesheet() {
            if (this.is_root)
                return this._stylesheet;
            else
                return this.root.stylesheet;
        }
        styles() {
            return [root_css_1.default];
        }
    }
    exports.View = View;
    View.__name__ = "View";
},
/* core/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(13) /* ./util/object */;
    const _createElement = (tag) => {
        return (attrs = {}, ...children) => {
            const element = document.createElement(tag);
            element.classList.add("bk");
            for (let [attr, value] of object_1.entries(attrs)) {
                if (value == null || types_1.isBoolean(value) && !value)
                    continue;
                if (attr === "class") {
                    if (types_1.isString(value))
                        value = value.split(/\s+/);
                    if (types_1.isArray(value)) {
                        for (const cls of value) {
                            if (cls != null)
                                element.classList.add(cls);
                        }
                        continue;
                    }
                }
                if (attr === "style" && types_1.isPlainObject(value)) {
                    for (const [prop, data] of object_1.entries(value)) {
                        element.style[prop] = data;
                    }
                    continue;
                }
                if (attr === "data" && types_1.isPlainObject(value)) {
                    for (const [key, data] of object_1.entries(value)) {
                        element.dataset[key] = data; // XXX: attrs needs a better type
                    }
                    continue;
                }
                element.setAttribute(attr, value);
            }
            function append(child) {
                if (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 (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.input = _createElement("input"), exports.select = _createElement("select"), exports.option = _createElement("option"), exports.optgroup = _createElement("optgroup"), exports.textarea = _createElement("textarea");
    function nbsp() {
        return document.createTextNode("\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;
    exports.removeElement = 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) {
            node.removeChild(child);
        }
        if (attrs && node instanceof Element) {
            for (const attr of node.attributes) {
                node.removeAttributeNode(attr);
            }
        }
    }
    exports.empty = empty;
    function display(element) {
        element.style.display = "";
    }
    exports.display = display;
    function undisplay(element) {
        element.style.display = "none";
    }
    exports.undisplay = undisplay;
    function show(element) {
        element.style.visibility = "";
    }
    exports.show = show;
    function hide(element) {
        element.style.visibility = "hidden";
    }
    exports.hide = hide;
    function offset(element) {
        const rect = element.getBoundingClientRect();
        return {
            top: rect.top + window.pageYOffset - document.documentElement.clientTop,
            left: rect.left + window.pageXOffset - document.documentElement.clientLeft,
        };
    }
    exports.offset = offset;
    function matches(el, selector) {
        var _a, _b, _c;
        const p = Element.prototype;
        const f = (_c = (_b = (_a = p.matches) !== null && _a !== void 0 ? _a : p.webkitMatchesSelector) !== null && _b !== void 0 ? _b : p.mozMatchesSelector) !== null && _c !== void 0 ? _c : p.msMatchesSelector;
        return f.call(el, selector);
    }
    exports.matches = matches;
    function parent(el, selector) {
        let node = el;
        while (node = node.parentElement) {
            if (matches(node, selector))
                return node;
        }
        return null;
    }
    exports.parent = parent;
    function num(value) {
        return parseFloat(value) || 0;
    }
    function extents(el) {
        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) {
        const { left, top } = el.getBoundingClientRect();
        const { padding } = extents(el);
        let width = 0;
        let height = 0;
        for (const child of 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 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;
    function children(el) {
        return Array.from(el.children);
    }
    exports.children = children;
    class ClassList {
        constructor(el) {
            this.el = el;
            this.classList = el.classList;
        }
        get values() {
            const values = [];
            for (let i = 0; i < this.classList.length; i++) {
                const item = this.classList.item(i);
                if (item != null)
                    values.push(item);
            }
            return values;
        }
        has(cls) {
            return this.classList.contains(cls);
        }
        add(...classes) {
            for (const cls of classes)
                this.classList.add(cls);
            return this;
        }
        remove(...classes) {
            for (const cls of classes)
                this.classList.remove(cls);
            return this;
        }
        clear() {
            for (const cls of this.values) {
                if (cls != "bk")
                    this.classList.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);
    }
    exports.classes = classes;
    function toggle_attribute(el, attr, state) {
        if (state == null) {
            state = !el.hasAttribute(attr);
        }
        if (state)
            el.setAttribute(attr, "true");
        else
            el.removeAttribute(attr);
    }
    exports.toggle_attribute = toggle_attribute;
    (function (Keys) {
        Keys[Keys["Backspace"] = 8] = "Backspace";
        Keys[Keys["Tab"] = 9] = "Tab";
        Keys[Keys["Enter"] = 13] = "Enter";
        Keys[Keys["Esc"] = 27] = "Esc";
        Keys[Keys["PageUp"] = 33] = "PageUp";
        Keys[Keys["PageDown"] = 34] = "PageDown";
        Keys[Keys["Left"] = 37] = "Left";
        Keys[Keys["Up"] = 38] = "Up";
        Keys[Keys["Right"] = 39] = "Right";
        Keys[Keys["Down"] = 40] = "Down";
        Keys[Keys["Delete"] = 46] = "Delete";
    })(exports.Keys || (exports.Keys = {}));
    function undisplayed(el, fn) {
        const { display } = el.style;
        el.style.display = "none";
        try {
            return fn();
        }
        finally {
            el.style.display = display;
        }
    }
    exports.undisplayed = undisplayed;
    function unsized(el, fn) {
        return sized(el, {}, fn);
    }
    exports.unsized = unsized;
    function sized(el, size, fn) {
        const { width, height, position, display } = el.style;
        el.style.position = "absolute";
        el.style.display = "";
        el.style.width = size.width != null && size.width != Infinity ? `${size.width}px` : "auto";
        el.style.height = size.height != null && size.height != Infinity ? `${size.height}px` : "auto";
        try {
            return fn();
        }
        finally {
            el.style.position = position;
            el.style.display = display;
            el.style.width = width;
            el.style.height = height;
        }
    }
    exports.sized = sized;
    class StyleSheet {
        constructor(root) {
            this.root = root;
            this.known = new Set();
            this.style = exports.style({ type: "text/css" });
            prepend(root, this.style);
        }
        append(css) {
            if (!this.known.has(css)) {
                this.style.appendChild(document.createTextNode(css));
                this.known.add(css);
            }
        }
    }
    exports.StyleSheet = StyleSheet;
    StyleSheet.__name__ = "StyleSheet";
    exports.stylesheet = new StyleSheet(document.head);
    async function dom_ready() {
        if (document.readyState == "loading") {
            return new Promise((resolve, _reject) => {
                document.addEventListener("DOMContentLoaded", () => resolve(), { once: true });
            });
        }
    }
    exports.dom_ready = dom_ready;
},
/* styles/root.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.default = `.bk-root{position:relative;width:auto;height:auto;z-index:0;box-sizing:border-box;font-family:Helvetica, Arial, sans-serif;font-size:13px;}.bk-root .bk,.bk-root .bk:before,.bk-root .bk:after{box-sizing:inherit;margin:0;border:0;padding:0;background-image:none;font-family:inherit;font-size:100%;line-height:1.42857143;}.bk-root pre.bk{font-family:Courier, monospace;}`;
},
/* core/visuals/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const line_1 = require(46) /* ./line */;
    __esExport("Line", line_1.Line);
    __esExport("LineScalar", line_1.LineScalar);
    __esExport("LineVector", line_1.LineVector);
    const fill_1 = require(49) /* ./fill */;
    __esExport("Fill", fill_1.Fill);
    __esExport("FillScalar", fill_1.FillScalar);
    __esExport("FillVector", fill_1.FillVector);
    const text_1 = require(50) /* ./text */;
    __esExport("Text", text_1.Text);
    __esExport("TextScalar", text_1.TextScalar);
    __esExport("TextVector", text_1.TextVector);
    const hatch_1 = require(51) /* ./hatch */;
    __esExport("Hatch", hatch_1.Hatch);
    __esExport("HatchScalar", hatch_1.HatchScalar);
    __esExport("HatchVector", hatch_1.HatchVector);
    const mixins = tslib_1.__importStar(require(48) /* ../property_mixins */);
    const visual_1 = require(47) /* ./visual */;
    __esExport("VisualProperties", visual_1.VisualProperties);
    __esExport("VisualUniforms", visual_1.VisualUniforms);
    class 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);
                        default:
                            throw new Error("unknown visual");
                    }
                })();
                this._visuals.push(visual);
                Object.defineProperty(this, prefix + visual.type, {
                    get() { return visual; },
                    configurable: false,
                    enumerable: true,
                });
            }
        }
        *[Symbol.iterator]() {
            yield* this._visuals;
        }
    }
    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(47) /* ./visual */;
    const mixins = tslib_1.__importStar(require(48) /* ../property_mixins */);
    const color_1 = require(22) /* ../util/color */;
    const types_1 = require(8) /* ../util/types */;
    function resolve_line_dash(line_dash) {
        if (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);
        }
        set_value(ctx) {
            const color = this.line_color.get_value();
            const alpha = this.line_alpha.get_value();
            ctx.strokeStyle = color_1.color2css(color, alpha);
            ctx.lineWidth = this.line_width.get_value();
            ctx.lineJoin = this.line_join.get_value();
            ctx.lineCap = this.line_cap.get_value();
            ctx.lineDash = resolve_line_dash(this.line_dash.get_value());
            ctx.lineDashOffset = this.line_dash_offset.get_value();
        }
    }
    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);
        }
        set_value(ctx) {
            const color = this.line_color.value;
            const alpha = this.line_alpha.value;
            ctx.strokeStyle = color_1.color2css(color, alpha);
            ctx.lineWidth = this.line_width.value;
            ctx.lineJoin = this.line_join.value;
            ctx.lineCap = this.line_cap.value;
            ctx.lineDash = resolve_line_dash(this.line_dash.value);
            ctx.lineDashOffset = this.line_dash_offset.value;
        }
    }
    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;
        }
        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 = color_1.color2css(color, alpha);
            ctx.lineWidth = width;
            ctx.lineJoin = join;
            ctx.lineCap = cap;
            ctx.lineDash = 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 {
        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);
            }
            this.update();
        }
        *[Symbol.iterator]() {
            yield* this._props;
        }
        update() { }
    }
    exports.VisualProperties = VisualProperties;
    VisualProperties.__name__ = "VisualProperties";
    class VisualUniforms {
        constructor(obj, prefix = "") {
            this.obj = obj;
            this.prefix = prefix;
            for (const attr of this.attrs) {
                Object.defineProperty(this, attr, {
                    get() {
                        return obj[prefix + attr];
                    },
                });
            }
        }
        *[Symbol.iterator]() {
            for (const attr of this.attrs) {
                yield this.obj.model.properties[this.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(13) /* ./util/object */;
    exports.Line = {
        line_color: [k.Nullable(k.Color), "black"],
        line_alpha: [k.Alpha, 1.0],
        line_width: [k.Number, 1],
        line_join: [enums_1.LineJoin, "bevel"],
        line_cap: [enums_1.LineCap, "butt"],
        line_dash: [k.Or(enums_1.LineDash, k.Array(k.Number)), []],
        line_dash_offset: [k.Number, 0],
    };
    exports.Fill = {
        fill_color: [k.Nullable(k.Color), "gray"],
        fill_alpha: [k.Alpha, 1.0],
    };
    exports.Hatch = {
        hatch_color: [k.Nullable(k.Color), "black"],
        hatch_alpha: [k.Alpha, 1.0],
        hatch_scale: [k.Number, 12.0],
        hatch_pattern: [k.Nullable(k.Or(enums_1.HatchPatternType, k.String)), null],
        hatch_weight: [k.Number, 1.0],
        hatch_extra: [k.Dict(k.AnyRef()), {}],
    };
    exports.Text = {
        text_color: [k.Nullable(k.Color), "#444444"],
        text_alpha: [k.Alpha, 1.0],
        text_font: [p.Font, "helvetica"],
        text_font_size: [k.FontSize, "16px"],
        text_font_style: [enums_1.FontStyle, "normal"],
        text_align: [enums_1.TextAlign, "left"],
        text_baseline: [enums_1.TextBaseline, "bottom"],
        text_line_height: [k.Number, 1.2],
    };
    exports.LineScalar = {
        line_color: [p.ColorScalar, "black"],
        line_alpha: [p.NumberScalar, 1.0],
        line_width: [p.NumberScalar, 1],
        line_join: [p.LineJoinScalar, "bevel"],
        line_cap: [p.LineCapScalar, "butt"],
        line_dash: [p.LineDashScalar, []],
        line_dash_offset: [p.NumberScalar, 0],
    };
    exports.FillScalar = {
        fill_color: [p.ColorScalar, "gray"],
        fill_alpha: [p.NumberScalar, 1.0],
    };
    exports.HatchScalar = {
        hatch_color: [p.ColorScalar, "black"],
        hatch_alpha: [p.NumberScalar, 1.0],
        hatch_scale: [p.NumberScalar, 12.0],
        hatch_pattern: [p.NullStringScalar, null],
        hatch_weight: [p.NumberScalar, 1.0],
        hatch_extra: [p.AnyScalar, {}],
    };
    exports.TextScalar = {
        text_color: [p.ColorScalar, "#444444"],
        text_alpha: [p.NumberScalar, 1.0],
        text_font: [p.FontScalar, "helvetica"],
        text_font_size: [p.FontSizeScalar, "16px"],
        text_font_style: [p.FontStyleScalar, "normal"],
        text_align: [p.TextAlignScalar, "left"],
        text_baseline: [p.TextBaselineScalar, "bottom"],
        text_line_height: [p.NumberScalar, 1.2],
    };
    exports.LineVector = {
        line_color: [p.ColorSpec, "black"],
        line_alpha: [p.NumberSpec, 1.0],
        line_width: [p.NumberSpec, 1],
        line_join: [p.LineJoinSpec, "bevel"],
        line_cap: [p.LineCapSpec, "butt"],
        line_dash: [p.LineDashSpec, []],
        line_dash_offset: [p.NumberSpec, 0],
    };
    exports.FillVector = {
        fill_color: [p.ColorSpec, "gray"],
        fill_alpha: [p.NumberSpec, 1.0],
    };
    exports.HatchVector = {
        hatch_color: [p.ColorSpec, "black"],
        hatch_alpha: [p.NumberSpec, 1.0],
        hatch_scale: [p.NumberSpec, 12.0],
        hatch_pattern: [p.NullStringSpec, null],
        hatch_weight: [p.NumberSpec, 1.0],
        hatch_extra: [p.AnyScalar, {}],
    };
    exports.TextVector = {
        text_color: [p.ColorSpec, "#444444"],
        text_alpha: [p.NumberSpec, 1.0],
        text_font: [p.FontSpec, "helvetica"],
        text_font_size: [p.FontSizeSpec, "16px"],
        text_font_style: [p.FontStyleSpec, "normal"],
        text_align: [p.TextAlignSpec, "left"],
        text_baseline: [p.TextBaselineSpec, "bottom"],
        text_line_height: [p.NumberSpec, 1.2],
    };
    function attrs_of(model, prefix, mixin, prefixed = false) {
        const attrs = {};
        for (const attr of object_1.keys(mixin)) {
            const prefixed_attr = `${prefix}${attr}`;
            const value = model[prefixed_attr];
            attrs[prefixed ? prefixed_attr : 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(47) /* ./visual */;
    const mixins = tslib_1.__importStar(require(48) /* ../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);
        }
        set_value(ctx) {
            const color = this.fill_color.get_value();
            const alpha = this.fill_alpha.get_value();
            ctx.fillStyle = 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);
        }
        set_value(ctx) {
            const color = this.fill_color.value;
            const alpha = this.fill_alpha.value;
            ctx.fillStyle = 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;
        }
        set_vectorize(ctx, i) {
            const color = this.fill_color.get(i);
            const alpha = this.fill_alpha.get(i);
            ctx.fillStyle = 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(47) /* ./visual */;
    const mixins = tslib_1.__importStar(require(48) /* ../property_mixins */);
    const color_1 = require(22) /* ../util/color */;
    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);
        }
        set_value(ctx) {
            const color = this.text_color.get_value();
            const alpha = this.text_alpha.get_value();
            ctx.fillStyle = color_1.color2css(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);
        }
        set_value(ctx) {
            const color = this.text_color.value;
            const alpha = this.text_alpha.value;
            const font = this.font_value();
            const align = this.text_align.value;
            const baseline = this.text_baseline.value;
            ctx.fillStyle = color_1.color2css(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 {
        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;
        }
        set_vectorize(ctx, i) {
            const color = this.text_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 = color_1.color2css(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(47) /* ./visual */;
    const patterns_1 = require(52) /* ./patterns */;
    const p = tslib_1.__importStar(require(18) /* ../properties */);
    const mixins = tslib_1.__importStar(require(48) /* ../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 = 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);
        }
        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 == null || 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 = patterns_1.get_pattern(layer, pattern, color, alpha, scale, weight);
                finalize(image);
            }
        }
        get doit() {
            return this._static_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;
            const texture = this.hatch_extra.value[pattern];
            if (texture == null)
                return "repeat";
            else {
                switch (texture.repetition) {
                    case "repeat": return "repeat";
                    case "repeat_x": return "repeat-x";
                    case "repeat_y": return "repeat-y";
                    case "no_repeat": return "no-repeat";
                }
            }
        }
    }
    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 = 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;
        }
        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);
            const texture = this.hatch_extra.value[pattern];
            if (texture == null)
                return "repeat";
            else {
                switch (texture.repetition) {
                    case "repeat": return "repeat";
                    case "repeat_x": return "repeat-x";
                    case "repeat_y": return "repeat-y";
                    case "no_repeat": return "no-repeat";
                }
            }
        }
    }
    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 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 = 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();
                ctx.stroke();
                break;
            case "left_diagonal_line":
                ctx.moveTo(h4 + 0.5, h);
                ctx.lineTo(-h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(3 * h4 + 0.5, h);
                ctx.lineTo(h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(5 * h4 + 0.5, h);
                ctx.lineTo(3 * h4 + 0.5, 0);
                ctx.stroke();
                ctx.stroke();
                break;
            case "diagonal_cross":
                _x(ctx, h);
                break;
            case "right_diagonal_dash":
                ctx.moveTo(h4 + 0.5, 3 * h4 + 0.5);
                ctx.lineTo(3 * h4 + 0.5, h4 + 0.5);
                ctx.stroke();
                break;
            case "left_diagonal_dash":
                ctx.moveTo(h4 + 0.5, h4 + 0.5);
                ctx.lineTo(3 * h4 + 0.5, 3 * h4 + 0.5);
                ctx.stroke();
                break;
            case "horizontal_wave":
                ctx.moveTo(0, h4);
                ctx.lineTo(h2, 3 * h4);
                ctx.lineTo(h, h4);
                ctx.stroke();
                break;
            case "vertical_wave":
                ctx.moveTo(h4, 0);
                ctx.lineTo(3 * h4, h2);
                ctx.lineTo(h4, h);
                ctx.stroke();
                break;
            case "criss_cross":
                _x(ctx, h);
                _horz(ctx, h, h2);
                _vert(ctx, h, h2);
                break;
        }
    }
},
/* model.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const has_props_1 = require(14) /* ./core/has_props */;
    const types_1 = require(8) /* ./core/util/types */;
    const object_1 = require(13) /* ./core/util/object */;
    const logging_1 = require(19) /* ./core/logging */;
    class Model extends has_props_1.HasProps {
        constructor(attrs) {
            super(attrs);
        }
        get is_syncable() {
            return this.syncable;
        }
        static init_Model() {
            this.define(({ Any, Unknown, Boolean, String, Array, 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: [Array(String), []],
                syncable: [Boolean, true],
            }));
        }
        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 _a;
            for (const callback of (_a = this.js_event_callbacks[event.event_name]) !== null && _a !== void 0 ? _a : [])
                callback.execute(event);
            if (this.document != null && this.subscribed_events.some((m) => m == 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 object_1.entries(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 (!object_1.isEmpty(this.js_event_callbacks) || this.subscribed_events.length != 0)
                this._update_event_callbacks();
        }
        _doc_detached() {
            this.document.event_manager.subscribed_models.delete(this);
        }
        select(selector) {
            if (types_1.isString(selector))
                return [...this.references()].filter((ref) => ref instanceof Model && ref.name === selector);
            else if (selector.prototype instanceof has_props_1.HasProps)
                return [...this.references()].filter((ref) => ref instanceof selector);
            else
                throw new Error("invalid 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");
            }
        }
    }
    exports.Model = Model;
    Model.__name__ = "Model";
    Model.init_Model();
},
/* models/canvas/coordinates.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class CoordinateTransform {
        constructor(x_scale, y_scale) {
            this.x_scale = x_scale;
            this.y_scale = y_scale;
            this.x_range = this.x_scale.source_range;
            this.y_range = this.y_scale.source_range;
            this.ranges = [this.x_range, this.y_range];
            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";
},
/* models/annotations/arrow.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(56) /* ./data_annotation */;
    const arrow_head_1 = require(133) /* ./arrow_head */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const enums_1 = require(20) /* ../../core/enums */;
    const types_1 = require(24) /* ../../core/types */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(10) /* ../../core/util/math */;
    class ArrowView extends data_annotation_1.DataAnnotationView {
        async lazy_initialize() {
            await super.lazy_initialize();
            const { start, end } = this.model;
            if (start != null)
                this.start = await build_views_1.build_view(start, { parent: this });
            if (end != null)
                this.end = await build_views_1.build_view(end, { parent: this });
        }
        set_data(source) {
            var _a, _b;
            super.set_data(source);
            (_a = this.start) === null || _a === void 0 ? void 0 : _a.set_data(source);
            (_b = this.end) === null || _b === void 0 ? void 0 : _b.set_data(source);
        }
        remove() {
            var _a, _b;
            (_a = this.start) === null || _a === void 0 ? void 0 : _a.remove();
            (_b = this.end) === null || _b === void 0 ? void 0 : _b.remove();
            super.remove();
        }
        map_data() {
            const { frame } = this.plot_view;
            if (this.model.start_units == "data") {
                this._sx_start = this.coordinates.x_scale.v_compute(this._x_start);
                this._sy_start = this.coordinates.y_scale.v_compute(this._y_start);
            }
            else {
                this._sx_start = frame.bbox.xview.v_compute(this._x_start);
                this._sy_start = frame.bbox.yview.v_compute(this._y_start);
            }
            if (this.model.end_units == "data") {
                this._sx_end = this.coordinates.x_scale.v_compute(this._x_end);
                this._sy_end = this.coordinates.y_scale.v_compute(this._y_end);
            }
            else {
                this._sx_end = frame.bbox.xview.v_compute(this._x_end);
                this._sy_end = frame.bbox.yview.v_compute(this._y_end);
            }
            const { _sx_start, _sy_start, _sx_end, _sy_end } = this;
            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 + 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) {
                    ctx.save();
                    if (start != null || end != null) {
                        ctx.beginPath();
                        ctx.rect(x, y, width, height);
                        if (end != null) {
                            ctx.save();
                            ctx.translate(_sx_end[i], _sy_end[i]);
                            ctx.rotate(_angles[i]);
                            end.clip(ctx, i);
                            ctx.restore();
                        }
                        if (start != null) {
                            ctx.save();
                            ctx.translate(_sx_start[i], _sy_start[i]);
                            ctx.rotate(_angles[i] + Math.PI);
                            start.clip(ctx, i);
                            ctx.restore();
                        }
                        ctx.closePath();
                        ctx.clip();
                    }
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.beginPath();
                    ctx.moveTo(_sx_start[i], _sy_start[i]);
                    ctx.lineTo(_sx_end[i], _sy_end[i]);
                    ctx.stroke();
                    ctx.restore();
                }
            }
        }
    }
    exports.ArrowView = ArrowView;
    ArrowView.__name__ = "ArrowView";
    class Arrow extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_Arrow() {
            this.prototype.default_view = ArrowView;
            this.mixins(property_mixins_1.LineVector);
            this.define(({ Ref, Nullable }) => ({
                x_start: [p.XCoordinateSpec, { field: "x_start" }],
                y_start: [p.YCoordinateSpec, { field: "y_start" }],
                start_units: [enums_1.SpatialUnits, "data"],
                start: [Nullable(Ref(arrow_head_1.ArrowHead)), null],
                x_end: [p.XCoordinateSpec, { field: "x_end" }],
                y_end: [p.YCoordinateSpec, { field: "y_end" }],
                end_units: [enums_1.SpatialUnits, "data"],
                end: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.OpenHead()],
            }));
        }
    }
    exports.Arrow = Arrow;
    Arrow.__name__ = "Arrow";
    Arrow.init_Arrow();
},
/* models/annotations/data_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(40) /* ./annotation */;
    const columnar_data_source_1 = require(57) /* ../sources/columnar_data_source */;
    const column_data_source_1 = require(130) /* ../sources/column_data_source */;
    const projections_1 = require(65) /* ../../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.request_render();
            };
            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);
        }
        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);
        }
        static init_DataAnnotation() {
            this.define(({ Ref }) => ({
                source: [Ref(columnar_data_source_1.ColumnarDataSource), () => new column_data_source_1.ColumnDataSource()],
            }));
        }
    }
    exports.DataAnnotation = DataAnnotation;
    DataAnnotation.__name__ = "DataAnnotation";
    DataAnnotation.init_DataAnnotation();
},
/* models/sources/columnar_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_source_1 = require(58) /* ./data_source */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const logging_1 = require(19) /* ../../core/logging */;
    const selection_manager_1 = require(60) /* ../../core/selection_manager */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../core/util/object */;
    const selection_1 = require(59) /* ../selections/selection */;
    const interaction_policy_1 = require(129) /* ../selections/interaction_policy */;
    const ndarray_1 = require(29) /* ../../core/util/ndarray */;
    class ColumnarDataSource extends data_source_1.DataSource {
        constructor(attrs) {
            super(attrs);
        }
        get_array(key) {
            let column = this.data[key];
            if (column == null)
                this.data[key] = column = [];
            else if (!types_1.isArray(column))
                this.data[key] = column = Array.from(column);
            return column;
        }
        static init_ColumnarDataSource() {
            this.define(({ Ref }) => ({
                selection_policy: [Ref(interaction_policy_1.SelectionPolicy), () => new interaction_policy_1.UnionRenderers()],
            }));
            this.internal(({ AnyRef }) => ({
                selection_manager: [AnyRef(), (self) => new selection_manager_1.SelectionManager({ source: self })],
                inspected: [AnyRef(), () => new selection_1.Selection()],
            }));
        }
        initialize() {
            super.initialize();
            this._select = new signaling_1.Signal0(this, "select");
            this.inspect = new signaling_1.Signal(this, "inspect");
            this.streaming = new signaling_1.Signal0(this, "streaming");
            this.patching = new signaling_1.Signal(this, "patching");
        }
        get_column(colname) {
            const column = this.data[colname];
            return column != null ? column : null;
        }
        columns() {
            // return the column names in this data source
            return object_1.keys(this.data);
        }
        get_length(soft = true) {
            const lengths = array_1.uniq(object_1.values(this.data).map((v) => 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 _a;
            return (_a = this.get_length()) !== null && _a !== void 0 ? _a : 0;
        }
        clear() {
            const empty = {};
            for (const col of this.columns()) {
                empty[col] = new this.data[col].constructor(0);
            }
            this.data = empty;
        }
    }
    exports.ColumnarDataSource = ColumnarDataSource;
    ColumnarDataSource.__name__ = "ColumnarDataSource";
    ColumnarDataSource.init_ColumnarDataSource();
},
/* models/sources/data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const selection_1 = require(59) /* ../selections/selection */;
    class DataSource extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_DataSource() {
            this.define(({ Ref }) => ({
                selected: [Ref(selection_1.Selection), () => new selection_1.Selection()],
            }));
        }
    }
    exports.DataSource = DataSource;
    DataSource.__name__ = "DataSource";
    DataSource.init_DataSource();
},
/* models/selections/selection.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const array_1 = require(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../core/util/object */;
    class Selection extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get_view() {
            return this.view;
        }
        static init_Selection() {
            this.define(({ Int, Array, Dict }) => ({
                indices: [Array(Int), []],
                line_indices: [Array(Int), []],
                multiline_indices: [Dict(Array(Int)), {}],
            }));
            this.internal(({ Int, Array, AnyRef, Struct, Nullable }) => ({
                selected_glyphs: [Array(AnyRef()), []],
                view: [Nullable(AnyRef()), null],
                // Used internally to support hover tool for now. Python API TBD
                image_indices: [Array(Struct({ index: Int, dim1: Int, dim2: Int, flat_index: Int })), []],
            }));
        }
        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.selected_glyphs = selection.selected_glyphs;
                    this.view = selection.view;
                    this.multiline_indices = selection.multiline_indices;
                    this.image_indices = selection.image_indices;
                    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.view = null;
            this.selected_glyphs = [];
        }
        is_empty() {
            return this.indices.length == 0 && this.line_indices.length == 0 && this.image_indices.length == 0;
        }
        update_through_union(other) {
            this.indices = array_1.union(this.indices, other.indices);
            this.selected_glyphs = array_1.union(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = array_1.union(other.line_indices, this.line_indices);
            this.view = other.view;
            this.multiline_indices = object_1.merge(other.multiline_indices, this.multiline_indices);
        }
        update_through_intersection(other) {
            this.indices = array_1.intersection(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = array_1.union(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = array_1.union(other.line_indices, this.line_indices);
            this.view = other.view;
            this.multiline_indices = object_1.merge(other.multiline_indices, this.multiline_indices);
        }
        update_through_subtraction(other) {
            this.indices = array_1.difference(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = array_1.union(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = array_1.union(other.line_indices, this.line_indices);
            this.view = other.view;
            this.multiline_indices = object_1.merge(other.multiline_indices, this.multiline_indices);
        }
    }
    exports.Selection = Selection;
    Selection.__name__ = "Selection";
    Selection.init_Selection();
},
/* core/selection_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const has_props_1 = require(14) /* ./has_props */;
    const selection_1 = require(59) /* ../models/selections/selection */;
    const glyph_renderer_1 = require(61) /* ../models/renderers/glyph_renderer */;
    const graph_renderer_1 = require(123) /* ../models/renderers/graph_renderer */;
    class SelectionManager extends has_props_1.HasProps {
        constructor(attrs) {
            super(attrs);
            this.inspectors = new Map();
        }
        static init_SelectionManager() {
            this.internal(({ AnyRef }) => ({
                source: [AnyRef()],
            }));
        }
        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 (r instanceof glyph_renderer_1.GlyphRendererView)
                    glyph_renderer_views.push(r);
                else if (r instanceof graph_renderer_1.GraphRendererView)
                    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 (renderer_view instanceof glyph_renderer_1.GlyphRendererView) {
                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 (renderer_view instanceof graph_renderer_1.GraphRendererView) {
                const hit_test_result = renderer_view.model.inspection_policy.hit_test(geometry, renderer_view);
                did_hit = did_hit || renderer_view.model.inspection_policy.do_inspection(hit_test_result, geometry, renderer_view, false, "replace");
            }
            return did_hit;
        }
        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";
    SelectionManager.init_SelectionManager();
},
/* models/renderers/glyph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_renderer_1 = require(62) /* ./data_renderer */;
    const line_1 = require(63) /* ../glyphs/line */;
    const patch_1 = require(116) /* ../glyphs/patch */;
    const harea_1 = require(117) /* ../glyphs/harea */;
    const varea_1 = require(119) /* ../glyphs/varea */;
    const glyph_1 = require(98) /* ../glyphs/glyph */;
    const columnar_data_source_1 = require(57) /* ../sources/columnar_data_source */;
    const cds_view_1 = require(120) /* ../sources/cds_view */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const array_1 = require(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../core/util/object */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const factor_range_1 = require(104) /* ../ranges/factor_range */;
    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: {},
    };
    class GlyphRendererView extends data_renderer_1.DataRendererView {
        get glyph_view() {
            return this.glyph;
        }
        async lazy_initialize() {
            var _a, _b;
            await super.lazy_initialize();
            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 = object_1.clone(glyph_attrs);
                if (has_fill)
                    object_1.extend(attrs, defaults.fill);
                if (has_line)
                    object_1.extend(attrs, defaults.line);
                return new base_glyph.constructor(attrs);
            }
            let { selection_glyph } = this.model;
            if (selection_glyph == null)
                selection_glyph = mk_glyph({ fill: {}, line: {} });
            else if (selection_glyph == "auto")
                selection_glyph = mk_glyph(selection_defaults);
            this.selection_glyph = await this.build_glyph_view(selection_glyph);
            let { nonselection_glyph } = this.model;
            if (nonselection_glyph == null)
                nonselection_glyph = mk_glyph({ fill: {}, line: {} });
            else if (nonselection_glyph == "auto")
                nonselection_glyph = mk_glyph(nonselection_defaults);
            this.nonselection_glyph = await this.build_glyph_view(nonselection_glyph);
            const { hover_glyph } = this.model;
            if (hover_glyph != null)
                this.hover_glyph = await this.build_glyph_view(hover_glyph);
            const { muted_glyph } = this.model;
            if (muted_glyph != null)
                this.muted_glyph = await this.build_glyph_view(muted_glyph);
            const decimated_glyph = mk_glyph(decimated_defaults);
            this.decimated_glyph = await this.build_glyph_view(decimated_glyph);
            this.selection_glyph.set_base(this.glyph);
            this.nonselection_glyph.set_base(this.glyph);
            (_a = this.hover_glyph) === null || _a === void 0 ? void 0 : _a.set_base(this.glyph);
            (_b = this.muted_glyph) === null || _b === void 0 ? void 0 : _b.set_base(this.glyph);
            this.decimated_glyph.set_base(this.glyph);
            this.set_data();
        }
        async build_glyph_view(glyph) {
            return build_views_1.build_view(glyph, { parent: this });
        }
        remove() {
            var _a, _b;
            this.glyph.remove();
            this.selection_glyph.remove();
            this.nonselection_glyph.remove();
            (_a = this.hover_glyph) === null || _a === void 0 ? void 0 : _a.remove();
            (_b = this.muted_glyph) === null || _b === void 0 ? void 0 : _b.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);
            if (this.muted_glyph != null)
                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, render);
            this.connect(this.model.properties.view.change, update);
            this.connect(this.model.view.properties.indices.change, update);
            this.connect(this.model.view.properties.masked.change, () => 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.change, update);
            }
            for (const [, range] of y_ranges) {
                if (range instanceof factor_range_1.FactorRange)
                    this.connect(range.change, 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 _a, _b, _c, _d;
            const source = this.model.data_source;
            const { all_indices } = this;
            this.glyph.set_visuals(source, all_indices);
            this.decimated_glyph.set_visuals(source, all_indices);
            (_a = this.selection_glyph) === null || _a === void 0 ? void 0 : _a.set_visuals(source, all_indices);
            (_b = this.nonselection_glyph) === null || _b === void 0 ? void 0 : _b.set_visuals(source, all_indices);
            (_c = this.hover_glyph) === null || _c === void 0 ? void 0 : _c.set_visuals(source, all_indices);
            (_d = this.muted_glyph) === null || _d === void 0 ? void 0 : _d.set_visuals(source, all_indices);
        }
        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;
            let selected_full_indices;
            if (!selected || selected.is_empty())
                selected_full_indices = [];
            else {
                if (this.glyph instanceof line_1.LineView && selected.selected_glyph === this.glyph.model)
                    selected_full_indices = this.model.view.convert_indices_from_subset(indices);
                else
                    selected_full_indices = selected.indices;
            }
            // inspected is in full set space
            const { inspected } = this.model.data_source;
            const inspected_full_indices = new Set((() => {
                if (!inspected || inspected.is_empty())
                    return [];
                else {
                    if (inspected.selected_glyph)
                        return this.model.view.convert_indices_from_subset(indices);
                    else if (inspected.indices.length > 0)
                        return inspected.indices;
                    else {
                        // TODO: return inspected.multiline_indices.keys()
                        return Object.keys(inspected.multiline_indices).map((i) => parseInt(i));
                    }
                }
            })());
            // inspected is transformed to subset space
            const inspected_subset_indices = 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 != null ? this.muted_glyph : this.glyph;
                nonselection_glyph = this.nonselection_glyph;
                selection_glyph = this.selection_glyph;
            }
            if (this.hover_glyph != null && inspected_subset_indices.length)
                indices = array_1.difference(indices, inspected_subset_indices);
            // Render with no selection
            if (!selected_full_indices.length) {
                if (this.glyph instanceof line_1.LineView) {
                    if (this.hover_glyph && inspected_subset_indices.length)
                        this.hover_glyph.render(ctx, this.model.view.convert_indices_from_subset(inspected_subset_indices));
                    else
                        glyph.render(ctx, all_indices);
                }
                else if (this.glyph instanceof patch_1.PatchView || this.glyph instanceof harea_1.HAreaView || this.glyph instanceof varea_1.VAreaView) {
                    if (inspected.selected_glyphs.length == 0 || this.hover_glyph == null) {
                        glyph.render(ctx, all_indices);
                    }
                    else {
                        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 && inspected_subset_indices.length)
                        this.hover_glyph.render(ctx, inspected_subset_indices);
                }
                // Render with selection
            }
            else {
                // reset the selection mask
                const selected_mask = {};
                for (const i of selected_full_indices) {
                    selected_mask[i] = true;
                }
                // 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[i] != null)
                            selected_subset_indices.push(i);
                        else
                            nonselected_subset_indices.push(i);
                    }
                }
                else {
                    for (const i of indices) {
                        if (selected_mask[all_indices[i]] != null)
                            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();
        }
        draw_legend(ctx, x0, x1, y0, y1, field, label, index) {
            if (this.glyph.data_size == 0)
                return;
            if (index == null)
                index = this.model.get_reference_point(field, label);
            this.glyph.draw_legend_for_index(ctx, { x0, x1, y0, y1 }, 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);
        }
        static init_GlyphRenderer() {
            this.prototype.default_view = GlyphRendererView;
            this.define(({ Boolean, Auto, Or, Ref, Null, Nullable }) => ({
                data_source: [Ref(columnar_data_source_1.ColumnarDataSource)],
                view: [Ref(cds_view_1.CDSView), (self) => new cds_view_1.CDSView({ source: self.data_source })],
                glyph: [Ref(glyph_1.Glyph)],
                hover_glyph: [Nullable(Ref(glyph_1.Glyph)), null],
                nonselection_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
                selection_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
                muted_glyph: [Nullable(Ref(glyph_1.Glyph)), null],
                muted: [Boolean, false],
            }));
        }
        initialize() {
            super.initialize();
            if (this.view.source != this.data_source) {
                this.view.source = this.data_source;
                this.view.compute_indices();
            }
        }
        get_reference_point(field, value) {
            let index = 0;
            if (field != null) {
                const data = this.data_source.get_column(field);
                if (data != null) {
                    if (this.view == null) {
                        const i = arrayable_1.indexOf(data, value);
                        if (i != -1)
                            index = i;
                    }
                    else {
                        for (const [k, v] of Object.entries(this.view.indices_map)) {
                            if (data[parseInt(k)] == value) {
                                index = v;
                                break;
                            }
                        }
                    }
                }
            }
            return index;
        }
        get_selection_manager() {
            return this.data_source.selection_manager;
        }
    }
    exports.GlyphRenderer = GlyphRenderer;
    GlyphRenderer.__name__ = "GlyphRenderer";
    GlyphRenderer.init_GlyphRenderer();
},
/* models/renderers/data_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const renderer_1 = require(41) /* ./renderer */;
    class DataRendererView extends renderer_1.RendererView {
        get xscale() {
            return this.coordinates.x_scale;
        }
        get yscale() {
            return this.coordinates.y_scale;
        }
    }
    exports.DataRendererView = DataRendererView;
    DataRendererView.__name__ = "DataRendererView";
    class DataRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        static init_DataRenderer() {
            this.override({
                level: 'glyph',
            });
        }
        get selection_manager() {
            return this.get_selection_manager();
        }
    }
    exports.DataRenderer = DataRenderer;
    DataRenderer.__name__ = "DataRenderer";
    DataRenderer.init_DataRenderer();
},
/* models/glyphs/line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const utils_1 = require(106) /* ./utils */;
    const line_1 = require(108) /* ./webgl/line */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const selection_1 = require(59) /* ../selections/selection */;
    class LineView extends xy_glyph_1.XYGlyphView {
        initialize() {
            super.initialize();
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null) {
                this.glglyph = new line_1.LineGL(webgl.gl, this);
            }
        }
        _render(ctx, indices, data) {
            const { sx, sy } = data !== null && data !== void 0 ? data : this;
            let drawing = false;
            let last_index = null;
            this.visuals.line.set_value(ctx);
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                if (drawing) {
                    if (!isFinite(sx_i + sy_i)) {
                        ctx.stroke();
                        ctx.beginPath();
                        drawing = false;
                        last_index = i;
                        continue;
                    }
                    if (last_index != null && i - last_index > 1) {
                        ctx.stroke();
                        drawing = false;
                    }
                }
                if (drawing)
                    ctx.lineTo(sx_i, sy_i);
                else {
                    ctx.beginPath();
                    ctx.moveTo(sx_i, sy_i);
                    drawing = true;
                }
                last_index = i;
            }
            if (drawing)
                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;
            const result = new selection_1.Selection();
            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;
            }
            for (let i = 0, end = values.length - 1; i < end; i++) {
                if ((values[i] <= val && val <= values[i + 1]) || (values[i + 1] <= val && val <= values[i])) {
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices.push(i);
                }
            }
            return result;
        }
        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 utils_1.line_interpolation(this.renderer, geometry, x2, y2, x3, y3);
        }
        draw_legend_for_index(ctx, bbox, _index) {
            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);
        }
        static init_Line() {
            this.prototype.default_view = LineView;
            this.mixins(mixins.LineScalar);
        }
    }
    exports.Line = Line;
    Line.__name__ = "Line";
    Line.init_Line();
},
/* models/glyphs/xy_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const glyph_1 = require(98) /* ./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];
                if (isNaN(x + y) || !isFinite(x + y))
                    index.add_empty();
                else
                    index.add(x, y, 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);
        }
        static init_XYGlyph() {
            this.define(({}) => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y: [p.YCoordinateSpec, { field: "y" }],
            }));
        }
    }
    exports.XYGlyph = XYGlyph;
    XYGlyph.__name__ = "XYGlyph";
    XYGlyph.init_XYGlyph();
},
/* core/util/projections.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const core_1 = tslib_1.__importDefault(require(66) /* proj4/lib/core */);
    const Proj_1 = tslib_1.__importDefault(require(67) /* 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 = 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 = 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(67) /* ./Proj */);
    const transform_1 = tslib_1.__importDefault(require(92) /* ./transform */);
    var wgs84 = Proj_1.default('WGS84');
    function transformer(from, to, coords) {
        var transformedArray, out, keys;
        if (Array.isArray(coords)) {
            transformedArray = transform_1.default(from, to, coords) || { 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 = transform_1.default(from, to, coords);
            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 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) {
                    return transformer(fromProj, toProj, coords);
                },
                inverse: function (coords) {
                    return transformer(toProj, fromProj, coords);
                }
            };
            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(68) /* ./parseCode */);
    const extend_1 = tslib_1.__importDefault(require(79) /* ./extend */);
    const projections_1 = tslib_1.__importDefault(require(80) /* ./projections */);
    const deriveConstants_1 = require(88) /* ./deriveConstants */;
    const Datum_1 = tslib_1.__importDefault(require(90) /* ./constants/Datum */);
    const datum_1 = tslib_1.__importDefault(require(91) /* ./datum */);
    const match_1 = tslib_1.__importDefault(require(75) /* ./match */);
    function Projection(srsCode, callback) {
        if (!(this instanceof Projection)) {
            return new Projection(srsCode);
        }
        callback = callback || function (error) {
            if (error) {
                throw error;
            }
        };
        var json = 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 = match_1.default(Datum_1.default, json.datumCode);
            if (datumDef) {
                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';
        var sphere_ = deriveConstants_1.sphere(json.a, json.b, json.rf, json.ellps, json.sphere);
        var ecc = deriveConstants_1.eccentricity(sphere_.a, sphere_.b, sphere_.rf, json.R_A);
        var datumObj = json.datum || datum_1.default(json.datumCode, json.datum_params, sphere_.a, sphere_.b, ecc.es, ecc.ep2);
        extend_1.default(this, json); // transfer everything over from the projection because we don't know what we'll need
        extend_1.default(this, ourProj); // transfer all the methods from the projection
        // copy the 4 things over we calulated in deriveConstants.sphere
        this.a = sphere_.a;
        this.b = sphere_.b;
        this.rf = sphere_.rf;
        this.sphere = sphere_.sphere;
        // copy the 3 things we calculated in deriveConstants.eccentricity
        this.es = ecc.es;
        this.e = ecc.e;
        this.ep2 = ecc.ep2;
        // add in the datum object
        this.datum = datumObj;
        // init the projection
        this.init();
        // legecy callback from back in the day when it went to spatialreference.org
        callback(null, this);
    }
    Projection.projections = projections_1.default;
    Projection.projections.start();
    exports.default = Projection;
},
/* proj4/lib/parseCode.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const defs_1 = tslib_1.__importDefault(require(69) /* ./defs */);
    const wkt_parser_1 = tslib_1.__importDefault(require(76) /* wkt-parser */);
    const projString_1 = tslib_1.__importDefault(require(71) /* ./projString */);
    const match_1 = tslib_1.__importDefault(require(75) /* ./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 = match_1.default(item, 'authority');
        if (!auth) {
            return;
        }
        var code = match_1.default(auth, 'epsg');
        return code && codes.indexOf(code) > -1;
    }
    function checkProjStr(item) {
        var ext = match_1.default(item, 'extension');
        if (!ext) {
            return;
        }
        return 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 = 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 projString_1.default(maybeProjStr);
                }
                return out;
            }
            if (testProj(code)) {
                return 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(70) /* ./global */);
    const projString_1 = tslib_1.__importDefault(require(71) /* ./projString */);
    const wkt_parser_1 = tslib_1.__importDefault(require(76) /* 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] = projString_1.default(arguments[1]);
                }
                else {
                    defs[name] = 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;
        }
    }
    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(72) /* ./constants/values */;
    const PrimeMeridian_1 = tslib_1.__importDefault(require(73) /* ./constants/PrimeMeridian */);
    const units_1 = tslib_1.__importDefault(require(74) /* ./constants/units */);
    const match_1 = tslib_1.__importDefault(require(75) /* ./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;
            },
            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 = 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 = 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;
                }
            }
        };
        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_WGS84 = 4; // WGS84 or equivalent
    exports.PJD_NODATUM = 5; // WGS84 or equivalent
    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(77) /* ./parser */);
    const process_1 = require(78) /* ./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];
                var descriptor = axis[0].toLowerCase();
                if (descriptor.indexOf('north') !== -1) {
                    axisOrder += 'n';
                }
                else if (descriptor.indexOf('south') !== -1) {
                    axisOrder += 's';
                }
                else if (descriptor.indexOf('east') !== -1) {
                    axisOrder += 'e';
                }
                else if (descriptor.indexOf('west') !== -1) {
                    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_2', 'Standard_Parallel_2'],
            ['false_easting', 'False_Easting'],
            ['false_northing', 'False_Northing'],
            ['central_meridian', 'Central_Meridian'],
            ['latitude_of_origin', 'Latitude_Of_Origin'],
            ['latitude_of_origin', 'Central_Parallel'],
            ['scale_factor', 'Scale_Factor'],
            ['k0', 'scale_factor'],
            ['latitude_of_center', 'Latitude_Of_Center'],
            ['latitude_of_center', 'Latitude_of_center'],
            ['lat0', 'latitude_of_center', d2r],
            ['longitude_of_center', 'Longitude_Of_Center'],
            ['longitude_of_center', 'Longitude_of_center'],
            ['longc', 'longitude_of_center', d2r],
            ['x0', 'false_easting', toMeter],
            ['y0', 'false_northing', toMeter],
            ['long0', 'central_meridian', d2r],
            ['lat0', 'latitude_of_origin', d2r],
            ['lat0', 'standard_parallel_1', d2r],
            ['lat1', 'standard_parallel_1', d2r],
            ['lat2', 'standard_parallel_2', d2r],
            ['azimuth', 'Azimuth'],
            ['alpha', 'azimuth', d2r],
            ['srsCode', 'name']
        ];
        list.forEach(renamer);
        if (!wkt.long0 && wkt.longc && (wkt.projName === 'Albers_Conic_Equal_Area' || wkt.projName === 'Lambert_Azimuthal_Equal_Area')) {
            wkt.long0 = wkt.longc;
        }
        if (!wkt.lat_ts && wkt.lat1 && (wkt.projName === 'Stereographic_South_Pole' || wkt.projName === 'Polar Stereographic (variant B)')) {
            wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90);
            wkt.lat_ts = wkt.lat1;
        }
    }
    function default_1(wkt) {
        var lisp = parser_1.default(wkt);
        var type = lisp.shift();
        var name = lisp.shift();
        lisp.unshift(['name', name]);
        lisp.unshift(['type', type]);
        var obj = {};
        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(81) /* ./projections/merc */);
    const longlat_1 = tslib_1.__importDefault(require(87) /* ./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(82) /* ../common/msfnz */);
    const adjust_lon_1 = tslib_1.__importDefault(require(83) /* ../common/adjust_lon */);
    const tsfnz_1 = tslib_1.__importDefault(require(85) /* ../common/tsfnz */);
    const phi2z_1 = tslib_1.__importDefault(require(86) /* ../common/phi2z */);
    const values_1 = require(72) /* ../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 = 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 * 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 = tsfnz_1.default(this.e, lat, sinphi);
                x = this.x0 + this.a * this.k0 * 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 = phi2z_1.default(this.e, ts);
            if (lat === -9999) {
                return null;
            }
        }
        lon = 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(72) /* ../constants/values */;
    const sign_1 = tslib_1.__importDefault(require(84) /* ./sign */);
    function default_1(x) {
        return (Math.abs(x) <= values_1.SPI) ? x : (x - (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(72) /* ../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(72) /* ../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(72) /* ./constants/values */;
    const Ellipsoid_1 = tslib_1.__importStar(require(89) /* ./constants/Ellipsoid */);
    const match_1 = tslib_1.__importDefault(require(75) /* ./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 = match_1.default(Ellipsoid_1.default, ellps);
            if (!ellipse) {
                ellipse = Ellipsoid_1.WGS84;
            }
            a = ellipse.a;
            b = ellipse.b;
            rf = ellipse.rf;
        }
        if (rf && !b) {
            b = (1.0 - 1.0 / rf) * a;
        }
        if (rf === 0 || Math.abs(a - b) < values_1.EPSLN) {
            sphere = true;
            b = a;
        }
        return {
            a: a,
            b: b,
            rf: rf,
            sphere: sphere
        };
    }
    exports.sphere = sphere;
},
/* proj4/lib/constants/Ellipsoid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var exports$1 = {};
    exports.default = exports$1;
    exports$1.MERIT = {
        a: 6378137.0,
        rf: 298.257,
        ellipseName: "MERIT 1983"
    };
    exports$1.SGS85 = {
        a: 6378136.0,
        rf: 298.257,
        ellipseName: "Soviet Geodetic System 85"
    };
    exports$1.GRS80 = {
        a: 6378137.0,
        rf: 298.257222101,
        ellipseName: "GRS 1980(IUGG, 1980)"
    };
    exports$1.IAU76 = {
        a: 6378140.0,
        rf: 298.257,
        ellipseName: "IAU 1976"
    };
    exports$1.airy = {
        a: 6377563.396,
        b: 6356256.910,
        ellipseName: "Airy 1830"
    };
    exports$1.APL4 = {
        a: 6378137,
        rf: 298.25,
        ellipseName: "Appl. Physics. 1965"
    };
    exports$1.NWL9D = {
        a: 6378145.0,
        rf: 298.25,
        ellipseName: "Naval Weapons Lab., 1965"
    };
    exports$1.mod_airy = {
        a: 6377340.189,
        b: 6356034.446,
        ellipseName: "Modified Airy"
    };
    exports$1.andrae = {
        a: 6377104.43,
        rf: 300.0,
        ellipseName: "Andrae 1876 (Den., Iclnd.)"
    };
    exports$1.aust_SA = {
        a: 6378160.0,
        rf: 298.25,
        ellipseName: "Australian Natl & S. Amer. 1969"
    };
    exports$1.GRS67 = {
        a: 6378160.0,
        rf: 298.2471674270,
        ellipseName: "GRS 67(IUGG 1967)"
    };
    exports$1.bessel = {
        a: 6377397.155,
        rf: 299.1528128,
        ellipseName: "Bessel 1841"
    };
    exports$1.bess_nam = {
        a: 6377483.865,
        rf: 299.1528128,
        ellipseName: "Bessel 1841 (Namibia)"
    };
    exports$1.clrk66 = {
        a: 6378206.4,
        b: 6356583.8,
        ellipseName: "Clarke 1866"
    };
    exports$1.clrk80 = {
        a: 6378249.145,
        rf: 293.4663,
        ellipseName: "Clarke 1880 mod."
    };
    exports$1.clrk58 = {
        a: 6378293.645208759,
        rf: 294.2606763692654,
        ellipseName: "Clarke 1858"
    };
    exports$1.CPM = {
        a: 6375738.7,
        rf: 334.29,
        ellipseName: "Comm. des Poids et Mesures 1799"
    };
    exports$1.delmbr = {
        a: 6376428.0,
        rf: 311.5,
        ellipseName: "Delambre 1810 (Belgium)"
    };
    exports$1.engelis = {
        a: 6378136.05,
        rf: 298.2566,
        ellipseName: "Engelis 1985"
    };
    exports$1.evrst30 = {
        a: 6377276.345,
        rf: 300.8017,
        ellipseName: "Everest 1830"
    };
    exports$1.evrst48 = {
        a: 6377304.063,
        rf: 300.8017,
        ellipseName: "Everest 1948"
    };
    exports$1.evrst56 = {
        a: 6377301.243,
        rf: 300.8017,
        ellipseName: "Everest 1956"
    };
    exports$1.evrst69 = {
        a: 6377295.664,
        rf: 300.8017,
        ellipseName: "Everest 1969"
    };
    exports$1.evrstSS = {
        a: 6377298.556,
        rf: 300.8017,
        ellipseName: "Everest (Sabah & Sarawak)"
    };
    exports$1.fschr60 = {
        a: 6378166.0,
        rf: 298.3,
        ellipseName: "Fischer (Mercury Datum) 1960"
    };
    exports$1.fschr60m = {
        a: 6378155.0,
        rf: 298.3,
        ellipseName: "Fischer 1960"
    };
    exports$1.fschr68 = {
        a: 6378150.0,
        rf: 298.3,
        ellipseName: "Fischer 1968"
    };
    exports$1.helmert = {
        a: 6378200.0,
        rf: 298.3,
        ellipseName: "Helmert 1906"
    };
    exports$1.hough = {
        a: 6378270.0,
        rf: 297.0,
        ellipseName: "Hough"
    };
    exports$1.intl = {
        a: 6378388.0,
        rf: 297.0,
        ellipseName: "International 1909 (Hayford)"
    };
    exports$1.kaula = {
        a: 6378163.0,
        rf: 298.24,
        ellipseName: "Kaula 1961"
    };
    exports$1.lerch = {
        a: 6378139.0,
        rf: 298.257,
        ellipseName: "Lerch 1979"
    };
    exports$1.mprts = {
        a: 6397300.0,
        rf: 191.0,
        ellipseName: "Maupertius 1738"
    };
    exports$1.new_intl = {
        a: 6378157.5,
        b: 6356772.2,
        ellipseName: "New International 1967"
    };
    exports$1.plessis = {
        a: 6376523.0,
        rf: 6355863.0,
        ellipseName: "Plessis 1817 (France)"
    };
    exports$1.krass = {
        a: 6378245.0,
        rf: 298.3,
        ellipseName: "Krassovsky, 1942"
    };
    exports$1.SEasia = {
        a: 6378155.0,
        b: 6356773.3205,
        ellipseName: "Southeast Asia"
    };
    exports$1.walbeck = {
        a: 6376896.0,
        b: 6355834.8467,
        ellipseName: "Walbeck"
    };
    exports$1.WGS60 = {
        a: 6378165.0,
        rf: 298.3,
        ellipseName: "WGS 60"
    };
    exports$1.WGS66 = {
        a: 6378145.0,
        rf: 298.25,
        ellipseName: "WGS 66"
    };
    exports$1.WGS7 = {
        a: 6378135.0,
        rf: 298.26,
        ellipseName: "WGS 72"
    };
    exports.WGS84 = exports$1.WGS84 = {
        a: 6378137.0,
        rf: 298.257223563,
        ellipseName: "WGS 84"
    };
    exports$1.sphere = {
        a: 6370997.0,
        b: 6370997.0,
        ellipseName: "Normal Sphere (r=6370997)"
    };
},
/* proj4/lib/constants/Datum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var exports$1 = {};
    exports.default = exports$1;
    exports$1.wgs84 = {
        towgs84: "0,0,0",
        ellipse: "WGS84",
        datumName: "WGS84"
    };
    exports$1.ch1903 = {
        towgs84: "674.374,15.056,405.346",
        ellipse: "bessel",
        datumName: "swiss"
    };
    exports$1.ggrs87 = {
        towgs84: "-199.87,74.79,246.62",
        ellipse: "GRS80",
        datumName: "Greek_Geodetic_Reference_System_1987"
    };
    exports$1.nad83 = {
        towgs84: "0,0,0",
        ellipse: "GRS80",
        datumName: "North_American_Datum_1983"
    };
    exports$1.nad27 = {
        nadgrids: "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",
        ellipse: "clrk66",
        datumName: "North_American_Datum_1927"
    };
    exports$1.potsdam = {
        towgs84: "606.0,23.0,413.0",
        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: "653.0,-212.0,449.0",
        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(72) /* ./constants/values */;
    function datum(datumCode, datum_params, a, b, es, ep2) {
        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;
                }
            }
        }
        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/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(72) /* ./constants/values */;
    const datum_transform_1 = tslib_1.__importDefault(require(93) /* ./datum_transform */);
    const adjust_axis_1 = tslib_1.__importDefault(require(95) /* ./adjust_axis */);
    const Proj_1 = tslib_1.__importDefault(require(67) /* ./Proj */);
    const toPoint_1 = tslib_1.__importDefault(require(96) /* ./common/toPoint */);
    const checkSanity_1 = tslib_1.__importDefault(require(97) /* ./checkSanity */);
    function checkNotWGS(source, dest) {
        return ((source.datum.datum_type === values_1.PJD_3PARAM || source.datum.datum_type === values_1.PJD_7PARAM) && dest.datumCode !== 'WGS84') || ((dest.datum.datum_type === values_1.PJD_3PARAM || dest.datum.datum_type === values_1.PJD_7PARAM) && source.datumCode !== 'WGS84');
    }
    function transform(source, dest, point) {
        var wgs84;
        if (Array.isArray(point)) {
            point = toPoint_1.default(point);
        }
        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);
            source = wgs84;
        }
        // DGR, 2010/11/12
        if (source.axis !== 'enu') {
            point = 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 = datum_transform_1.default(source.datum, dest.datum, point);
        // 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 (dest.axis !== 'enu') {
            return adjust_axis_1.default(dest, true, point);
        }
        return point;
    }
    exports.default = transform;
},
/* proj4/lib/datum_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const values_1 = require(72) /* ./constants/values */;
    const datumUtils_1 = require(94) /* ./datumUtils */;
    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 (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.
        // 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 = datumUtils_1.geodeticToGeocentric(point, source.es, source.a);
        // Convert between datums
        if (checkParams(source.datum_type)) {
            point = datumUtils_1.geocentricToWgs84(point, source.datum_type, source.datum_params);
        }
        if (checkParams(dest.datum_type)) {
            point = datumUtils_1.geocentricFromWgs84(point, dest.datum_type, dest.datum_params);
        }
        return datumUtils_1.geocentricToGeodetic(point, dest.es, dest.a, dest.b);
    }
    exports.default = default_1;
},
/* proj4/lib/datumUtils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const values_1 = require(72) /* ./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/glyphs/glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const bbox = tslib_1.__importStar(require(99) /* ../../core/util/bbox */);
    const visuals = tslib_1.__importStar(require(45) /* ../../core/visuals */);
    const view_1 = require(42) /* ../../core/view */;
    const model_1 = require(53) /* ../../model */;
    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(100) /* ../../core/util/ragged_array */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const eq_1 = require(26) /* ../../core/util/eq */;
    const spatial_1 = require(101) /* ../../core/util/spatial */;
    const factor_range_1 = require(104) /* ../ranges/factor_range */;
    const selection_1 = require(59) /* ../selections/selection */;
    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();
        }
        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 { _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);
        }
        request_render() {
            this.parent.request_render();
        }
        get canvas() {
            return this.renderer.parent.canvas_view;
        }
        render(ctx, indices, data) {
            var _a;
            if (this.glglyph != null) {
                this.renderer.needs_webgl_blit = this.glglyph.render(ctx, indices, (_a = this.base) !== null && _a !== void 0 ? _a : this);
                if (this.renderer.needs_webgl_blit)
                    return;
            }
            ctx.beginPath();
            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;
            }
        }
        /** @deprecated */
        scenterx(i, sx, sy) {
            return this.scenterxy(i, sx, sy)[0];
        }
        /** @deprecated */
        scentery(i, sx, sy) {
            return this.scenterxy(i, sx, sy)[1];
        }
        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)
                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, types_2.isString(prop) ? prop : prop.attr, Object.assign({ configurable: true, enumerable: true }, descriptor));
        }
        set_visuals(source, indices) {
            var _a;
            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 && 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();
            }
            (_a = this.glglyph) === null || _a === void 0 ? void 0 : _a.set_visuals_changed();
        }
        set_data(source, indices, indices_to_update) {
            var _a;
            const { x_range, y_range } = 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_range : y_range;
                    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 : 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
            (_a = this.glglyph) === null || _a === void 0 ? void 0 : _a.set_data_changed();
            this.index_data();
        }
        _set_data(_indices) { }
        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 _a;
            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();
            (_a = this.glglyph) === null || _a === void 0 ? void 0 : _a.set_data_changed();
        }
        // 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;
    Glyph.__name__ = "Glyph";
},
/* core/util/bbox.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(24) /* ../types */;
    const eq_1 = require(26) /* ./eq */;
    const { min, max } = 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 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) {
            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 (!(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))
                    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;
            }
        }
        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 left() { return this.x0; }
        get top() { return this.y0; }
        get right() { return this.x1; }
        get bottom() { return this.y1; }
        get p0() { return [this.x0, this.y0]; }
        get p1() { return [this.x1, 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 h_range() { return { start: this.x0, end: this.x1 }; }
        get v_range() { return { start: this.y0, end: this.y1 }; }
        get ranges() { return [this.h_range, this.v_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; }
        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 });
        }
        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,
            });
        }
        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 xview() {
            return {
                compute: (x) => {
                    return this.left + x;
                },
                v_compute: (xx) => {
                    const _xx = new types_1.ScreenArray(xx.length);
                    const left = this.left;
                    for (let i = 0; i < xx.length; i++) {
                        _xx[i] = left + xx[i];
                    }
                    return _xx;
                },
            };
        }
        get yview() {
            return {
                compute: (y) => {
                    return this.bottom - y;
                },
                v_compute: (yy) => {
                    const _yy = new types_1.ScreenArray(yy.length);
                    const bottom = this.bottom;
                    for (let i = 0; i < yy.length; i++) {
                        _yy[i] = bottom - yy[i];
                    }
                    return _yy;
                },
            };
        }
    }
    exports.BBox = BBox;
    BBox.__name__ = "BBox";
},
/* core/util/ragged_array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(26) /* ./eq */;
    const assert_1 = require(11) /* ./assert */;
    class RaggedArray {
        constructor(offsets, array) {
            this.offsets = offsets;
            this.array = array;
        }
        [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) {
            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[Symbol.toStringTag] = "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(102) /* flatbush */);
    const types_1 = require(24) /* ../types */;
    const bbox_1 = require(99) /* ./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 {
        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
                    if (maxX < this._boxes[pos + 0])
                        continue; // maxX < nodeMinX
                    if (maxY < this._boxes[pos + 1])
                        continue; // maxY < nodeMinY
                    if (minX > this._boxes[pos + 2])
                        continue; // minX > nodeMaxX
                    if (minY > this._boxes[pos + 3])
                        continue; // minY > nodeMaxY
                    if (nodeIndex < this.numItems * 4) {
                        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(x0, y0, x1, y1) {
            var _a;
            (_a = this.index) === null || _a === void 0 ? void 0 : _a.add(x0, y0, x1, y1);
        }
        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 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 = bbox_1.empty();
            for (const i of this.indices(rect)) {
                const boxes = this.index._boxes;
                const x1 = boxes[4 * i + 0];
                const y1 = boxes[4 * i + 1];
                const x0 = boxes[4 * i + 2];
                const y0 = boxes[4 * i + 3];
                if (x0 < bounds.x0)
                    bounds.x0 = x0;
                if (x1 > bounds.x1)
                    bounds.x1 = x1;
                if (y0 < bounds.y0)
                    bounds.y0 = y0;
                if (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(103) /* flatqueue */);
    const ARRAY_TYPES = [
        Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
        Int32Array, Uint32Array, Float32Array, Float64Array
    ];
    const VERSION = 3; // serialized format version
    class Flatbush {
        static from(data) {
            if (!(data instanceof ArrayBuffer)) {
                throw new Error('Data must be an instance of ArrayBuffer.');
            }
            const [magic, versionAndType] = new Uint8Array(data, 0, 2);
            if (magic !== 0xfb) {
                throw new Error('Data does not appear to be in a Flatbush format.');
            }
            if (versionAndType >> 4 !== VERSION) {
                throw new Error(`Got v${versionAndType >> 4} data when expected v${VERSION}.`);
            }
            const [nodeSize] = new Uint16Array(data, 2, 1);
            const [numItems] = new Uint32Array(data, 4, 1);
            return new Flatbush(numItems, nodeSize, ARRAY_TYPES[versionAndType & 0x0f], data);
        }
        constructor(numItems, nodeSize = 16, ArrayType = Float64Array, data) {
            if (numItems === undefined)
                throw new Error('Missing required argument: numItems.');
            if (isNaN(numItems) || numItems <= 0)
                throw new Error(`Unpexpected numItems value: ${numItems}.`);
            this.numItems = +numItems;
            this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
            // calculate the total number of nodes in the R-tree to allocate space for
            // and the index of each tree level (used in search later)
            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 || Float64Array;
            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}.`);
            }
            if (data && (data instanceof ArrayBuffer)) {
                this.data = data;
                this._boxes = new this.ArrayType(this.data, 8, numNodes * 4);
                this._indices = new this.IndexArrayType(this.data, 8 + nodesByteSize, numNodes);
                this._pos = numNodes * 4;
                this.minX = this._boxes[this._pos - 4];
                this.minY = this._boxes[this._pos - 3];
                this.maxX = this._boxes[this._pos - 2];
                this.maxY = this._boxes[this._pos - 1];
            }
            else {
                this.data = new ArrayBuffer(8 + nodesByteSize + numNodes * this.IndexArrayType.BYTES_PER_ELEMENT);
                this._boxes = new this.ArrayType(this.data, 8, numNodes * 4);
                this._indices = new this.IndexArrayType(this.data, 8 + nodesByteSize, numNodes);
                this._pos = 0;
                this.minX = Infinity;
                this.minY = Infinity;
                this.maxX = -Infinity;
                this.maxY = -Infinity;
                new Uint8Array(this.data, 0, 2).set([0xfb, (VERSION << 4) + arrayTypeIndex]);
                new Uint16Array(this.data, 2, 1)[0] = nodeSize;
                new Uint32Array(this.data, 4, 1)[0] = numItems;
            }
            // a priority queue for k-nearest-neighbors queries
            this._queue = new flatqueue_1.default();
        }
        add(minX, minY, maxX, maxY) {
            const index = this._pos >> 2;
            this._indices[index] = index;
            this._boxes[this._pos++] = minX;
            this._boxes[this._pos++] = minY;
            this._boxes[this._pos++] = maxX;
            this._boxes[this._pos++] = maxY;
            if (minX < this.minX)
                this.minX = minX;
            if (minY < this.minY)
                this.minY = minY;
            if (maxX > this.maxX)
                this.maxX = maxX;
            if (maxY > this.maxY)
                this.maxY = maxY;
            return index;
        }
        finish() {
            if (this._pos >> 2 !== this.numItems) {
                throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
            }
            if (this.numItems <= this.nodeSize) {
                // only one node, skip sorting and just fill the root box
                this._boxes[this._pos++] = this.minX;
                this._boxes[this._pos++] = this.minY;
                this._boxes[this._pos++] = this.maxX;
                this._boxes[this._pos++] = this.maxY;
                return;
            }
            const width = this.maxX - this.minX;
            const height = this.maxY - this.minY;
            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; i < this.numItems; i++) {
                let pos = 4 * i;
                const minX = this._boxes[pos++];
                const minY = this._boxes[pos++];
                const maxX = this._boxes[pos++];
                const maxY = this._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, this._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 = Infinity;
                    let nodeMinY = Infinity;
                    let nodeMaxX = -Infinity;
                    let nodeMaxY = -Infinity;
                    for (let i = 0; i < this.nodeSize && pos < end; i++) {
                        nodeMinX = Math.min(nodeMinX, this._boxes[pos++]);
                        nodeMinY = Math.min(nodeMinY, this._boxes[pos++]);
                        nodeMaxX = Math.max(nodeMaxX, this._boxes[pos++]);
                        nodeMaxY = Math.max(nodeMaxY, this._boxes[pos++]);
                    }
                    // add the new node to the tree data
                    this._indices[this._pos >> 2] = nodeIndex;
                    this._boxes[this._pos++] = nodeMinX;
                    this._boxes[this._pos++] = nodeMinY;
                    this._boxes[this._pos++] = nodeMaxX;
                    this._boxes[this._pos++] = nodeMaxY;
                }
            }
        }
        search(minX, minY, maxX, maxY, filterFn) {
            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 = [];
            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
                    if (maxX < this._boxes[pos])
                        continue; // maxX < nodeMinX
                    if (maxY < this._boxes[pos + 1])
                        continue; // maxY < nodeMinY
                    if (minX > this._boxes[pos + 2])
                        continue; // minX > nodeMaxX
                    if (minY > this._boxes[pos + 3])
                        continue; // minY > nodeMaxY
                    if (nodeIndex < this.numItems * 4) {
                        if (filterFn === undefined || filterFn(index)) {
                            results.push(index); // leaf item
                        }
                    }
                    else {
                        queue.push(index); // node; add it to the search queue
                    }
                }
                nodeIndex = queue.pop();
            }
            return results;
        }
        neighbors(x, y, maxResults = Infinity, maxDistance = Infinity, filterFn) {
            if (this._pos !== this._boxes.length) {
                throw new Error('Data not yet indexed - call index.finish().');
            }
            let nodeIndex = this._boxes.length - 4;
            const q = this._queue;
            const results = [];
            const maxDistSquared = maxDistance * maxDistance;
            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 (nodeIndex < this.numItems * 4) { // leaf node
                        if (filterFn === undefined || filterFn(index)) {
                            // put a negative index if it's an item rather than a node, to recognize later
                            q.push(-index - 1, dist);
                        }
                    }
                    else {
                        q.push(index, dist);
                    }
                }
                // pop items from the queue
                while (q.length && q.peek() < 0) {
                    const dist = q.peekValue();
                    if (dist > maxDistSquared) {
                        q.clear();
                        return results;
                    }
                    results.push(-q.pop() - 1);
                    if (results.length === maxResults) {
                        q.clear();
                        return results;
                    }
                }
                nodeIndex = q.pop();
            }
            q.clear();
            return results;
        }
    }
    exports.default = Flatbush;
    function axisDist(k, min, max) {
        return k < min ? min - k : k <= max ? 0 : k - max;
    }
    // binary search for the first value in the array bigger than the given
    function upperBound(value, arr) {
        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
    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
    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)
    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.mjs */ 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++;
            this.ids[pos] = id;
            this.values[pos] = value;
            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];
        }
    }
    exports.default = FlatQueue;
},
/* models/ranges/factor_range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const range_1 = require(105) /* ./range */;
    const enums_1 = require(20) /* ../../core/enums */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const types_1 = require(24) /* ../../core/types */;
    const array_1 = require(9) /* ../../core/util/array */;
    const types_2 = require(8) /* ../../core/util/types */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    exports.Factor = kinds_1.Or(kinds_1.String, kinds_1.Tuple(kinds_1.String, kinds_1.String), kinds_1.Tuple(kinds_1.String, kinds_1.String, kinds_1.String));
    exports.FactorSeq = kinds_1.Or(kinds_1.Array(kinds_1.String), kinds_1.Array(kinds_1.Tuple(kinds_1.String, kinds_1.String)), kinds_1.Array(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 _a;
        const mapping = new Map();
        const tops = new Map();
        for (const [f0, f1] of factors) {
            const top = (_a = tops.get(f0)) !== null && _a !== void 0 ? _a : [];
            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 = 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 _a;
        const mapping = new Map();
        const tops = new Map();
        for (const [f0, f1, f2] of factors) {
            const top = (_a = tops.get(f0)) !== null && _a !== void 0 ? _a : [];
            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 = 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);
        }
        static init_FactorRange() {
            this.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],
                end: [Number],
            }));
            this.internal(({ Number, String, Array, Tuple, Nullable }) => ({
                levels: [Number],
                mids: [Nullable(Array(Tuple(String, String))), null],
                tops: [Nullable(Array(String)), null],
            }));
        }
        get min() {
            return this.start;
        }
        get max() {
            return this.end;
        }
        initialize() {
            super.initialize();
            this._init(true);
        }
        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(false);
            this.change.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;
                }
                default:
                    assert_1.unreachable();
            }
        }
        // convert a string factor into a synthetic coordinate
        synthetic(x) {
            if (types_2.isNumber(x))
                return x;
            if (types_2.isString(x))
                return this._lookup([x]);
            let offset = 0;
            const off = x[x.length - 1];
            if (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(silent) {
            const { levels, mapping, tops, mids, inside_padding } = (() => {
                if (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 (array_1.every(this.factors, (x) => types_2.isArray(x) && x.length == 2 && types_2.isString(x[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 (array_1.every(this.factors, (x) => types_2.isArray(x) && x.length == 3 && types_2.isString(x[0]) && types_2.isString(x[1]) && 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
                    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 });
            if (this.bounds == "auto")
                this.setv({ bounds: [start, end] }, { silent: true });
        }
    }
    exports.FactorRange = FactorRange;
    FactorRange.__name__ = "FactorRange";
    FactorRange.init_FactorRange();
},
/* models/ranges/range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    class Range extends model_1.Model {
        constructor(attrs) {
            super(attrs);
            this.have_updated_interactively = false;
        }
        static init_Range() {
            this.define(({ Number, Tuple, Or, Auto, Nullable }) => ({
                bounds: [Nullable(Or(Tuple(Nullable(Number), Nullable(Number)), Auto)), null],
                min_interval: [Nullable(Number), null],
                max_interval: [Nullable(Number), null],
            }));
            this.internal(({ Array, AnyRef }) => ({
                plots: [Array(AnyRef()), []],
            }));
        }
        get is_reversed() {
            return this.start > this.end;
        }
        get is_valid() {
            return isFinite(this.min) && isFinite(this.max);
        }
    }
    exports.Range = Range;
    Range.__name__ = "Range";
    Range.init_Range();
},
/* models/glyphs/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const hittest = tslib_1.__importStar(require(107) /* ../../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);
        if (visuals.line.doit) {
            visuals.line.set_value(ctx);
            ctx.stroke();
        }
        ctx.restore();
    }
    exports.generic_line_scalar_legend = generic_line_scalar_legend;
    function generic_line_vector_legend(visuals, ctx, { x0, x1, y0, y1 }, index) {
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x0, (y0 + y1) / 2);
        ctx.lineTo(x1, (y0 + y1) / 2);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, index);
            ctx.stroke();
        }
        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);
        if (visuals.fill.doit) {
            visuals.fill.set_value(ctx);
            ctx.fill();
        }
        if ((_a = visuals.hatch) === null || _a === void 0 ? void 0 : _a.doit) {
            visuals.hatch.set_value(ctx);
            ctx.fill();
        }
        if ((_b = visuals.line) === null || _b === void 0 ? void 0 : _b.doit) {
            visuals.line.set_value(ctx);
            ctx.stroke();
        }
    }
    exports.generic_area_scalar_legend = generic_area_scalar_legend;
    function generic_area_vector_legend(visuals, ctx, { x0, x1, y0, y1 }, index) {
        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);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, index);
            ctx.fill();
        }
        if ((_a = visuals.hatch) === null || _a === void 0 ? void 0 : _a.doit) {
            visuals.hatch.set_vectorize(ctx, index);
            ctx.fill();
        }
        if ((_b = visuals.line) === null || _b === void 0 ? void 0 : _b.doit) {
            visuals.line.set_vectorize(ctx, index);
            ctx.stroke();
        }
    }
    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/webgl/line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const utils_1 = require(109) /* ./utils */;
    const base_1 = require(113) /* ./base */;
    const line_vert_1 = tslib_1.__importDefault(require(114) /* ./line.vert */);
    const line_frag_1 = tslib_1.__importDefault(require(115) /* ./line.frag */);
    const color_1 = require(22) /* ../../../core/util/color */;
    const line_1 = require(46) /* ../../../core/visuals/line */;
    class DashAtlas {
        constructor(gl) {
            this._atlas = new Map();
            this._width = 256;
            this._height = 256;
            // Init texture
            this.tex = new utils_1.Texture2d(gl);
            this.tex.set_wrapping(gl.REPEAT, gl.REPEAT);
            this.tex.set_interpolation(gl.NEAREST, gl.NEAREST);
            this.tex.set_size([this._width, this._height], gl.RGBA);
            this.tex.set_data([0, 0], [this._width, this._height], new Uint8Array(4 * this._width * this._height));
            // Init with solid line (index 0 is reserved for this)
            this.get_atlas_data([1]);
        }
        get_atlas_data(pattern) {
            const key = pattern.join("-");
            let atlas_data = this._atlas.get(key);
            if (atlas_data == null) {
                const [data, period] = this.make_pattern(pattern);
                const index = this._atlas.size;
                this.tex.set_data([0, index], [this._width, 1], new Uint8Array(data.map((x) => x + 10)));
                atlas_data = [index / this._height, period];
                this._atlas.set(key, atlas_data);
            }
            return atlas_data;
        }
        make_pattern(pattern) {
            // A pattern is defined as on/off sequence of segments
            // It must be a multiple of 2
            if (pattern.length > 1 && pattern.length % 2) {
                pattern = pattern.concat(pattern);
            }
            // Period is sum of elements
            let period = 0;
            for (const v of pattern) {
                period += v;
            }
            // Find all start and end of on-segment only
            const C = [];
            let c = 0;
            for (let i = 0, end = pattern.length + 2; i < end; i += 2) {
                const a = Math.max(0.0001, pattern[i % pattern.length]);
                const b = Math.max(0.0001, pattern[(i + 1) % pattern.length]);
                C.push(c, c + a);
                c += a + b;
            }
            // Build pattern
            const n = this._width;
            const Z = new Float32Array(n * 4);
            for (let i = 0, end = n; i < end; i++) {
                let dash_end, dash_start, dash_type;
                const x = (period * i) / (n - 1);
                // get index at min - index = np.argmin(abs(C-(x)))
                let index = 0;
                let val_at_index = 1e16;
                for (let j = 0, endj = C.length; j < endj; j++) {
                    const val = Math.abs(C[j] - x);
                    if (val < val_at_index) {
                        index = j;
                        val_at_index = val;
                    }
                }
                if ((index % 2) === 0) {
                    dash_type = (x <= C[index]) ? +1 : 0;
                    dash_start = C[index];
                    dash_end = C[index + 1];
                }
                else {
                    dash_type = (x > C[index]) ? -1 : 0;
                    dash_start = C[index - 1];
                    dash_end = C[index];
                }
                Z[(i * 4) + 0] = C[index];
                Z[(i * 4) + 1] = dash_type;
                Z[(i * 4) + 2] = dash_start;
                Z[(i * 4) + 3] = dash_end;
            }
            return [Z, period];
        }
    }
    DashAtlas.__name__ = "DashAtlas";
    const joins = { miter: 0, round: 1, bevel: 2 };
    const caps = {
        '': 0, none: 0, '.': 0,
        round: 1, ')': 1, '(': 1, o: 1,
        'triangle in': 2, '<': 2,
        'triangle out': 3, '>': 3,
        square: 4, '[': 4, ']': 4, '=': 4,
        butt: 5, '|': 5,
    };
    class LineGL extends base_1.BaseGLGlyph {
        constructor(gl, glyph) {
            super(gl, glyph);
            this.glyph = glyph;
            this._scale_aspect = 0; // keep track, so we know when we need to update segment data
            const vert = line_vert_1.default;
            const frag = line_frag_1.default;
            // The program
            this.prog = new utils_1.Program(gl);
            this.prog.set_shaders(vert, frag);
            this.index_buffer = new utils_1.IndexBuffer(gl);
            // Buffers
            this.vbo_position = new utils_1.VertexBuffer(gl);
            this.vbo_tangents = new utils_1.VertexBuffer(gl);
            this.vbo_segment = new utils_1.VertexBuffer(gl);
            this.vbo_angles = new utils_1.VertexBuffer(gl);
            this.vbo_texcoord = new utils_1.VertexBuffer(gl);
            // Dash atlas
            this.dash_atlas = new DashAtlas(gl);
        }
        draw(indices, mainGlyph, trans) {
            const mainGlGlyph = mainGlyph.glglyph;
            if (mainGlGlyph.data_changed) {
                mainGlGlyph._set_data();
                mainGlGlyph.data_changed = false;
            }
            if (this.visuals_changed) {
                this._set_visuals();
                this.visuals_changed = false;
            }
            mainGlGlyph._update_scale(1, 1);
            this._scale_aspect = 1;
            // Select buffers from main glyph
            // (which may be this glyph but maybe not if this is a (non)selection glyph)
            this.prog.set_attribute('a_position', 'vec2', mainGlGlyph.vbo_position);
            this.prog.set_attribute('a_tangents', 'vec4', mainGlGlyph.vbo_tangents);
            this.prog.set_attribute('a_segment', 'vec2', mainGlGlyph.vbo_segment);
            this.prog.set_attribute('a_angles', 'vec2', mainGlGlyph.vbo_angles);
            this.prog.set_attribute('a_texcoord', 'vec2', mainGlGlyph.vbo_texcoord);
            //
            this.prog.set_uniform('u_length', 'float', [mainGlGlyph.cumsum]);
            this.prog.set_texture('u_dash_atlas', this.dash_atlas.tex);
            // Handle transformation to device coordinates
            this.prog.set_uniform('u_pixel_ratio', 'float', [trans.pixel_ratio]);
            this.prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height]);
            this.prog.set_uniform('u_scale_aspect', 'vec2', [1, 1]);
            this.prog.set_uniform('u_scale_length', 'float', [Math.sqrt(2)]);
            this.I_triangles = mainGlGlyph.I_triangles;
            if (this.I_triangles.length < 65535) {
                // Data is small enough to draw in one pass
                this.index_buffer.set_size(this.I_triangles.length * 2);
                this.index_buffer.set_data(0, new Uint16Array(this.I_triangles));
                this.prog.draw(this.gl.TRIANGLES, this.index_buffer);
                // @prog.draw(@gl.LINE_STRIP, @index_buffer)  # Use this to draw the line skeleton
            }
            else {
                // Work around the limit that the indexbuffer must be uint16. We draw in chunks.
                // First collect indices in chunks
                indices = Array.from(this.I_triangles);
                const nvertices = this.I_triangles.length;
                const chunksize = 64008; // 65536 max. 64008 is divisible by 12
                const chunks = [];
                for (let i = 0, end = Math.ceil(nvertices / chunksize); i < end; i++) {
                    chunks.push([]);
                }
                for (let i = 0, end = indices.length; i < end; i++) {
                    const uint16_index = indices[i] % chunksize;
                    const chunk = Math.floor(indices[i] / chunksize);
                    chunks[chunk].push(uint16_index);
                }
                // Then draw each chunk
                for (let chunk = 0, end = chunks.length; chunk < end; chunk++) {
                    const these_indices = new Uint16Array(chunks[chunk]);
                    const offset = chunk * chunksize * 4;
                    if (these_indices.length === 0) {
                        continue;
                    }
                    this.prog.set_attribute('a_position', 'vec2', mainGlGlyph.vbo_position, 0, offset * 2);
                    this.prog.set_attribute('a_tangents', 'vec4', mainGlGlyph.vbo_tangents, 0, offset * 4);
                    this.prog.set_attribute('a_segment', 'vec2', mainGlGlyph.vbo_segment, 0, offset * 2);
                    this.prog.set_attribute('a_angles', 'vec2', mainGlGlyph.vbo_angles, 0, offset * 2);
                    this.prog.set_attribute('a_texcoord', 'vec2', mainGlGlyph.vbo_texcoord, 0, offset * 2);
                    // The actual drawing
                    this.index_buffer.set_size(these_indices.length * 2);
                    this.index_buffer.set_data(0, these_indices);
                    this.prog.draw(this.gl.TRIANGLES, this.index_buffer);
                }
            }
        }
        _set_data() {
            this._bake();
            this.vbo_position.set_size(this.V_position.length * 4);
            this.vbo_position.set_data(0, this.V_position);
            this.vbo_tangents.set_size(this.V_tangents.length * 4);
            this.vbo_tangents.set_data(0, this.V_tangents);
            this.vbo_angles.set_size(this.V_angles.length * 4);
            this.vbo_angles.set_data(0, this.V_angles);
            this.vbo_texcoord.set_size(this.V_texcoord.length * 4);
            this.vbo_texcoord.set_data(0, this.V_texcoord);
        }
        _set_visuals() {
            const { line_color, line_alpha, line_width, line_cap, line_join, line_dash, line_dash_offset } = this.glyph.visuals.line;
            const [r, g, b, a] = color_1.color2rgba(line_color.value, line_alpha.value);
            const width = line_width.value;
            const cap = caps[line_cap.value];
            const join = joins[line_join.value];
            this.prog.set_uniform('u_color', 'vec4', [r / 255, g / 255, b / 255, a / 255]);
            this.prog.set_uniform('u_linewidth', 'float', [width]);
            this.prog.set_uniform('u_antialias', 'float', [0.9]); // Smaller aa-region to obtain crisper images
            this.prog.set_uniform('u_linecaps', 'vec2', [cap, cap]);
            this.prog.set_uniform('u_linejoin', 'float', [join]);
            this.prog.set_uniform('u_miter_limit', 'float', [10.0]); // 10 should be a good value
            // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit
            const dash_pattern = line_1.resolve_line_dash(line_dash.value);
            let dash_index = 0;
            let dash_period = 1;
            if (dash_pattern.length) {
                [dash_index, dash_period] = this.dash_atlas.get_atlas_data(dash_pattern);
            }
            this.prog.set_uniform('u_dash_index', 'float', [dash_index]); // 0 means solid line
            this.prog.set_uniform('u_dash_phase', 'float', [line_dash_offset.value]);
            this.prog.set_uniform('u_dash_period', 'float', [dash_period]);
            this.prog.set_uniform('u_dash_caps', 'vec2', [cap, cap]);
            this.prog.set_uniform('u_closed', 'float', [0]); // We dont do closed lines
        }
        _bake() {
            // This is what you get if you port 50 lines of numpy code to JS.
            // V_segment is handled in another method, because it depends on the aspect
            // ratio of the scale (The original paper/code assumed isotropic scaling).
            //
            // Buffer dtype from the Python implementation:
            //
            // self.vtype = np.dtype( [('a_position', 'f4', 2),
            //                         ('a_segment',  'f4', 2),
            //                         ('a_angles',   'f4', 2),
            //                         ('a_tangents', 'f4', 4),
            //                         ('a_texcoord', 'f4', 2) ])
            // Init array of implicit shape nx2
            let I, T, V_angles2, V_position2, V_tangents2, V_texcoord2, Vp, Vt;
            const n = this.nvertices;
            const sx = this.glyph.sx;
            const sy = this.glyph.sy;
            // Init vertex data
            const V_position = (Vp = new Float32Array(n * 2));
            //V_segment = new Float32Array(n*2)  # Done later
            const V_angles = new Float32Array(n * 2);
            const V_tangents = (Vt = new Float32Array(n * 4)); // mind the 4!
            // Position, replacing non-finite numbers with zeros
            for (let i = 0, end = n; i < end; i++) {
                V_position[(i * 2) + 0] = isFinite(sx[i]) ? sx[i] : 0.0;
                V_position[(i * 2) + 1] = isFinite(sy[i]) ? sy[i] : 0.0;
            }
            // Tangents & norms (need tangents to calculate segments based on scale)
            this.tangents = (T = new Float32Array((n * 2) - 2));
            for (let i = 0, end = n - 1; i < end; i++) {
                T[(i * 2) + 0] = Vp[((i + 1) * 2) + 0] - Vp[(i * 2) + 0];
                T[(i * 2) + 1] = Vp[((i + 1) * 2) + 1] - Vp[(i * 2) + 1];
            }
            for (let i = 0, end = n - 1; i < end; i++) {
                // V['a_tangents'][+1:, :2] = T
                V_tangents[((i + 1) * 4) + 0] = T[(i * 2) + 0];
                V_tangents[((i + 1) * 4) + 1] = T[(i * 2) + 1];
                // V['a_tangents'][:-1, 2:] = T
                V_tangents[(i * 4) + 2] = T[(i * 2) + 0];
                V_tangents[(i * 4) + 3] = T[(i * 2) + 1];
            }
            // V['a_tangents'][0  , :2] = T[0]
            V_tangents[(0 * 4) + 0] = T[0];
            V_tangents[(0 * 4) + 1] = T[1];
            // V['a_tangents'][ -1, 2:] = T[-1]
            V_tangents[((n - 1) * 4) + 2] = T[((n - 2) * 2) + 0];
            V_tangents[((n - 1) * 4) + 3] = T[((n - 2) * 2) + 1];
            // Angles
            const A = new Float32Array(n);
            for (let i = 0, end = n; i < end; i++) {
                A[i] = Math.atan2((Vt[(i * 4) + 0] * Vt[(i * 4) + 3]) - (Vt[(i * 4) + 1] * Vt[(i * 4) + 2]), (Vt[(i * 4) + 0] * Vt[(i * 4) + 2]) + (Vt[(i * 4) + 1] * Vt[(i * 4) + 3]));
            }
            for (let i = 0, end = n - 1; i < end; i++) {
                V_angles[(i * 2) + 0] = A[i];
                V_angles[(i * 2) + 1] = A[i + 1];
            }
            // Position, non-finite numbers
            for (let i = 0, end = n; i < end; i++) {
                if (!isFinite(sx[i])) {
                    V_position[(i * 2) + 0] = sx[i];
                }
                if (!isFinite(sy[i])) {
                    V_position[(i * 2) + 1] = sy[i];
                }
            }
            // Step 1: A -- B -- C  =>  A -- B, B' -- C
            // Repeat our array 4 times
            const m = (4 * n) - 4;
            this.V_position = (V_position2 = new Float32Array(m * 2));
            this.V_angles = (V_angles2 = new Float32Array(m * 2));
            this.V_tangents = (V_tangents2 = new Float32Array(m * 4)); // mind the 4!
            this.V_texcoord = (V_texcoord2 = new Float32Array(m * 2));
            const o = 2;
            //
            // Arg, we really need an ndarray thing in JS :/
            for (let i = 0, end = n; i < end; i++) { // all nodes on the line
                for (let j = 0; j < 4; j++) { // the four quad vertices
                    for (let k = 0; k < 2; k++) { // xy
                        V_position2[((((i * 4) + j) - o) * 2) + k] = V_position[(i * 2) + k];
                        V_angles2[(((i * 4) + j) * 2) + k] = V_angles[(i * 2) + k];
                    } // no offset
                    for (let k = 0; k < 4; k++) {
                        V_tangents2[((((i * 4) + j) - o) * 4) + k] = V_tangents[(i * 4) + k];
                    }
                }
            }
            for (let i = 0, end = n; i < end; i++) {
                V_texcoord2[(((i * 4) + 0) * 2) + 0] = -1;
                V_texcoord2[(((i * 4) + 1) * 2) + 0] = -1;
                V_texcoord2[(((i * 4) + 2) * 2) + 0] = +1;
                V_texcoord2[(((i * 4) + 3) * 2) + 0] = +1;
                //
                V_texcoord2[(((i * 4) + 0) * 2) + 1] = -1;
                V_texcoord2[(((i * 4) + 1) * 2) + 1] = +1;
                V_texcoord2[(((i * 4) + 2) * 2) + 1] = -1;
                V_texcoord2[(((i * 4) + 3) * 2) + 1] = +1;
            }
            // Indices
            //I = np.resize( np.array([0,1,2,1,2,3], dtype=np.uint32), (n-1)*(2*3))
            //I += np.repeat( 4*np.arange(n-1), 6)
            const ni = (n - 1) * 6;
            this.I_triangles = (I = new Uint32Array(ni));
            // Order of indices is such that drawing as line_strip reveals the line skeleton
            // Might have implications on culling, if we ever turn that on.
            // Order in paper was: 0 1 2 1 2 3
            for (let i = 0, end = n; i < end; i++) {
                I[(i * 6) + 0] = 0 + (4 * i);
                I[(i * 6) + 1] = 1 + (4 * i);
                I[(i * 6) + 2] = 3 + (4 * i);
                I[(i * 6) + 3] = 2 + (4 * i);
                I[(i * 6) + 4] = 0 + (4 * i);
                I[(i * 6) + 5] = 3 + (4 * i);
            }
        }
        _update_scale(sx, sy) {
            // Update segment data and cumsum so the length along the line has the
            // scale aspect ratio in it. In the vertex shader we multiply with the
            // "isotropic part" of the scale.
            let V_segment2;
            const n = this.nvertices;
            const m = (4 * n) - 4;
            // Prepare arrays
            const T = this.tangents;
            const N = new Float32Array(n - 1);
            const V_segment = new Float32Array(n * 2); // Elements are initialized with 0
            this.V_segment = (V_segment2 = new Float32Array(m * 2));
            // Calculate vector lengths - with scale aspect ratio taken into account
            for (let i = 0, end = n - 1; i < end; i++) {
                N[i] = Math.sqrt((T[(i * 2) + 0] * sx) ** 2 + (T[(i * 2) + 1] * sy) ** 2);
            }
            // Calculate Segments
            let cumsum = 0;
            for (let i = 0, end = n - 1; i < end; i++) {
                cumsum += N[i];
                V_segment[((i + 1) * 2) + 0] = cumsum;
                V_segment[(i * 2) + 1] = cumsum;
            }
            // Upscale (same loop as in _bake())
            for (let i = 0, end = n; i < end; i++) {
                for (let j = 0; j < 4; j++) {
                    for (let k = 0; k < 2; k++) {
                        V_segment2[(((i * 4) + j) * 2) + k] = V_segment[(i * 2) + k];
                    }
                }
            }
            // Update
            this.cumsum = cumsum; // L[-1] in Nico's code
            this.vbo_segment.set_size(this.V_segment.length * 4);
            this.vbo_segment.set_data(0, this.V_segment);
        }
    }
    exports.LineGL = LineGL;
    LineGL.__name__ = "LineGL";
},
/* models/glyphs/webgl/utils/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var program_1 = require(110) /* ./program */;
    __esExport("Program", program_1.Program);
    var texture_1 = require(112) /* ./texture */;
    __esExport("Texture2d", texture_1.Texture2d);
    var buffer_1 = require(111) /* ./buffer */;
    __esExport("IndexBuffer", buffer_1.IndexBuffer);
    __esExport("VertexBuffer", buffer_1.VertexBuffer);
},
/* models/glyphs/webgl/utils/program.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const buffer_1 = require(111) /* ./buffer */;
    class Program {
        constructor(gl) {
            this.gl = gl;
            this.UTYPEMAP = {
                float: "uniform1fv",
                vec2: "uniform2fv",
                vec3: "uniform3fv",
                vec4: "uniform4fv",
                int: "uniform1iv",
                ivec2: "uniform2iv",
                ivec3: "uniform3iv",
                ivec4: "uniform4iv",
                bool: "uniform1iv",
                bvec2: "uniform2iv",
                bvec3: "uniform3iv",
                bvec4: "uniform4iv",
                mat2: "uniformMatrix2fv",
                mat3: "uniformMatrix3fv",
                mat4: "uniformMatrix4fv",
                sampler1D: "uniform1i",
                sampler2D: "uniform1i",
                sampler3D: "uniform1i",
            };
            this.ATYPEMAP = {
                float: "vertexAttrib1f",
                vec2: "vertexAttrib2f",
                vec3: "vertexAttrib3f",
                vec4: "vertexAttrib4f",
            };
            this.ATYPEINFO = {
                float: [1, 5126],
                vec2: [2, 5126],
                vec3: [3, 5126],
                vec4: [4, 5126],
                vec4_uint8: [4, 5121],
            };
            this._linked = false;
            this._validated = false;
            this._unset_variables = new Set();
            this._known_invalid = new Set();
            this._locations = new Map();
            this._samplers = new Map();
            this._attributes = new Map();
            this.handle = this.gl.createProgram();
        }
        delete() {
            this.gl.deleteProgram(this.handle);
        }
        activate() {
            this.gl.useProgram(this.handle);
        }
        deactivate() {
            this.gl.useProgram(0);
        }
        set_shaders(vert, frag) {
            // Set GLSL code for the vertex and fragment shader.
            //
            // This function takes care of setting the shading code and
            // compiling+linking it into a working program object that is ready
            // to use.
            //
            // Parameters
            // ----------
            // vert : str
            //     GLSL code for the vertex shader.
            // frag : str
            //     GLSL code for the fragment shader.
            const gl = this.gl;
            this._linked = false;
            const vert_handle = gl.createShader(gl.VERTEX_SHADER);
            const frag_handle = gl.createShader(gl.FRAGMENT_SHADER);
            const tmp = [
                [vert, vert_handle, "vertex"],
                [frag, frag_handle, "fragment"],
            ];
            for (const [code, handle, type] of tmp) {
                gl.shaderSource(handle, code);
                gl.compileShader(handle);
                const status = gl.getShaderParameter(handle, gl.COMPILE_STATUS);
                if (!status) {
                    const errors = gl.getShaderInfoLog(handle);
                    throw new Error(`errors in ${type} shader:\n${errors}`);
                }
            }
            gl.attachShader(this.handle, vert_handle);
            gl.attachShader(this.handle, frag_handle);
            gl.linkProgram(this.handle);
            if (!gl.getProgramParameter(this.handle, gl.LINK_STATUS)) {
                const logs = gl.getProgramInfoLog(this.handle);
                throw new Error(`Program link error:\n${logs}`);
            }
            this._unset_variables = this._get_active_attributes_and_uniforms();
            gl.detachShader(this.handle, vert_handle);
            gl.detachShader(this.handle, frag_handle);
            gl.deleteShader(vert_handle);
            gl.deleteShader(frag_handle);
            this._known_invalid.clear();
            this._linked = true;
        }
        _get_active_attributes_and_uniforms() {
            // Retrieve active attributes and uniforms to be able to check that
            // all uniforms/attributes are set by the user.
            const gl = this.gl;
            this._locations.clear();
            const regex = new RegExp("(\\w+)\\s*(\\[(\\d+)\\])\\s*");
            const cu = gl.getProgramParameter(this.handle, gl.ACTIVE_UNIFORMS);
            const ca = gl.getProgramParameter(this.handle, gl.ACTIVE_ATTRIBUTES);
            const attributes = [];
            const uniforms = [];
            const stub5_seq = [
                [attributes, ca, gl.getActiveAttrib, gl.getAttribLocation],
                [uniforms, cu, gl.getActiveUniform, gl.getUniformLocation],
            ];
            for (const [container, count, getActive, getLocation] of stub5_seq) {
                for (let i = 0; i < count; i += 1) {
                    const info = getActive.call(gl, this.handle, i);
                    const name = info.name;
                    const m = name.match(regex);
                    if (m != null) {
                        const name = m[1];
                        for (let j = 0; j < info.size; j += 1) {
                            container.push([`${name}[${j}]`, info.type]);
                        }
                    }
                    else {
                        container.push([name, info.type]);
                    }
                    this._locations.set(name, getLocation.call(gl, this.handle, name));
                }
            }
            const attrs_and_uniforms = new Set();
            for (const [name] of attributes) {
                attrs_and_uniforms.add(name);
            }
            for (const [name] of uniforms) {
                attrs_and_uniforms.add(name);
            }
            return attrs_and_uniforms;
        }
        set_texture(name, value) {
            var _a;
            // Set a texture sampler.
            //
            // A texture is a 2 dimensional grid of colors/intensities that
            // can be applied to a face (or used for other means by providing
            // a regular grid of data).
            //
            // Parameters
            // ----------
            // name : str
            //     The name by which the texture is known in the GLSL code.
            // value : Texture2d
            //     The Texture2d object to bind.
            if (!this._linked) {
                throw new Error("Cannot set uniform when program has no code");
            }
            const handle = (_a = this._locations.get(name)) !== null && _a !== void 0 ? _a : -1;
            if (handle < 0) {
                if (!this._known_invalid.has(name)) {
                    this._known_invalid.add(name);
                    console.log(`"Variable ${name} is not an active texture`);
                }
                return;
            }
            if (this._unset_variables.has(name)) {
                this._unset_variables.delete(name);
            }
            this.activate();
            if (true) {
                let unit = this._samplers.size;
                if (this._samplers.has(name)) {
                    unit = this._samplers.get(name)[2];
                }
                this._samplers.set(name, [value._target, value.handle, unit]);
                this.gl.uniform1i(handle, unit);
            }
        }
        set_uniform(name, type_, value) {
            var _a;
            // Set a uniform value.
            //
            // A uniform is a value that is global to both the vertex and
            // fragment shader.
            //
            // Parameters
            // ----------
            // name : str
            //     The name by which the uniform is known in the GLSL code.
            // type_ : str
            //     The type of the uniform, e.g. 'float', 'vec2', etc.
            // value : list of scalars
            //     The value for the uniform. Should be a list even for type float.
            if (!this._linked) {
                throw new Error("Cannot set uniform when program has no code");
            }
            const handle = (_a = this._locations.get(name)) !== null && _a !== void 0 ? _a : -1;
            if (handle < 0) {
                if (!this._known_invalid.has(name)) {
                    this._known_invalid.add(name);
                    console.log(`Variable ${name} is not an active uniform`);
                }
                return;
            }
            if (this._unset_variables.has(name)) {
                this._unset_variables.delete(name);
            }
            let count = 1;
            if (!type_.startsWith("mat")) {
                const a_type = type_ == "int" || type_ == "bool" ? "float" : type_.replace(/^ib/, "");
                count = Math.floor(value.length / (this.ATYPEINFO[a_type][0]));
            }
            if (count > 1) {
                for (let j = 0; j < count; j += 1) {
                    if (this._unset_variables.has(`${name}[${j}]`)) {
                        const name_ = `${name}[${j}]`;
                        if (this._unset_variables.has(name_)) {
                            this._unset_variables.delete(name_);
                        }
                    }
                }
            }
            const funcname = this.UTYPEMAP[type_];
            this.activate();
            if (type_.startsWith("mat")) {
                this.gl[funcname](handle, false, value);
            }
            else {
                this.gl[funcname](handle, value);
            }
        }
        set_attribute(name, type_, value, stride = 0, offset = 0, normalize = false) {
            var _a;
            // Set an attribute value.
            //
            // An attribute represents per-vertex data and can only be used
            // in the vertex shader.
            //
            // Parameters
            // ----------
            // name : str
            //     The name by which the attribute is known in the GLSL code.
            // type_ : str
            //     The type of the attribute, e.g. 'float', 'vec2', etc.
            // value : VertexBuffer, array
            //     If value is a VertexBuffer, it is used (with stride and offset)
            //     for the vertex data. If value is an array, its used to set
            //     the value of all vertices (similar to a uniform).
            // stide : int, default 0
            //     The stride to "sample" the vertex data inside the buffer. Unless
            //     multiple vertex data are packed into a single buffer, this should
            //     be zero.
            // offset : int, default 0
            //     The offset to "sample" the vertex data inside the buffer. Unless
            //     multiple vertex data are packed into a single buffer, or only
            //     a part of the data must be used, this should probably be zero.
            if (!this._linked) {
                throw new Error("Cannot set attribute when program has no code");
            }
            const handle = (_a = this._locations.get(name)) !== null && _a !== void 0 ? _a : -1;
            if (handle < 0) {
                if (!this._known_invalid.has(name)) {
                    this._known_invalid.add(name);
                    if (value instanceof buffer_1.VertexBuffer && offset > 0) {
                    }
                    else {
                        console.log(`Variable ${name} is not an active attribute`);
                    }
                }
                return;
            }
            if (this._unset_variables.has(name)) {
                this._unset_variables.delete(name);
            }
            this.activate();
            if (!(value instanceof buffer_1.VertexBuffer)) {
                const funcname = this.ATYPEMAP[type_];
                this._attributes.set(name, [null, handle, funcname, value]);
            }
            else {
                const [size, gtype] = this.ATYPEINFO[type_];
                const funcname = "vertexAttribPointer";
                const args = [size, gtype, normalize, stride, offset];
                this._attributes.set(name, [value.handle, handle, funcname, args]);
            }
        }
        _pre_draw() {
            this.activate();
            for (const [tex_target, tex_handle, unit] of this._samplers.values()) {
                this.gl.activeTexture(this.gl.TEXTURE0 + unit);
                this.gl.bindTexture(tex_target, tex_handle);
            }
            for (const [vbo_handle, attr_handle, funcname, args] of this._attributes.values()) {
                if (vbo_handle != null) {
                    this.gl.bindBuffer(this.gl.ARRAY_BUFFER, vbo_handle);
                    this.gl.enableVertexAttribArray(attr_handle);
                    this.gl[funcname].apply(this.gl, [attr_handle, ...args]);
                }
                else {
                    this.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);
                    this.gl.disableVertexAttribArray(attr_handle);
                    this.gl[funcname].apply(this.gl, [attr_handle, ...args]);
                }
            }
            if (!this._validated) {
                this._validated = true;
                this._validate();
            }
        }
        _validate() {
            if (this._unset_variables.size) {
                console.log(`Program has unset variables: ${this._unset_variables}`);
            }
            this.gl.validateProgram(this.handle);
            if (!this.gl.getProgramParameter(this.handle, this.gl.VALIDATE_STATUS)) {
                console.log(this.gl.getProgramInfoLog(this.handle));
                throw new Error("Program validation error");
            }
        }
        draw(mode, selection) {
            // Draw the current visualization defined by the program.
            //
            // Parameters
            // ----------
            // mode : GL enum
            //     Can be POINTS, LINES, LINE_LOOP, LINE_STRIP, LINE_FAN, TRIANGLES
            // selection : 2-element tuple or IndexBuffer
            //     The selection to draw, specified either as (first, count) or an
            //     IndexBuffer object.
            if (!this._linked) {
                throw new Error("Cannot draw program if code has not been set");
            }
            if (selection instanceof buffer_1.IndexBuffer) {
                this._pre_draw();
                selection.activate();
                const count = selection.buffer_size / 2;
                const gtype = this.gl.UNSIGNED_SHORT;
                this.gl.drawElements(mode, count, gtype, 0);
                selection.deactivate();
            }
            else {
                const [first, count] = selection;
                if (count != 0) {
                    this._pre_draw();
                    this.gl.drawArrays(mode, first, count);
                }
            }
        }
    }
    exports.Program = Program;
    Program.__name__ = "Program";
},
/* models/glyphs/webgl/utils/buffer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class Buffer {
        constructor(gl) {
            this.gl = gl;
            this._usage = 35048;
            this.buffer_size = 0;
            this.handle = this.gl.createBuffer();
        }
        delete() {
            this.gl.deleteBuffer(this.handle);
        }
        activate() {
            this.gl.bindBuffer(this._target, this.handle);
        }
        deactivate() {
            this.gl.bindBuffer(this._target, null);
        }
        set_size(nbytes) {
            // Set the size of the buffer in bytes.
            //
            // Parameters
            // ----------
            // nbytes : int
            //     The number of bytes that the buffer needs to hold.
            if (nbytes != this.buffer_size) {
                this.activate();
                this.gl.bufferData(this._target, nbytes, this._usage);
                this.buffer_size = nbytes;
            }
        }
        set_data(offset, data) {
            // Set the buffer data.
            //
            // Parameters
            // ----------
            // offset : int
            //     The offset in bytes for the new data.
            // data : typed array
            //     The data to upload.
            this.activate();
            this.gl.bufferSubData(this._target, offset, data);
        }
    }
    exports.Buffer = Buffer;
    Buffer.__name__ = "Buffer";
    class VertexBuffer extends Buffer {
        constructor() {
            super(...arguments);
            this._target = 34962;
        }
    }
    exports.VertexBuffer = VertexBuffer;
    VertexBuffer.__name__ = "VertexBuffer";
    class IndexBuffer extends Buffer {
        constructor() {
            super(...arguments);
            this._target = 34963;
        }
    }
    exports.IndexBuffer = IndexBuffer;
    IndexBuffer.__name__ = "IndexBuffer";
},
/* models/glyphs/webgl/utils/texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const assert_1 = require(11) /* ../../../../core/util/assert */;
    class Texture2d {
        constructor(gl) {
            this.gl = gl;
            this._target = 3553;
            this._types = {
                Int8Array: 5120,
                Uint8Array: 5121,
                Int16Array: 5122,
                Uint16Array: 5123,
                Int32Array: 5124,
                Uint32Array: 5125,
                Float32Array: 5126,
            };
            this.handle = this.gl.createTexture();
        }
        delete() {
            this.gl.deleteTexture(this.handle);
        }
        activate() {
            this.gl.bindTexture(this._target, this.handle);
        }
        deactivate() {
            this.gl.bindTexture(this._target, 0);
        }
        _get_alignment(width) {
            // Determines a textures byte alignment. If the width isn't a
            // power of 2 we need to adjust the byte alignment of the image.
            // The image height is unimportant.
            //
            // www.opengl.org/wiki/Common_Mistakes#Texture_upload_and_pixel_reads
            const alignments = [4, 8, 2, 1];
            for (const alignment of alignments) {
                if (width % alignment == 0) {
                    return alignment;
                }
            }
            assert_1.unreachable();
        }
        set_wrapping(wrap_s, wrap_t) {
            // Set the texture wrapping mode.
            //
            // Parameters
            // ----------
            // wrap_s : GL enum
            //     The mode to wrap the x dimension. Valid values are REPEAT
            //     CLAMP_TO_EDGE MIRRORED_REPEAT
            // wrap_t : GL enum
            //     The mode to wrap the y dimension. Same options as for wrap_s.
            this.activate();
            this.gl.texParameterf(this._target, this.gl.TEXTURE_WRAP_S, wrap_s);
            this.gl.texParameterf(this._target, this.gl.TEXTURE_WRAP_T, wrap_t);
        }
        set_interpolation(min, mag) {
            // Set the texture interpolation mode
            //
            // Parameters
            // ----------
            // min : GL enum
            //     The interpolation mode when minifying (i.e. zoomed out). Valid
            //     values are LINEAR and NEAREST.
            // max : GL enum
            //     The interpolation mode when magnifying (i.e. zoomed in). Valid
            //     values are LINEAR, NEAREST, NEAREST_MIPMAP_NEAREST,
            //     LINEAR_MIPMAP_NEAREST, NEAREST_MIPMAP_LINEAR, LINEAR_MIPMAP_LINEAR.
            this.activate();
            this.gl.texParameterf(this._target, this.gl.TEXTURE_MIN_FILTER, min);
            this.gl.texParameterf(this._target, this.gl.TEXTURE_MAG_FILTER, mag);
        }
        set_size([width, height], format) {
            var _a, _b, _c;
            // Set the size of the 2D texture.
            //
            // Parameters
            // ----------
            // shape : tuple of ints
            //     The shape of the data to upload
            // format : GL enum
            //     The format of the texture data. Can be LUMINANCE, LUMINANCE_ALPHA,
            //     RGB, and RGBA.
            if (width != ((_a = this._shape_format) === null || _a === void 0 ? void 0 : _a.width) || height != ((_b = this._shape_format) === null || _b === void 0 ? void 0 : _b.height) || format != ((_c = this._shape_format) === null || _c === void 0 ? void 0 : _c.format)) {
                this._shape_format = { width, height, format };
                this.activate();
                this.gl.texImage2D(this._target, 0, format, width, height, 0, format, this.gl.UNSIGNED_BYTE, null);
            }
        }
        set_data(offset, [width, height], data) {
            // Set the 2D texture data.
            //
            // Parameters
            // ----------
            // offset : tuple of ints
            //     Offset in pixels for each dimension.
            // shape : tuple of ints
            //     The shape of the data to upload
            // data : typed array
            //     The actual pixel data. Can be of any type, but on the GPU the
            //     dat is stored in 8 bit precision.
            this.activate();
            const { format } = this._shape_format;
            const [x, y] = offset;
            const gtype = this._types[data.constructor.name];
            if (gtype == null) {
                throw new Error(`Type ${data.constructor.name} not allowed for texture`);
            }
            const alignment = this._get_alignment(width);
            if (alignment != 4) {
                this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT, alignment);
            }
            this.gl.texSubImage2D(this._target, 0, x, y, width, height, format, gtype, data);
            if (alignment != 4) {
                this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT, 4);
            }
        }
    }
    exports.Texture2d = Texture2d;
    Texture2d.__name__ = "Texture2d";
},
/* models/glyphs/webgl/base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class BaseGLGlyph {
        constructor(gl, glyph) {
            this.gl = gl;
            this.glyph = glyph;
            this.nvertices = 0;
            this.size_changed = false;
            this.data_changed = false;
            this.visuals_changed = false;
        }
        set_data_changed() {
            const { data_size } = this.glyph;
            if (data_size != this.nvertices) {
                this.nvertices = data_size;
                this.size_changed = true;
            }
            this.data_changed = true;
        }
        set_visuals_changed() {
            this.visuals_changed = true;
        }
        render(_ctx, indices, mainglyph) {
            if (indices.length == 0) {
                return true;
            }
            const { width, height } = this.glyph.renderer.plot_view.canvas_view.webgl.canvas;
            const trans = {
                pixel_ratio: this.glyph.renderer.plot_view.canvas_view.pixel_ratio,
                width,
                height,
            };
            this.draw(indices, mainglyph, trans);
            return true;
        }
    }
    exports.BaseGLGlyph = BaseGLGlyph;
    BaseGLGlyph.__name__ = "BaseGLGlyph";
},
/* models/glyphs/webgl/line.vert.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const shader = `
precision mediump float;

const float PI = 3.14159265358979323846264;
const float THETA = 15.0 * 3.14159265358979323846264/180.0;

uniform float u_pixel_ratio;
uniform vec2 u_canvas_size, u_offset;
uniform vec2 u_scale_aspect;
uniform float u_scale_length;

uniform vec4 u_color;
uniform float u_antialias;
uniform float u_length;
uniform float u_linewidth;
uniform float u_dash_index;
uniform float u_closed;

attribute vec2 a_position;
attribute vec4 a_tangents;
attribute vec2 a_segment;
attribute vec2 a_angles;
attribute vec2 a_texcoord;

varying vec4  v_color;
varying vec2  v_segment;
varying vec2  v_angles;
varying vec2  v_texcoord;
varying vec2  v_miter;
varying float v_length;
varying float v_linewidth;

float cross(in vec2 v1, in vec2 v2)
{
    return v1.x*v2.y - v1.y*v2.x;
}

float signed_distance(in vec2 v1, in vec2 v2, in vec2 v3)
{
    return cross(v2-v1,v1-v3) / length(v2-v1);
}

void rotate( in vec2 v, in float alpha, out vec2 result )
{
    float c = cos(alpha);
    float s = sin(alpha);
    result = vec2( c*v.x - s*v.y,
                   s*v.x + c*v.y );
}

void main()
{
    bool closed = (u_closed > 0.0);

    // Attributes and uniforms to varyings
    v_color = u_color;
    v_linewidth = u_linewidth;
    v_segment = a_segment * u_scale_length;
    v_length = u_length * u_scale_length;

    // Scale to map to pixel coordinates. The original algorithm from the paper
    // assumed isotropic scale. We obviously do not have this.
    vec2 abs_scale_aspect = abs(u_scale_aspect);
    vec2 abs_scale = u_scale_length * abs_scale_aspect;

    // Correct angles for aspect ratio
    vec2 av;
    av = vec2(1.0, tan(a_angles.x)) / abs_scale_aspect;
    v_angles.x = atan(av.y, av.x);
    av = vec2(1.0, tan(a_angles.y)) / abs_scale_aspect;
    v_angles.y = atan(av.y, av.x);

    // Thickness below 1 pixel are represented using a 1 pixel thickness
    // and a modified alpha
    v_color.a = min(v_linewidth, v_color.a);
    v_linewidth = max(v_linewidth, 1.0);

    // If color is fully transparent we just will discard the fragment anyway
    if( v_color.a <= 0.0 ) {
        gl_Position = vec4(0.0,0.0,0.0,1.0);
        return;
    }

    // This is the actual half width of the line
    float w = ceil(u_antialias+v_linewidth)/2.0;

    vec2 position = a_position;

    vec2 t1 = normalize(a_tangents.xy * abs_scale_aspect);  // note the scaling for aspect ratio here
    vec2 t2 = normalize(a_tangents.zw * abs_scale_aspect);
    float u = a_texcoord.x;
    float v = a_texcoord.y;
    vec2 o1 = vec2( +t1.y, -t1.x);
    vec2 o2 = vec2( +t2.y, -t2.x);

    // This is a join
    // ----------------------------------------------------------------
    if( t1 != t2 ) {
        float angle = atan (t1.x*t2.y-t1.y*t2.x, t1.x*t2.x+t1.y*t2.y);  // Angle needs recalculation for some reason
        vec2 t  = normalize(t1+t2);
        vec2 o  = vec2( + t.y, - t.x);

        if ( u_dash_index > 0.0 )
        {
            // Broken angle
            // ----------------------------------------------------------------
            if( (abs(angle) > THETA) ) {
                position += v * w * o / cos(angle/2.0);
                float s = sign(angle);
                if( angle < 0.0 ) {
                    if( u == +1.0 ) {
                        u = v_segment.y + v * w * tan(angle/2.0);
                        if( v == 1.0 ) {
                            position -= 2.0 * w * t1 / sin(angle);
                            u -= 2.0 * w / sin(angle);
                        }
                    } else {
                        u = v_segment.x - v * w * tan(angle/2.0);
                        if( v == 1.0 ) {
                            position += 2.0 * w * t2 / sin(angle);
                            u += 2.0*w / sin(angle);
                        }
                    }
                } else {
                    if( u == +1.0 ) {
                        u = v_segment.y + v * w * tan(angle/2.0);
                        if( v == -1.0 ) {
                            position += 2.0 * w * t1 / sin(angle);
                            u += 2.0 * w / sin(angle);
                        }
                    } else {
                        u = v_segment.x - v * w * tan(angle/2.0);
                        if( v == -1.0 ) {
                            position -= 2.0 * w * t2 / sin(angle);
                            u -= 2.0*w / sin(angle);
                        }
                    }
                }
                // Continuous angle
                // ------------------------------------------------------------
            } else {
                position += v * w * o / cos(angle/2.0);
                if( u == +1.0 ) u = v_segment.y;
                else            u = v_segment.x;
            }
        }

        // Solid line
        // --------------------------------------------------------------------
        else
        {
            position.xy += v * w * o / cos(angle/2.0);
            if( angle < 0.0 ) {
                if( u == +1.0 ) {
                    u = v_segment.y + v * w * tan(angle/2.0);
                } else {
                    u = v_segment.x - v * w * tan(angle/2.0);
                }
            } else {
                if( u == +1.0 ) {
                    u = v_segment.y + v * w * tan(angle/2.0);
                } else {
                    u = v_segment.x - v * w * tan(angle/2.0);
                }
            }
        }

    // This is a line start or end (t1 == t2)
    // ------------------------------------------------------------------------
    } else {
        position += v * w * o1;
        if( u == -1.0 ) {
            u = v_segment.x - w;
            position -= w * t1;
        } else {
            u = v_segment.y + w;
            position += w * t2;
        }
    }

    // Miter distance
    // ------------------------------------------------------------------------
    vec2 t;
    vec2 curr = a_position * abs_scale;
    if( a_texcoord.x < 0.0 ) {
        vec2 next = curr + t2*(v_segment.y-v_segment.x);

        rotate( t1, +v_angles.x/2.0, t);
        v_miter.x = signed_distance(curr, curr+t, position);

        rotate( t2, +v_angles.y/2.0, t);
        v_miter.y = signed_distance(next, next+t, position);
    } else {
        vec2 prev = curr - t1*(v_segment.y-v_segment.x);

        rotate( t1, -v_angles.x/2.0,t);
        v_miter.x = signed_distance(prev, prev+t, position);

        rotate( t2, -v_angles.y/2.0,t);
        v_miter.y = signed_distance(curr, curr+t, position);
    }

    if (!closed && v_segment.x <= 0.0) {
        v_miter.x = 1e10;
    }
    if (!closed && v_segment.y >= v_length)
    {
        v_miter.y = 1e10;
    }

    v_texcoord = vec2( u, v*w );

    // Calculate position in device coordinates. Note that we
    // already scaled with abs scale above.
    vec2 normpos = position * sign(u_scale_aspect);
    normpos += 0.5;  // make up for Bokeh's offset
    normpos /= u_canvas_size / u_pixel_ratio;  // in 0..1
    gl_Position = vec4(normpos*2.0-1.0, 0.0, 1.0);
    gl_Position.y *= -1.0;
}
`;
    exports.default = shader;
},
/* models/glyphs/webgl/line.frag.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const shader = `
precision mediump float;

const float PI = 3.14159265358979323846264;
const float THETA = 15.0 * 3.14159265358979323846264/180.0;

uniform sampler2D u_dash_atlas;

uniform vec2 u_linecaps;
uniform float u_miter_limit;
uniform float u_linejoin;
uniform float u_antialias;
uniform float u_dash_phase;
uniform float u_dash_period;
uniform float u_dash_index;
uniform vec2 u_dash_caps;
uniform float u_closed;

varying vec4  v_color;
varying vec2  v_segment;
varying vec2  v_angles;
varying vec2  v_texcoord;
varying vec2  v_miter;
varying float v_length;
varying float v_linewidth;

// Compute distance to cap ----------------------------------------------------
float cap( int type, float dx, float dy, float t, float linewidth )
{
    float d = 0.0;
    dx = abs(dx);
    dy = abs(dy);
    if      (type == 0)  discard;  // None
    else if (type == 1)  d = sqrt(dx*dx+dy*dy);  // Round
    else if (type == 3)  d = (dx+abs(dy));  // Triangle in
    else if (type == 2)  d = max(abs(dy),(t+dx-abs(dy)));  // Triangle out
    else if (type == 4)  d = max(dx,dy);  // Square
    else if (type == 5)  d = max(dx+t,dy);  // Butt
    return d;
}

// Compute distance to join -------------------------------------------------
float join( in int type, in float d, in vec2 segment, in vec2 texcoord, in vec2 miter,
           in float linewidth )
{
    // texcoord.x is distance from start
    // texcoord.y is distance from centerline
    // segment.x and y indicate the limits (as for texcoord.x) for this segment

    float dx = texcoord.x;

    // Round join
    if( type == 1 ) {
        if (dx < segment.x) {
            d = max(d,length( texcoord - vec2(segment.x,0.0)));
            //d = length( texcoord - vec2(segment.x,0.0));
        } else if (dx > segment.y) {
            d = max(d,length( texcoord - vec2(segment.y,0.0)));
            //d = length( texcoord - vec2(segment.y,0.0));
        }
    }
    // Bevel join
    else if ( type == 2 ) {
        if (dx < segment.x) {
            vec2 x = texcoord - vec2(segment.x,0.0);
            d = max(d, max(abs(x.x), abs(x.y)));

        } else if (dx > segment.y) {
            vec2 x = texcoord - vec2(segment.y,0.0);
            d = max(d, max(abs(x.x), abs(x.y)));
        }
        /*  Original code for bevel which does not work for us
        if( (dx < segment.x) ||  (dx > segment.y) )
            d = max(d, min(abs(x.x),abs(x.y)));
        */
    }

    return d;
}

void main()
{
    // If color is fully transparent we just discard the fragment
    if( v_color.a <= 0.0 ) {
        discard;
    }

    // Test if dash pattern is the solid one (0)
    bool solid =  (u_dash_index == 0.0);

    // Test if path is closed
    bool closed = (u_closed > 0.0);

    vec4 color = v_color;
    float dx = v_texcoord.x;
    float dy = v_texcoord.y;
    float t = v_linewidth/2.0-u_antialias;
    float width = 1.0;  //v_linewidth; original code had dashes scale with line width, we do not
    float d = 0.0;

    vec2 linecaps = u_linecaps;
    vec2 dash_caps = u_dash_caps;
    float line_start = 0.0;
    float line_stop = v_length;

    // Apply miter limit; fragments too far into the miter are simply discarded
    if( (dx < v_segment.x) || (dx > v_segment.y) ) {
        float into_miter = max(v_segment.x - dx, dx - v_segment.y);
        if (into_miter > u_miter_limit*v_linewidth/2.0)
          discard;
    }

    // Solid line --------------------------------------------------------------
    if( solid ) {
        d = abs(dy);
        if( (!closed) && (dx < line_start) ) {
            d = cap( int(u_linecaps.x), abs(dx), abs(dy), t, v_linewidth );
        }
        else if( (!closed) &&  (dx > line_stop) ) {
            d = cap( int(u_linecaps.y), abs(dx)-line_stop, abs(dy), t, v_linewidth );
        }
        else {
            d = join( int(u_linejoin), abs(dy), v_segment, v_texcoord, v_miter, v_linewidth );
        }

    // Dash line --------------------------------------------------------------
    } else {
        float segment_start = v_segment.x;
        float segment_stop  = v_segment.y;
        float segment_center= (segment_start+segment_stop)/2.0;
        float freq          = u_dash_period*width;
        float u = mod( dx + u_dash_phase*width, freq);
        vec4 tex = texture2D(u_dash_atlas, vec2(u/freq, u_dash_index)) * 255.0 -10.0;  // conversion to int-like
        float dash_center= tex.x * width;
        float dash_type  = tex.y;
        float _start = tex.z * width;
        float _stop  = tex.a * width;
        float dash_start = dx - u + _start;
        float dash_stop  = dx - u + _stop;

        // Compute extents of the first dash (the one relative to v_segment.x)
        // Note: this could be computed in the vertex shader
        if( (dash_stop < segment_start) && (dash_caps.x != 5.0) ) {
            float u = mod(segment_start + u_dash_phase*width, freq);
            vec4 tex = texture2D(u_dash_atlas, vec2(u/freq, u_dash_index)) * 255.0 -10.0;  // conversion to int-like
            dash_center= tex.x * width;
            //dash_type  = tex.y;
            float _start = tex.z * width;
            float _stop  = tex.a * width;
            dash_start = segment_start - u + _start;
            dash_stop = segment_start - u + _stop;
        }

        // Compute extents of the last dash (the one relatives to v_segment.y)
        // Note: This could be computed in the vertex shader
        else if( (dash_start > segment_stop)  && (dash_caps.y != 5.0) ) {
            float u = mod(segment_stop + u_dash_phase*width, freq);
            vec4 tex = texture2D(u_dash_atlas, vec2(u/freq, u_dash_index)) * 255.0 -10.0;  // conversion to int-like
            dash_center= tex.x * width;
            //dash_type  = tex.y;
            float _start = tex.z * width;
            float _stop  = tex.a * width;
            dash_start = segment_stop - u + _start;
            dash_stop  = segment_stop - u + _stop;
        }

        // This test if the we are dealing with a discontinuous angle
        bool discontinuous = ((dx <  segment_center) && abs(v_angles.x) > THETA) ||
                             ((dx >= segment_center) && abs(v_angles.y) > THETA);
        //if( dx < line_start) discontinuous = false;
        //if( dx > line_stop)  discontinuous = false;

        float d_join = join( int(u_linejoin), abs(dy),
                            v_segment, v_texcoord, v_miter, v_linewidth );

        // When path is closed, we do not have room for linecaps, so we make room
        // by shortening the total length
        if (closed) {
             line_start += v_linewidth/2.0;
             line_stop  -= v_linewidth/2.0;
        }

        // We also need to take antialias area into account
        //line_start += u_antialias;
        //line_stop  -= u_antialias;

        // Check is dash stop is before line start
        if( dash_stop <= line_start ) {
            discard;
        }
        // Check is dash start is beyond line stop
        if( dash_start >= line_stop ) {
            discard;
        }

        // Check if current dash start is beyond segment stop
        if( discontinuous ) {
            // Dash start is beyond segment, we discard
            if( (dash_start > segment_stop) ) {
                discard;
                //gl_FragColor = vec4(1.0,0.0,0.0,.25); return;
            }

            // Dash stop is before segment, we discard
            if( (dash_stop < segment_start) ) {
                discard;  //gl_FragColor = vec4(0.0,1.0,0.0,.25); return;
            }

            // Special case for round caps (nicer with this)
            if( dash_caps.x == 1.0 ) {
                if( (u > _stop) && (dash_stop > segment_stop )  && (abs(v_angles.y) < PI/2.0)) {
                    discard;
                }
            }

            // Special case for round caps  (nicer with this)
            if( dash_caps.y == 1.0 ) {
                if( (u < _start) && (dash_start < segment_start )  && (abs(v_angles.x) < PI/2.0)) {
                    discard;
                }
            }

            // Special case for triangle caps (in & out) and square
            // We make sure the cap stop at crossing frontier
            if( (dash_caps.x != 1.0) && (dash_caps.x != 5.0) ) {
                if( (dash_start < segment_start )  && (abs(v_angles.x) < PI/2.0) ) {
                    float a = v_angles.x/2.0;
                    float x = (segment_start-dx)*cos(a) - dy*sin(a);
                    float y = (segment_start-dx)*sin(a) + dy*cos(a);
                    if( x > 0.0 ) discard;
                    // We transform the cap into square to avoid holes
                    dash_caps.x = 4.0;
                }
            }

            // Special case for triangle caps (in & out) and square
            // We make sure the cap stop at crossing frontier
            if( (dash_caps.y != 1.0) && (dash_caps.y != 5.0) ) {
                if( (dash_stop > segment_stop )  && (abs(v_angles.y) < PI/2.0) ) {
                    float a = v_angles.y/2.0;
                    float x = (dx-segment_stop)*cos(a) - dy*sin(a);
                    float y = (dx-segment_stop)*sin(a) + dy*cos(a);
                    if( x > 0.0 ) discard;
                    // We transform the caps into square to avoid holes
                    dash_caps.y = 4.0;
                }
            }
        }

        // Line cap at start
        if( (dx < line_start) && (dash_start < line_start) && (dash_stop > line_start) ) {
            d = cap( int(linecaps.x), dx-line_start, dy, t, v_linewidth);
        }
        // Line cap at stop
        else if( (dx > line_stop) && (dash_stop > line_stop) && (dash_start < line_stop) ) {
            d = cap( int(linecaps.y), dx-line_stop, dy, t, v_linewidth);
        }
        // Dash cap left - dash_type = -1, 0 or 1, but there may be roundoff errors
        else if( dash_type < -0.5 ) {
            d = cap( int(dash_caps.y), abs(u-dash_center), dy, t, v_linewidth);
            if( (dx > line_start) && (dx < line_stop) )
                d = max(d,d_join);
        }
        // Dash cap right
        else if( dash_type > 0.5 ) {
            d = cap( int(dash_caps.x), abs(dash_center-u), dy, t, v_linewidth);
            if( (dx > line_start) && (dx < line_stop) )
                d = max(d,d_join);
        }
        // Dash body (plain)
        else {// if( dash_type > -0.5 &&  dash_type < 0.5) {
            d = abs(dy);
        }

        // Line join
        if( (dx > line_start) && (dx < line_stop)) {
            if( (dx <= segment_start) && (dash_start <= segment_start)
                && (dash_stop >= segment_start) ) {
                d = d_join;
                // Antialias at outer border
                float angle = PI/2.+v_angles.x;
                float f = abs( (segment_start - dx)*cos(angle) - dy*sin(angle));
                d = max(f,d);
            }
            else if( (dx > segment_stop) && (dash_start <= segment_stop)
                     && (dash_stop >= segment_stop) ) {
                d = d_join;
                // Antialias at outer border
                float angle = PI/2.+v_angles.y;
                float f = abs((dx - segment_stop)*cos(angle) - dy*sin(angle));
                d = max(f,d);
            }
            else if( dx < (segment_start - v_linewidth/2.)) {
                discard;
            }
            else if( dx > (segment_stop + v_linewidth/2.)) {
                discard;
            }
        }
        else if( dx < (segment_start - v_linewidth/2.)) {
            discard;
        }
        else if( dx > (segment_stop + v_linewidth/2.)) {
            discard;
        }
    }

    // Distance to border ------------------------------------------------------
    d = d - t;
    if( d < 0.0 ) {
        gl_FragColor = color;
    } else {
        d /= u_antialias;
        gl_FragColor = vec4(color.rgb, exp(-d*d)*color.a);
    }
}
`;
    exports.default = shader;
},
/* models/glyphs/patch.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const utils_1 = require(106) /* ./utils */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const selection_1 = require(59) /* ../selections/selection */;
    class PatchView extends xy_glyph_1.XYGlyphView {
        _inner_loop(ctx, indices, sx, sy, func) {
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                if (i == 0) {
                    ctx.beginPath();
                    ctx.moveTo(sx_i, sy_i);
                    continue;
                }
                else if (isNaN(sx_i + sy_i)) {
                    ctx.closePath();
                    func.apply(ctx);
                    ctx.beginPath();
                    continue;
                }
                else
                    ctx.lineTo(sx_i, sy_i);
            }
            ctx.closePath();
            func.call(ctx);
        }
        _render(ctx, indices, data) {
            const { sx, sy } = data !== null && data !== void 0 ? data : this;
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_value(ctx);
                this._inner_loop(ctx, indices, sx, sy, ctx.fill);
            }
            if (this.visuals.hatch.doit) {
                this.visuals.hatch.set_value(ctx);
                this._inner_loop(ctx, indices, sx, sy, ctx.fill);
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_value(ctx);
                this._inner_loop(ctx, indices, sx, sy, ctx.stroke);
            }
        }
        draw_legend_for_index(ctx, bbox, _index) {
            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);
        }
        static init_Patch() {
            this.prototype.default_view = PatchView;
            this.mixins([mixins.LineScalar, mixins.FillScalar, mixins.HatchScalar]);
        }
    }
    exports.Patch = Patch;
    Patch.__name__ = "Patch";
    Patch.init_Patch();
},
/* models/glyphs/harea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const types_1 = require(24) /* ../../core/types */;
    const area_1 = require(118) /* ./area */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(59) /* ../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];
                if (isNaN(x1 + x2 + y) || !isFinite(x1 + x2 + y))
                    index.add_empty();
                else
                    index.add(min(x1, x2), y, max(x1, x2), y);
            }
        }
        _inner(ctx, sx1, sx2, sy, func) {
            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();
            func.call(ctx);
        }
        _render(ctx, _indices, data) {
            const { sx1, sx2, sy } = data !== null && data !== void 0 ? data : this;
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_value(ctx);
                this._inner(ctx, sx1, sx2, sy, ctx.fill);
            }
            if (this.visuals.hatch.doit) {
                this.visuals.hatch.set_value(ctx);
                this._inner(ctx, sx1, sx2, sy, ctx.fill);
            }
        }
        _hit_point(geometry) {
            const L = this.sy.length;
            const sx = new types_1.ScreenArray(2 * L);
            const sy = new types_1.ScreenArray(2 * L);
            for (let i = 0, end = L; i < end; i++) {
                sx[i] = this.sx1[i];
                sy[i] = this.sy[i];
                sx[L + i] = this.sx2[L - i - 1];
                sy[L + i] = this.sy[L - i - 1];
            }
            const result = new selection_1.Selection();
            if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
            }
            return result;
        }
        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);
        }
        static init_HArea() {
            this.prototype.default_view = HAreaView;
            this.define(({}) => ({
                x1: [p.XCoordinateSpec, { field: "x1" }],
                x2: [p.XCoordinateSpec, { field: "x2" }],
                y: [p.YCoordinateSpec, { field: "y" }],
            }));
        }
    }
    exports.HArea = HArea;
    HArea.__name__ = "HArea";
    HArea.init_HArea();
},
/* models/glyphs/area.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(98) /* ./glyph */;
    const utils_1 = require(106) /* ./utils */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    class AreaView extends glyph_1.GlyphView {
        draw_legend_for_index(ctx, bbox, _index) {
            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);
        }
        static init_Area() {
            this.mixins([mixins.FillScalar, mixins.HatchScalar]);
        }
    }
    exports.Area = Area;
    Area.__name__ = "Area";
    Area.init_Area();
},
/* models/glyphs/varea.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const types_1 = require(24) /* ../../core/types */;
    const area_1 = require(118) /* ./area */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(59) /* ../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];
                if (isNaN(x + y1 + y2) || !isFinite(x + y1 + y2))
                    index.add_empty();
                else
                    index.add(x, min(y1, y2), x, max(y1, y2));
            }
        }
        _inner(ctx, sx, sy1, sy2, func) {
            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();
            func.call(ctx);
        }
        _render(ctx, _indices, data) {
            const { sx, sy1, sy2 } = data !== null && data !== void 0 ? data : this;
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_value(ctx);
                this._inner(ctx, sx, sy1, sy2, ctx.fill);
            }
            if (this.visuals.hatch.doit) {
                this.visuals.hatch.set_value(ctx);
                this._inner(ctx, sx, sy1, sy2, ctx.fill);
            }
        }
        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 sx = new types_1.ScreenArray(2 * L);
            const sy = new types_1.ScreenArray(2 * L);
            for (let i = 0, end = L; i < end; i++) {
                sx[i] = this.sx[i];
                sy[i] = this.sy1[i];
                sx[L + i] = this.sx[L - i - 1];
                sy[L + i] = this.sy2[L - i - 1];
            }
            const result = new selection_1.Selection();
            if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
            }
            return result;
        }
        _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);
        }
        static init_VArea() {
            this.prototype.default_view = VAreaView;
            this.define(({}) => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
                y2: [p.YCoordinateSpec, { field: "y2" }],
            }));
        }
    }
    exports.VArea = VArea;
    VArea.__name__ = "VArea";
    VArea.init_VArea();
},
/* models/sources/cds_view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const selection_1 = require(59) /* ../selections/selection */;
    const types_1 = require(24) /* ../../core/types */;
    const filter_1 = require(121) /* ../filters/filter */;
    const columnar_data_source_1 = require(57) /* ./columnar_data_source */;
    class CDSView extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_CDSView() {
            this.define(({ Array, Ref }) => ({
                filters: [Array(Ref(filter_1.Filter)), []],
                source: [Ref(columnar_data_source_1.ColumnarDataSource)],
            }));
            this.internal(({ Int, Dict, Ref, Nullable }) => ({
                indices: [Ref(types_1.Indices)],
                indices_map: [Dict(Int), {}],
                masked: [Nullable(Ref(types_1.Indices)), null],
            }));
        }
        initialize() {
            super.initialize();
            this.compute_indices();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.properties.filters.change, () => this.compute_indices());
            const connect_listeners = () => {
                const fn = () => this.compute_indices();
                if (this.source != null) {
                    this.connect(this.source.change, fn);
                    if (this.source instanceof columnar_data_source_1.ColumnarDataSource) {
                        this.connect(this.source.streaming, fn);
                        this.connect(this.source.patching, fn);
                    }
                }
            };
            let initialized = this.source != null;
            if (initialized)
                connect_listeners();
            else {
                this.connect(this.properties.source.change, () => {
                    if (!initialized) {
                        connect_listeners();
                        initialized = true;
                    }
                });
            }
        }
        compute_indices() {
            var _a;
            const { source } = this;
            if (source == null)
                return;
            // XXX: if the data source is empty, there still may be one
            // index originating from glyph's scalar values.
            const size = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 1;
            const indices = types_1.Indices.all_set(size);
            for (const filter of this.filters) {
                indices.intersect(filter.compute_indices(source));
            }
            this.indices = indices;
            this._indices = [...indices];
            this.indices_map_to_subset();
        }
        indices_map_to_subset() {
            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) {
            const indices = selection_subset.indices.map((i) => this._indices[i]);
            return new selection_1.Selection(Object.assign(Object.assign({}, selection_subset.attributes), { indices }));
        }
        convert_selection_to_subset(selection_full) {
            const indices = selection_full.indices.map((i) => this.indices_map[i]);
            return new selection_1.Selection(Object.assign(Object.assign({}, selection_full.attributes), { indices }));
        }
        convert_indices_from_subset(indices) {
            return indices.map((i) => this._indices[i]);
        }
    }
    exports.CDSView = CDSView;
    CDSView.__name__ = "CDSView";
    CDSView.init_CDSView();
},
/* models/filters/filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    class Filter extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Filter = Filter;
    Filter.__name__ = "Filter";
},
/* core/build_views.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(9) /* ./util/array */;
    async function _build_view(view_cls, model, options) {
        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 = array_1.difference([...view_storage.keys()], models);
        for (const model of to_remove) {
            view_storage.get(model).remove();
            view_storage.delete(model);
        }
        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_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;
},
/* models/renderers/graph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_renderer_1 = require(62) /* ./data_renderer */;
    const glyph_renderer_1 = require(61) /* ./glyph_renderer */;
    const expression_1 = require(124) /* ../expressions/expression */;
    const layout_provider_1 = require(125) /* ../graphs/layout_provider */;
    const graph_hit_test_policy_1 = require(126) /* ../graphs/graph_hit_test_policy */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const xy_glyph_1 = require(64) /* ../glyphs/xy_glyph */;
    const multi_line_1 = require(127) /* ../glyphs/multi_line */;
    const patches_1 = require(128) /* ../glyphs/patches */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    class GraphRendererView extends data_renderer_1.DataRendererView {
        get glyph_view() {
            return this.node_view.glyph;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const graph = this.model;
            // TODO: replace this with bi-variate transforms
            let xs_ys = null;
            let x_y = null;
            const xs_expr = new class extends expression_1.Expression {
                _v_compute(source) {
                    assert_1.assert(xs_ys == null);
                    const [xs] = xs_ys = graph.layout_provider.get_edge_coordinates(source);
                    return xs;
                }
            };
            const ys_expr = new class extends expression_1.Expression {
                _v_compute(_source) {
                    assert_1.assert(xs_ys != null);
                    const [, ys] = xs_ys;
                    xs_ys = null;
                    return ys;
                }
            };
            const x_expr = new class extends expression_1.Expression {
                _v_compute(source) {
                    assert_1.assert(x_y == null);
                    const [x] = x_y = graph.layout_provider.get_node_coordinates(source);
                    return x;
                }
            };
            const y_expr = new class extends expression_1.Expression {
                _v_compute(_source) {
                    assert_1.assert(x_y != null);
                    const [, y] = x_y;
                    x_y = null;
                    return y;
                }
            };
            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`);
            }
            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: xs_expr };
            edge_renderer.glyph.ys = { expr: ys_expr };
            node_renderer.glyph.x = { expr: x_expr };
            node_renderer.glyph.y = { expr: y_expr };
            const { parent } = this;
            this.edge_view = await build_views_1.build_view(edge_renderer, { parent });
            this.node_view = await build_views_1.build_view(node_renderer, { parent });
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.layout_provider.change, () => {
                this.edge_view.set_data();
                this.node_view.set_data();
                this.request_render();
            });
        }
        remove() {
            this.edge_view.remove();
            this.node_view.remove();
            super.remove();
        }
        _render() {
            this.edge_view.render();
            this.node_view.render();
        }
        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);
        }
        static init_GraphRenderer() {
            this.prototype.default_view = GraphRendererView;
            this.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()],
            }));
        }
        get_selection_manager() {
            return this.node_renderer.data_source.selection_manager;
        }
    }
    exports.GraphRenderer = GraphRenderer;
    GraphRenderer.__name__ = "GraphRenderer";
    GraphRenderer.init_GraphRenderer();
},
/* models/expressions/expression.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    class Expression extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._connected = new Set();
            this._result = new Map();
        }
        v_compute(source) {
            if (!this._connected.has(source)) {
                this.connect(source.change, () => this._result.delete(source));
                this.connect(source.patching, () => this._result.delete(source));
                this.connect(source.streaming, () => this._result.delete(source));
                this._connected.add(source);
            }
            let result = this._result.get(source);
            if (result == null) {
                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._connected = new Set();
            this._result = new Map();
        }
        compute(source) {
            if (!this._connected.has(source)) {
                this.connect(source.change, () => this._result.delete(source));
                this.connect(source.patching, () => this._result.delete(source));
                this.connect(source.streaming, () => this._result.delete(source));
                this._connected.add(source);
            }
            let result = this._result.get(source);
            if (result == null) {
                result = this._compute(source);
                this._result.set(source, result);
            }
            return result;
        }
    }
    exports.ScalarExpression = ScalarExpression;
    ScalarExpression.__name__ = "ScalarExpression";
},
/* models/graphs/layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    class LayoutProvider extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LayoutProvider = LayoutProvider;
    LayoutProvider.__name__ = "LayoutProvider";
},
/* models/graphs/graph_hit_test_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const array_1 = require(9) /* ../../core/util/array */;
    const selection_1 = require(59) /* ../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) {
            let node_indices = [];
            if (mode == 'selection') {
                node_indices = node_source.selected.indices.map((i) => node_source.data.index[i]);
            }
            else if (mode == 'inspection') {
                node_indices = node_source.inspected.indices.map((i) => node_source.data.index[i]);
            }
            const edge_indices = [];
            for (let i = 0; i < edge_source.data.start.length; i++) {
                if (array_1.contains(node_indices, edge_source.data.start[i]) || 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) {
            let edge_indices = [];
            if (mode == 'selection')
                edge_indices = edge_source.selected.indices;
            else if (mode == 'inspection')
                edge_indices = 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 = array_1.uniq(nodes).map((i) => arrayable_1.indexOf(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";
},
/* models/glyphs/multi_line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const object_1 = require(13) /* ../../core/util/object */;
    const glyph_1 = require(98) /* ./glyph */;
    const utils_1 = require(106) /* ./utils */;
    const selection_1 = require(59) /* ../selections/selection */;
    class MultiLineView 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);
                if (xsi.length == 0) {
                    index.add_empty();
                    continue;
                }
                const ysi = this._ys.get(i);
                if (ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                const [x0, x1] = arrayable_1.minmax(xsi);
                const [y0, y1] = arrayable_1.minmax(ysi);
                index.add(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);
                this.visuals.line.set_vectorize(ctx, i);
                for (let j = 0, end = sx.length; j < end; j++) {
                    const sx_j = sx[j];
                    const sy_j = sy[j];
                    if (j == 0) {
                        ctx.beginPath();
                        ctx.moveTo(sx_j, sy_j);
                        continue;
                    }
                    else if (isNaN(sx_j + sy_j)) {
                        ctx.stroke();
                        ctx.beginPath();
                        continue;
                    }
                    else
                        ctx.lineTo(sx_j, sy_j);
                }
                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: object_1.to_object(hits),
            });
        }
        _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: object_1.to_object(hits),
            });
        }
        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 utils_1.line_interpolation(this.renderer, geometry, x2, y2, x3, y3);
        }
        draw_legend_for_index(ctx, bbox, index) {
            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);
        }
        static init_MultiLine() {
            this.prototype.default_view = MultiLineView;
            this.define(({}) => ({
                xs: [p.XCoordinateSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSpec, { field: "ys" }],
            }));
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.MultiLine = MultiLine;
    MultiLine.__name__ = "MultiLine";
    MultiLine.init_MultiLine();
},
/* models/glyphs/patches.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(98) /* ./glyph */;
    const utils_1 = require(106) /* ./utils */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(59) /* ../selections/selection */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    const projections_1 = require(65) /* ../../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);
                if (xsi.length == 0)
                    index.add_empty();
                else {
                    const [x0, x1] = arrayable_1.minmax(xsi);
                    const [y0, y1] = arrayable_1.minmax(ysi);
                    index.add(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,
            });
        }
        _inner_loop(ctx, sx, sy, func) {
            for (let j = 0, end = sx.length; j < end; j++) {
                if (j == 0) {
                    ctx.beginPath();
                    ctx.moveTo(sx[j], sy[j]);
                    continue;
                }
                else if (isNaN(sx[j] + sy[j])) {
                    ctx.closePath();
                    func.apply(ctx);
                    ctx.beginPath();
                    continue;
                }
                else
                    ctx.lineTo(sx[j], sy[j]);
            }
            ctx.closePath();
            func.call(ctx);
        }
        _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);
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    this._inner_loop(ctx, sx_i, sy_i, ctx.fill);
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    this._inner_loop(ctx, sx_i, sy_i, ctx.fill);
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    this._inner_loop(ctx, sx_i, sy_i, ctx.stroke);
                }
            }
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const xs = [sx0, sx1, sx1, sx0];
            const ys = [sy0, sy0, sy1, sy1];
            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 index of candidates) {
                const sxss = this.sxs.get(index);
                const syss = this.sys.get(index);
                let hit = true;
                for (let j = 0, endj = sxss.length; j < endj; j++) {
                    const sx = sxss[j];
                    const sy = syss[j];
                    if (!hittest.point_in_poly(sx, sy, xs, ys)) {
                        hit = false;
                        break;
                    }
                }
                if (hit) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _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 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;
            }
            assert_1.unreachable();
        }
        draw_legend_for_index(ctx, bbox, index) {
            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);
        }
        static init_Patches() {
            this.prototype.default_view = PatchesView;
            this.define(({}) => ({
                xs: [p.XCoordinateSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSpec, { field: "ys" }],
            }));
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        }
    }
    exports.Patches = Patches;
    Patches.__name__ = "Patches";
    Patches.init_Patches();
},
/* models/selections/interaction_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../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/column_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const columnar_data_source_1 = require(57) /* ./columnar_data_source */;
    const types_1 = require(8) /* ../../core/util/types */;
    const object_1 = require(13) /* ../../core/util/object */;
    const typed_array = tslib_1.__importStar(require(131) /* ../../core/util/typed_array */);
    const set_1 = require(132) /* ../../core/util/set */;
    const events_1 = require(35) /* ../../document/events */;
    //exported for testing
    function stream_to_column(col, new_col, rollover) {
        if (types_1.isArray(col)) {
            const result = col.concat(new_col);
            if (rollover != null && result.length > rollover)
                return result.slice(-rollover);
            else
                return result;
        }
        else if (types_1.isTypedArray(col)) {
            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
                let result;
                if (col.length < rollover) {
                    result = new col.constructor(rollover);
                    result.set(col, 0);
                }
                else
                    result = col;
                // shift values in original col to accommodate new_col
                for (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 tmp = new col.constructor(new_col);
                return typed_array.concat(col, tmp);
            }
        }
        else
            throw new Error("unsupported array types");
    }
    exports.stream_to_column = stream_to_column;
    // exported for testing
    function slice(ind, length) {
        let start, step, stop;
        if (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 (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 (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;
    class ColumnDataSource extends columnar_data_source_1.ColumnarDataSource {
        constructor(attrs) {
            super(attrs);
        }
        static init_ColumnDataSource() {
            this.define(({ Dict, Any /*Arrayable*/ }) => ({
                data: [Dict(Any /*Arrayable*/), {}],
            }));
        }
        stream(new_data, rollover, setter_id) {
            const { data } = this;
            for (const [name, new_column] of object_1.entries(new_data)) {
                data[name] = stream_to_column(data[name], new_column, rollover);
            }
            this.setv({ data }, { silent: true });
            this.streaming.emit();
            if (this.document != null) {
                const hint = new events_1.ColumnsStreamedEvent(this.document, this.ref(), new_data, rollover);
                this.document._notify_change(this, 'data', null, null, { setter_id, hint });
            }
        }
        patch(patches, setter_id) {
            const { data } = this;
            let patched = new Set();
            for (const [column, patch] of object_1.entries(patches)) {
                patched = set_1.union(patched, patch_to_column(data[column], patch)); // XXX
            }
            this.setv({ data }, { silent: true });
            this.patching.emit([...patched]);
            if (this.document != null) {
                const hint = new events_1.ColumnsPatchedEvent(this.document, this.ref(), patches);
                this.document._notify_change(this, 'data', null, null, { setter_id, hint });
            }
        }
    }
    exports.ColumnDataSource = ColumnDataSource;
    ColumnDataSource.__name__ = "ColumnDataSource";
    ColumnDataSource.init_ColumnDataSource();
},
/* 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/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;
},
/* models/annotations/arrow_head.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(53) /* ../../model */;
    const view_1 = require(42) /* ../../core/view */;
    const visuals = tslib_1.__importStar(require(45) /* ../../core/visuals */);
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class ArrowHeadView 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) {
            const self = this;
            for (const prop of this.model) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec))
                    continue;
                const uniform = prop.uniform(source);
                self[`${prop.attr}`] = uniform;
            }
        }
    }
    exports.ArrowHeadView = ArrowHeadView;
    ArrowHeadView.__name__ = "ArrowHeadView";
    class ArrowHead extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_ArrowHead() {
            this.define(() => ({
                size: [p.NumberSpec, 25],
            }));
        }
    }
    exports.ArrowHead = ArrowHead;
    ArrowHead.__name__ = "ArrowHead";
    ArrowHead.init_ArrowHead();
    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) {
            if (this.visuals.line.doit) {
                this.visuals.line.set_vectorize(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.stroke();
            }
        }
    }
    exports.OpenHeadView = OpenHeadView;
    OpenHeadView.__name__ = "OpenHeadView";
    class OpenHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
        static init_OpenHead() {
            this.prototype.default_view = OpenHeadView;
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.OpenHead = OpenHead;
    OpenHead.__name__ = "OpenHead";
    OpenHead.init_OpenHead();
    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) {
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_vectorize(ctx, i);
                this._normal(ctx, i);
                ctx.fill();
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_vectorize(ctx, i);
                this._normal(ctx, i);
                ctx.stroke();
            }
        }
        _normal(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();
        }
    }
    exports.NormalHeadView = NormalHeadView;
    NormalHeadView.__name__ = "NormalHeadView";
    class NormalHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
        static init_NormalHead() {
            this.prototype.default_view = NormalHeadView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector]);
            this.override({
                fill_color: "black",
            });
        }
    }
    exports.NormalHead = NormalHead;
    NormalHead.__name__ = "NormalHead";
    NormalHead.init_NormalHead();
    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) {
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_vectorize(ctx, i);
                this._vee(ctx, i);
                ctx.fill();
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_vectorize(ctx, i);
                this._vee(ctx, i);
                ctx.stroke();
            }
        }
        _vee(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();
        }
    }
    exports.VeeHeadView = VeeHeadView;
    VeeHeadView.__name__ = "VeeHeadView";
    class VeeHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
        static init_VeeHead() {
            this.prototype.default_view = VeeHeadView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector]);
            this.override({
                fill_color: "black",
            });
        }
    }
    exports.VeeHead = VeeHead;
    VeeHead.__name__ = "VeeHead";
    VeeHead.init_VeeHead();
    class TeeHeadView extends ArrowHeadView {
        render(ctx, i) {
            if (this.visuals.line.doit) {
                this.visuals.line.set_vectorize(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);
                ctx.stroke();
            }
        }
        clip(_ctx, _i) { }
    }
    exports.TeeHeadView = TeeHeadView;
    TeeHeadView.__name__ = "TeeHeadView";
    class TeeHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
        static init_TeeHead() {
            this.prototype.default_view = TeeHeadView;
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.TeeHead = TeeHead;
    TeeHead.__name__ = "TeeHead";
    TeeHead.init_TeeHead();
},
/* models/annotations/band.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const upper_lower_1 = require(135) /* ./upper_lower */;
    const mixins = tslib_1.__importStar(require(48) /* ../../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();
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_value(ctx);
                ctx.fill();
            }
            // 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]);
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_value(ctx);
                ctx.stroke();
            }
            // 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]);
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_value(ctx);
                ctx.stroke();
            }
        }
    }
    exports.BandView = BandView;
    BandView.__name__ = "BandView";
    class Band extends upper_lower_1.UpperLower {
        constructor(attrs) {
            super(attrs);
        }
        static init_Band() {
            this.prototype.default_view = BandView;
            this.mixins([mixins.Line, mixins.Fill]);
            this.override({
                fill_color: "#fff9ba",
                fill_alpha: 0.4,
                line_color: "#cccccc",
                line_alpha: 0.3,
            });
        }
    }
    exports.Band = Band;
    Band.__name__ = "Band";
    Band.init_Band();
},
/* models/annotations/upper_lower.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(56) /* ./data_annotation */;
    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;
            let _lower_sx;
            if (this.model.properties.lower.units == "data")
                _lower_sx = limit_scale.v_compute(this._lower);
            else
                _lower_sx = limit_view.v_compute(this._lower);
            let _upper_sx;
            if (this.model.properties.upper.units == "data")
                _upper_sx = limit_scale.v_compute(this._upper);
            else
                _upper_sx = limit_view.v_compute(this._upper);
            let _base_sx;
            if (this.model.properties.base.units == "data")
                _base_sx = base_scale.v_compute(this._base);
            else
                _base_sx = base_view.v_compute(this._base);
            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 {
        get dimension() {
            return this.obj.dimension == "width" ? "x" : "y";
        }
        // XXX: a hack to make a coordinate & unit spec
        get units() {
            var _a;
            return (_a = this.spec.units) !== null && _a !== void 0 ? _a : "data";
        }
    }
    exports.XOrYCoordinateSpec = XOrYCoordinateSpec;
    XOrYCoordinateSpec.__name__ = "XOrYCoordinateSpec";
    class UpperLower extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_UpperLower() {
            this.define(() => ({
                dimension: [enums_1.Dimension, "height"],
                lower: [XOrYCoordinateSpec, { field: "lower" }],
                upper: [XOrYCoordinateSpec, { field: "upper" }],
                base: [XOrYCoordinateSpec, { field: "base" }],
            }));
        }
    }
    exports.UpperLower = UpperLower;
    UpperLower.__name__ = "UpperLower";
    UpperLower.init_UpperLower();
},
/* models/annotations/box_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(40) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const bbox_1 = require(99) /* ../../core/util/bbox */;
    exports.EDGE_TOLERANCE = 2.5;
    class BoxAnnotationView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this.bbox = new bbox_1.BBox();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
        }
        _render() {
            const { left, right, top, bottom } = this.model;
            // don't render if *all* position are null
            if (left == null && right == null && top == null && bottom == null)
                return;
            const { frame } = this.plot_view;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const _calc_dim = (dim, dim_units, scale, view, frame_extrema) => {
                let sdim;
                if (dim != null) {
                    if (this.model.screen)
                        sdim = dim;
                    else {
                        if (dim_units == 'data')
                            sdim = scale.compute(dim);
                        else
                            sdim = view.compute(dim);
                    }
                }
                else
                    sdim = frame_extrema;
                return sdim;
            };
            this.bbox = new bbox_1.BBox({
                left: _calc_dim(left, this.model.left_units, xscale, frame.bbox.xview, frame.bbox.left),
                right: _calc_dim(right, this.model.right_units, xscale, frame.bbox.xview, frame.bbox.right),
                top: _calc_dim(top, this.model.top_units, yscale, frame.bbox.yview, frame.bbox.top),
                bottom: _calc_dim(bottom, this.model.bottom_units, yscale, frame.bbox.yview, frame.bbox.bottom),
            });
            this._paint_box();
        }
        _paint_box() {
            const { ctx } = this.layer;
            ctx.save();
            const { left, top, width, height } = this.bbox;
            ctx.beginPath();
            ctx.rect(left, top, width, height);
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_value(ctx);
                ctx.fill();
            }
            if (this.visuals.hatch.doit) {
                this.visuals.hatch.set_value(ctx);
                ctx.fill();
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_value(ctx);
                ctx.stroke();
            }
            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.in_cursor == null)
                return false;
            const bbox = this.interactive_bbox();
            return bbox.contains(sx, sy);
        }
        cursor(sx, sy) {
            const tol = 3;
            const { left, right, bottom, top } = this.bbox;
            if (Math.abs(sx - left) < tol || Math.abs(sx - right) < tol)
                return this.model.ew_cursor;
            else if (Math.abs(sy - bottom) < tol || Math.abs(sy - top) < tol)
                return this.model.ns_cursor;
            else if (this.bbox.contains(sx, sy))
                return this.model.in_cursor;
            else
                return null;
        }
    }
    exports.BoxAnnotationView = BoxAnnotationView;
    BoxAnnotationView.__name__ = "BoxAnnotationView";
    class BoxAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_BoxAnnotation() {
            this.prototype.default_view = BoxAnnotationView;
            this.mixins([mixins.Line, mixins.Fill, mixins.Hatch]);
            this.define(({ Number, Nullable }) => ({
                top: [Nullable(Number), null],
                top_units: [enums_1.SpatialUnits, "data"],
                bottom: [Nullable(Number), null],
                bottom_units: [enums_1.SpatialUnits, "data"],
                left: [Nullable(Number), null],
                left_units: [enums_1.SpatialUnits, "data"],
                right: [Nullable(Number), null],
                right_units: [enums_1.SpatialUnits, "data"],
                /** @deprecated */
                render_mode: [enums_1.RenderMode, "canvas"],
            }));
            this.internal(({ Boolean, String, Nullable }) => ({
                screen: [Boolean, false],
                ew_cursor: [Nullable(String), null],
                ns_cursor: [Nullable(String), null],
                in_cursor: [Nullable(String), null],
            }));
            this.override({
                fill_color: '#fff9ba',
                fill_alpha: 0.4,
                line_color: '#cccccc',
                line_alpha: 0.3,
            });
        }
        update({ left, right, top, bottom }) {
            this.setv({ left, right, top, bottom, screen: true });
        }
    }
    exports.BoxAnnotation = BoxAnnotation;
    BoxAnnotation.__name__ = "BoxAnnotation";
    BoxAnnotation.init_BoxAnnotation();
},
/* models/annotations/color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(40) /* ./annotation */;
    const title_1 = require(138) /* ./title */;
    const cartesian_frame_1 = require(144) /* ../canvas/cartesian_frame */;
    const axes_1 = require(162) /* ../axes */;
    const ticker_1 = require(165) /* ../tickers/ticker */;
    const tickers_1 = require(198) /* ../tickers */;
    const tick_formatter_1 = require(166) /* ../formatters/tick_formatter */;
    const formatters_1 = require(205) /* ../formatters */;
    const labeling_1 = require(169) /* ../policies/labeling */;
    const color_mapper_1 = require(203) /* ../mappers/color_mapper */;
    const continuous_color_mapper_1 = require(202) /* ../mappers/continuous_color_mapper */;
    const mappers_1 = require(209) /* ../mappers */;
    const scales_1 = require(217) /* ../scales */;
    const ranges_1 = require(220) /* ../ranges */;
    const enums_1 = require(20) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const array_1 = require(9) /* ../../core/util/array */;
    const layout_1 = require(221) /* ../../core/layout */;
    const alignments_1 = require(222) /* ../../core/layout/alignments */;
    const border_1 = require(225) /* ../../core/layout/border */;
    const side_panel_1 = require(140) /* ../../core/layout/side_panel */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const types_1 = require(8) /* ../../core/util/types */;
    const MINOR_DIM = 25;
    const MAJOR_DIM_MIN_SCALAR = 0.3;
    const MAJOR_DIM_MAX_SCALAR = 0.8;
    class ColorBarView extends annotation_1.AnnotationView {
        get orientation() {
            return this._orientation;
        }
        initialize() {
            super.initialize();
            const { ticker, formatter, color_mapper } = this.model;
            this._ticker = ticker != "auto" ? ticker : (() => {
                switch (true) {
                    case color_mapper instanceof mappers_1.LogColorMapper:
                        return new tickers_1.LogTicker();
                    case color_mapper instanceof mappers_1.ScanningColorMapper:
                        return new tickers_1.BinnedTicker({ mapper: color_mapper });
                    case color_mapper instanceof mappers_1.CategoricalColorMapper:
                        return new tickers_1.CategoricalTicker();
                    default:
                        return new tickers_1.BasicTicker();
                }
            })();
            this._formatter = formatter != "auto" ? formatter : (() => {
                switch (true) {
                    case this._ticker instanceof tickers_1.LogTicker:
                        return new formatters_1.LogTickFormatter();
                    case color_mapper instanceof mappers_1.CategoricalColorMapper:
                        return new formatters_1.CategoricalTickFormatter();
                    default:
                        return new formatters_1.BasicTickFormatter();
                }
            })();
            /*
            Creates and returns a scale instance that maps the `color_mapper` range
            (low to high) to a screen space range equal to the length of the ColorBar's
            scale image. The scale is used to calculate the tick coordinates in screen
            coordinates for plotting purposes.
        
            Note: the type of color_mapper has to match the type of scale (i.e.
            a LinearColorMapper will require a corresponding LinearScale instance).
            */
            this._major_range = (() => {
                if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                    const { factors } = color_mapper;
                    return new ranges_1.FactorRange({ factors });
                }
                else if (color_mapper instanceof continuous_color_mapper_1.ContinuousColorMapper) {
                    const { min, max } = color_mapper.metrics;
                    return new ranges_1.Range1d({ start: min, end: max });
                }
                else
                    assert_1.unreachable();
            })();
            this._major_scale = (() => {
                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) {
                    const { binning } = color_mapper.metrics;
                    return new scales_1.LinearInterpolationScale({ binning });
                }
                else if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                    return new scales_1.CategoricalScale();
                }
                else
                    assert_1.unreachable();
            })();
            this._minor_range = new ranges_1.Range1d({ start: 0, end: 1 });
            this._minor_scale = new scales_1.LinearScale();
            const major_label_text = mixins.attrs_of(this.model, "major_label_", mixins.Text, true);
            const major_tick_line = mixins.attrs_of(this.model, "major_tick_", mixins.Line, true);
            const minor_tick_line = mixins.attrs_of(this.model, "minor_tick_", mixins.Line, true);
            const title_text = mixins.attrs_of(this.model, "title_", mixins.Text);
            const AxisCls = (() => {
                if (color_mapper instanceof mappers_1.CategoricalColorMapper)
                    return axes_1.CategoricalAxis;
                else if (color_mapper instanceof mappers_1.LogColorMapper)
                    return axes_1.LogAxis;
                else
                    return axes_1.LinearAxis;
            })();
            this._axis = new AxisCls(Object.assign(Object.assign(Object.assign({ ticker: this._ticker, formatter: this._formatter, major_tick_in: this.model.major_tick_in, major_tick_out: this.model.major_tick_out, minor_tick_in: this.model.minor_tick_in, minor_tick_out: this.model.minor_tick_out, major_label_standoff: this.model.label_standoff, major_label_overrides: this.model.major_label_overrides, major_label_policy: this.model.major_label_policy, axis_line_color: null }, major_label_text), major_tick_line), minor_tick_line));
            const { title } = this.model;
            if (title) {
                this._title = new title_1.Title(Object.assign({ text: title, standoff: this.model.title_standoff }, title_text));
            }
        }
        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() {
                    self.parent.request_layout();
                },
            };
            this._axis_view = await build_views_1.build_view(this._axis, { parent });
            if (this._title != null)
                this._title_view = await build_views_1.build_view(this._title, { parent });
        }
        remove() {
            var _a;
            (_a = this._title_view) === null || _a === void 0 ? void 0 : _a.remove();
            this._axis_view.remove();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            // TODO: this.connect(this.model.change, () => this.plot_view.invalidate_layout())
            this.connect(this._ticker.change, () => this.request_render());
            this.connect(this._formatter.change, () => this.request_render());
            this.connect(this.model.color_mapper.metrics_change, () => {
                const range = this._major_range;
                const scale = this._major_scale;
                const { color_mapper } = this.model;
                if (color_mapper instanceof continuous_color_mapper_1.ContinuousColorMapper && range instanceof ranges_1.Range1d) {
                    const { min, max } = color_mapper.metrics;
                    range.setv({ start: min, end: max });
                }
                if (color_mapper instanceof mappers_1.ScanningColorMapper && scale instanceof scales_1.LinearInterpolationScale) {
                    const { binning } = color_mapper.metrics;
                    scale.binning = binning;
                }
                this._set_canvas_image();
                this.plot_view.request_layout(); // this.request_render()
            });
        }
        _set_canvas_image() {
            const { orientation } = this;
            const palette = (() => {
                const { palette } = this.model.color_mapper;
                if (orientation == "vertical")
                    return array_1.reversed(palette);
                else
                    return 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(array_1.range(0, palette.length));
            image_data.data.set(buf8);
            image_ctx.putImageData(image_data, 0, 0);
        }
        update_layout() {
            const { location, width: w, height: h, padding, margin } = this.model;
            const [valign, halign] = (() => {
                if (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;
            })();
            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;
            const [x_scale, y_scale, x_range, y_range] = (() => {
                if (orientation == "horizontal")
                    return [this._major_scale, this._minor_scale, this._major_range, this._minor_range];
                else
                    return [this._minor_scale, this._major_scale, this._minor_range, this._major_range];
            })();
            this._frame = new cartesian_frame_1.CartesianFrame(x_scale, y_scale, x_range, y_range);
            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 (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 {
                    if (types_1.isString(location))
                        return undefined;
                    else {
                        const [left, bottom] = location;
                        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";
                    major_size = this.model.color_mapper.palette.length * MINOR_DIM;
                    min_major_size = { percent: MAJOR_DIM_MIN_SCALAR };
                    max_major_size = { percent: MAJOR_DIM_MAX_SCALAR };
                }
                else {
                    major_policy = "fit";
                    major_size = undefined;
                }
            }
            if (orientation == "horizontal") {
                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 (_title_view != null) {
                if (orientation == "horizontal") {
                    _title_view.panel = new side_panel_1.Panel("above");
                    _title_view.update_layout();
                    top_panel.children.push(_title_view.layout);
                }
                else {
                    _title_view.panel = new side_panel_1.Panel("left");
                    _title_view.update_layout();
                    left_panel.children.push(_title_view.layout);
                }
            }
            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();
            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;
            this._set_canvas_image();
        }
        _render() {
            var _a;
            const { ctx } = this.layer;
            ctx.save();
            this._paint_bbox(ctx, this._inner_layout.bbox);
            this._paint_image(ctx, this._inner_layout.center_panel.bbox);
            (_a = this._title_view) === null || _a === void 0 ? void 0 : _a.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();
        }
        _paint_image(ctx, bbox) {
            const { x, y, width, height } = bbox;
            ctx.save();
            ctx.setImageSmoothingEnabled(false);
            ctx.globalAlpha = this.model.scale_alpha;
            ctx.drawImage(this._image, x, y, width, height);
            if (this.visuals.bar_line.doit) {
                this.visuals.bar_line.set_value(ctx);
                ctx.strokeRect(x, y, width, height);
            }
            ctx.restore();
        }
        serializable_state() {
            const _a = super.serializable_state(), { children = [] } = _a, state = tslib_1.__rest(_a, ["children"]);
            if (this._title_view != null)
                children.push(this._title_view.serializable_state());
            children.push(this._axis_view.serializable_state());
            return Object.assign(Object.assign({}, state), { children });
        }
    }
    exports.ColorBarView = ColorBarView;
    ColorBarView.__name__ = "ColorBarView";
    class ColorBar extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_ColorBar() {
            this.prototype.default_view = ColorBarView;
            this.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],
            ]);
            this.define(({ Alpha, Number, String, Tuple, Dict, Or, Ref, Auto, Nullable }) => ({
                location: [Or(enums_1.Anchor, Tuple(Number, Number)), "top_right"],
                orientation: [Or(enums_1.Orientation, Auto), "auto"],
                title: [Nullable(String), null],
                title_standoff: [Number, 2],
                width: [Or(Number, Auto), "auto"],
                height: [Or(Number, Auto), "auto"],
                scale_alpha: [Alpha, 1.0],
                ticker: [Or(Ref(ticker_1.Ticker), Auto), "auto"],
                formatter: [Or(Ref(tick_formatter_1.TickFormatter), Auto), "auto"],
                major_label_overrides: [Dict(String), {}],
                major_label_policy: [Ref(labeling_1.LabelingPolicy), () => new labeling_1.NoOverlap()],
                color_mapper: [Ref(color_mapper_1.ColorMapper)],
                label_standoff: [Number, 5],
                margin: [Number, 30],
                padding: [Number, 10],
                major_tick_in: [Number, 5],
                major_tick_out: [Number, 0],
                minor_tick_in: [Number, 0],
                minor_tick_out: [Number, 0],
            }));
            this.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",
            });
        }
    }
    exports.ColorBar = ColorBar;
    ColorBar.__name__ = "ColorBar";
    ColorBar.init_ColorBar();
},
/* models/annotations/title.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(139) /* ./text_annotation */;
    const enums_1 = require(20) /* ../../core/enums */;
    const text_1 = require(143) /* ../../core/util/text */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    class TitleView 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 == null || 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');
            const draw = this.model.render_mode == 'canvas' ? this._canvas_text.bind(this) : this._css_text.bind(this);
            draw(this.layer.ctx, text, sx, sy, angle);
        }
        _get_size() {
            const { text } = this.model;
            if (text == null || text.length == 0)
                return { width: 0, height: 0 };
            else {
                const { ctx } = this.layer;
                this.visuals.text.set_value(ctx);
                const { width } = this.layer.ctx.measureText(text);
                const { height } = text_1.font_metrics(ctx.font);
                // 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: 2 + height * this.model.text_line_height + this.model.standoff };
            }
        }
    }
    exports.TitleView = TitleView;
    TitleView.__name__ = "TitleView";
    class Title extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_Title() {
            this.prototype.default_view = TitleView;
            this.mixins([
                mixins.Text,
                ["border_", mixins.Line],
                ["background_", mixins.Fill],
            ]);
            this.define(({ Number, String }) => ({
                text: [String, ""],
                vertical_align: [enums_1.VerticalAlign, "bottom"],
                align: [enums_1.TextAlign, "left"],
                offset: [Number, 0],
                standoff: [Number, 10],
            }));
            this.prototype._props.text_align.options.internal = true;
            this.prototype._props.text_baseline.options.internal = true;
            this.override({
                text_font_size: "13px",
                text_font_style: "bold",
                text_line_height: 1.0,
                background_fill_color: null,
                border_line_color: null,
            });
        }
    }
    exports.Title = Title;
    Title.__name__ = "Title";
    Title.init_Title();
},
/* models/annotations/text_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const annotation_1 = require(40) /* ./annotation */;
    const dom_1 = require(43) /* ../../core/dom */;
    const enums_1 = require(20) /* ../../core/enums */;
    const side_panel_1 = require(140) /* ../../core/layout/side_panel */;
    const text_1 = require(143) /* ../../core/util/text */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    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();
            if (this.model.render_mode == 'css') {
                this.el = dom_1.div();
                this.plot_view.canvas_view.add_overlay(this.el);
            }
        }
        remove() {
            if (this.el != null)
                dom_1.remove(this.el);
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            if (this.model.render_mode == 'css') {
                // dispatch CSS update immediately
                this.connect(this.model.change, () => this.render());
            }
            else {
                this.connect(this.model.change, () => this.request_render());
            }
        }
        render() {
            if (!this.model.visible && this.model.render_mode == "css")
                dom_1.undisplay(this.el);
            super.render();
        }
        _calculate_text_dimensions(ctx, text) {
            const { width } = ctx.measureText(text);
            const { height } = text_1.font_metrics(this.visuals.text.font_value());
            return [width, height];
        }
        _calculate_bounding_box_dimensions(ctx, text) {
            const [width, height] = this._calculate_text_dimensions(ctx, text);
            let x_offset;
            switch (ctx.textAlign) {
                case 'left':
                    x_offset = 0;
                    break;
                case 'center':
                    x_offset = -width / 2;
                    break;
                case 'right':
                    x_offset = -width;
                    break;
                default:
                    assert_1.unreachable();
            }
            // guestimated from https://www.w3.org/TR/2dcontext/#dom-context-2d-textbaseline
            let y_offset;
            switch (ctx.textBaseline) {
                case 'top':
                    y_offset = 0.0;
                    break;
                case 'middle':
                    y_offset = -0.5 * height;
                    break;
                case 'bottom':
                    y_offset = -1.0 * height;
                    break;
                case 'alphabetic':
                    y_offset = -0.8 * height;
                    break;
                case 'hanging':
                    y_offset = -0.17 * height;
                    break;
                case 'ideographic':
                    y_offset = -0.83 * height;
                    break;
                default:
                    assert_1.unreachable();
            }
            return [x_offset, y_offset, width, height];
        }
        _canvas_text(ctx, text, sx, sy, angle) {
            this.visuals.text.set_value(ctx);
            const bbox_dims = this._calculate_bounding_box_dimensions(ctx, text);
            ctx.save();
            ctx.beginPath();
            ctx.translate(sx, sy);
            if (angle)
                ctx.rotate(angle);
            ctx.rect(bbox_dims[0], bbox_dims[1], bbox_dims[2], bbox_dims[3]);
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_value(ctx);
                ctx.fill();
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_value(ctx);
                ctx.stroke();
            }
            if (this.visuals.text.doit) {
                this.visuals.text.set_value(ctx);
                ctx.fillText(text, 0, 0);
            }
            ctx.restore();
        }
        _css_text(ctx, text, sx, sy, angle) {
            const { el } = this;
            assert_1.assert(el != null);
            dom_1.undisplay(el);
            this.visuals.text.set_value(ctx);
            const [x, y] = this._calculate_bounding_box_dimensions(ctx, text);
            el.style.position = "absolute";
            el.style.left = `${sx + x}px`;
            el.style.top = `${sy + y}px`;
            el.style.color = ctx.fillStyle;
            el.style.font = ctx.font;
            el.style.lineHeight = "normal"; // needed to prevent ipynb css override
            if (angle) {
                el.style.transform = `rotate(${angle}rad)`;
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_value(ctx);
                el.style.backgroundColor = ctx.fillStyle;
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_value(ctx);
                // attempt to support vector-style ("8 4 8") line dashing for css mode
                el.style.borderStyle = ctx.lineDash.length < 2 ? "solid" : "dashed";
                el.style.borderWidth = `${ctx.lineWidth}px`;
                el.style.borderColor = ctx.strokeStyle;
            }
            el.textContent = text;
            dom_1.display(el);
        }
    }
    exports.TextAnnotationView = TextAnnotationView;
    TextAnnotationView.__name__ = "TextAnnotationView";
    class TextAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_TextAnnotation() {
            this.define(() => ({
                render_mode: [enums_1.RenderMode, "canvas"],
            }));
        }
    }
    exports.TextAnnotation = TextAnnotation;
    TextAnnotation.__name__ = "TextAnnotation";
    TextAnnotation.init_TextAnnotation();
},
/* core/layout/side_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(141) /* ./types */;
    const layoutable_1 = require(142) /* ./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) {
            this.side = side;
        }
        get dimension() {
            return this.side == "above" || this.side == "below" ? 0 : 1;
        }
        get normals() {
            switch (this.side) {
                case "above": return [0, -1];
                case "below": return [0, 1];
                case "left": return [-1, 0];
                case "right": return [1, 0];
            }
        }
        get orientation() {
            return this.is_horizontal ? "horizontal" : "vertical";
        }
        get is_horizontal() {
            return this.dimension == 0;
        }
        get is_vertical() {
            return this.dimension == 1;
        }
        get_label_text_heuristics(orient) {
            const { side } = this;
            if (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 (types_2.isString(orient))
                return _angle_lookup[this.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 = kinds_1.Enum("fixed", "fit", "min", "max");
},
/* core/layout/layoutable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(141) /* ./types */;
    const bbox_1 = require(99) /* ../util/bbox */;
    const types_2 = require(8) /* ../util/types */;
    const { min, max, round } = Math;
    class Layoutable {
        constructor() {
            this.absolute = false;
            this._bbox = new bbox_1.BBox();
            this._inner_bbox = new bbox_1.BBox();
            this._dirty = false;
            this._handlers = [];
        }
        *[Symbol.iterator]() { }
        get bbox() {
            return this._bbox;
        }
        get inner_bbox() {
            return this._inner_bbox;
        }
        get sizing() {
            return this._sizing;
        }
        set visible(visible) {
            this._sizing.visible = visible;
            this._dirty = true;
        }
        set_sizing(sizing) {
            var _a, _b, _c, _d, _e;
            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 = sizing.visible !== false;
            const halign = (_d = sizing.halign) !== null && _d !== void 0 ? _d : "start";
            const valign = (_e = sizing.valign) !== null && _e !== void 0 ? _e : "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) {
            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 = Math.abs(viewport.width - w_width) + Math.abs(viewport.height - w_height);
                        const h_diff = Math.abs(viewport.width - h_width) + Math.abs(viewport.height - h_height);
                        if (w_diff <= h_diff) {
                            width = w_width;
                            height = w_height;
                        }
                        else {
                            width = h_width;
                            height = h_height;
                        }
                    }
                    else if (gt(width_policy, height_policy)) {
                        height = round(width / aspect);
                    }
                    else {
                        width = round(height * aspect);
                    }
                }
                else if (width_policy == "fixed") {
                    height = round(width / aspect);
                }
                else if (height_policy == "fixed") {
                    width = round(height * aspect);
                }
            }
            return { width, height };
        }
        measure(viewport_size) {
            if (!this.sizing.visible)
                return { width: 0, height: 0 };
            const exact_width = (vw) => {
                return vw == Infinity && this.sizing.width_policy == "fixed" && this.sizing.width != null ? this.sizing.width : vw;
            };
            const exact_height = (vh) => {
                return vh == Infinity && this.sizing.height_policy == "fixed" && this.sizing.height != null ? this.sizing.height : vh;
            };
            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 size = this.apply_aspect(viewport, clipped);
            return Object.assign(Object.assign({}, computed), size);
        }
        compute(viewport = {}) {
            const _viewport = {
                width: viewport.width != null && this.is_width_expanding() ? viewport.width : Infinity,
                height: viewport.height != null && this.is_height_expanding() ? viewport.height : Infinity,
            };
            const size_hint = this.measure(_viewport);
            const { width, height } = size_hint;
            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);
        }
        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 (!types_2.isNumber(min_size))
                    min_size = Math.round(min_size.percent * vsize);
                if (max_size == null)
                    max_size = Infinity;
                else if (!types_2.isNumber(max_size))
                    max_size = Math.round(max_size.percent * vsize);
                return max(min_size, min(size, max_size));
            }
            return {
                width: clip(size.width, viewport.width, this.sizing.min_width, this.sizing.max_width),
                height: clip(size.height, viewport.height, this.sizing.min_height, this.sizing.max_height),
            };
        }
        has_size_changed() {
            const { _dirty } = this;
            this._dirty = false;
            return _dirty;
        }
    }
    exports.Layoutable = Layoutable;
    Layoutable.__name__ = "Layoutable";
    class LayoutItem extends Layoutable {
        _measure(viewport) {
            const { width_policy, height_policy } = this.sizing;
            const width = (() => {
                const { width } = this.sizing;
                if (viewport.width == Infinity) {
                    return width !== null && width !== void 0 ? width : 0;
                }
                else {
                    switch (width_policy) {
                        case "fixed": return width !== null && width !== void 0 ? width : 0;
                        case "min": return width != null ? min(viewport.width, width) : 0;
                        case "fit": return width != null ? min(viewport.width, width) : viewport.width;
                        case "max": return width != null ? max(viewport.width, width) : viewport.width;
                    }
                }
            })();
            const height = (() => {
                const { height } = this.sizing;
                if (viewport.height == Infinity) {
                    return height !== null && height !== void 0 ? height : 0;
                }
                else {
                    switch (height_policy) {
                        case "fixed": return height !== null && height !== void 0 ? height : 0;
                        case "min": return height != null ? min(viewport.height, height) : 0;
                        case "fit": return height != null ? min(viewport.height, height) : viewport.height;
                        case "max": return height != null ? max(viewport.height, height) : viewport.height;
                    }
                }
            })();
            return { width, height };
        }
    }
    exports.LayoutItem = LayoutItem;
    LayoutItem.__name__ = "LayoutItem";
    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 Math.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 Math.max(content_size.height, bounds.height);
                }
            })();
            return { width, height };
        }
    }
    exports.ContentLayoutable = ContentLayoutable;
    ContentLayoutable.__name__ = "ContentLayoutable";
},
/* core/util/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const assert_1 = require(11) /* ./assert */;
    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);
        const ctx = canvas.getContext("2d");
        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 (font_ascent != null && font_descent != null) {
                return {
                    height: font_ascent + font_descent,
                    ascent: font_ascent,
                    descent: font_descent,
                    cap_height: cap_metrics.actualBoundingBoxAscent,
                    x_height: x_metrics.actualBoundingBoxAscent,
                };
            }
            const text_ascent = metrics.actualBoundingBoxAscent;
            const text_descent = metrics.actualBoundingBoxDescent;
            if (text_ascent != null && text_descent != null) {
                return {
                    height: text_ascent + text_descent,
                    ascent: text_ascent,
                    descent: text_descent,
                    cap_height: cap_metrics.actualBoundingBoxAscent,
                    x_height: x_metrics.actualBoundingBoxAscent,
                };
            }
            assert_1.unreachable();
        };
    })();
    const _native_glyph_metrics = (() => {
        const canvas = _offscreen_canvas(0, 0);
        const ctx = canvas.getContext("2d");
        return (glyph, font) => {
            ctx.font = font;
            const metrics = ctx.measureText(glyph);
            const glyph_ascent = metrics.actualBoundingBoxAscent;
            const glyph_descent = metrics.actualBoundingBoxDescent;
            if (glyph_ascent != null && glyph_descent != null) {
                return {
                    width: metrics.width,
                    height: glyph_ascent + glyph_descent,
                    ascent: glyph_ascent,
                    descent: glyph_descent,
                };
            }
            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 _internal_glyph_metrics = (() => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        let cwidth = -1;
        let cheight = -1;
        return (glyph, 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 || cheight < height) {
                cwidth = width;
                canvas.width = width;
                cheight = height;
                canvas.height = height;
            }
            ctx.save();
            ctx.scale(scale, scale);
            ctx.fillStyle = "#f00";
            ctx.fillRect(0, 0, width, height);
            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";
            ctx.fillText(glyph, 0, baseline / scale);
            const size = ctx.measureText(glyph);
            const { data } = ctx.getImageData(0, 0, width, height);
            const ascent = measure_ascent(data) / scale;
            const descent = measure_descent(data) / scale;
            ctx.restore();
            return { width: size.width, height: ascent + descent, ascent, descent };
        };
    })();
    const _font_metrics = (() => {
        try {
            _native_font_metrics("normal 10px sans-serif");
            return _native_font_metrics;
        }
        catch (_a) {
            return _internal_font_metrics;
        }
    })();
    const _glyph_metrics = (() => {
        try {
            _native_glyph_metrics("A", "normal 10px sans-serif");
            return _native_glyph_metrics;
        }
        catch (_a) {
            return _internal_glyph_metrics;
        }
    })();
    const _metrics_cache = new Map();
    function font_metrics(font) {
        let metrics = _metrics_cache.get(font);
        if (metrics == null) {
            // TODO: document.fonts.check(font)
            metrics = { font: _font_metrics(font), glyphs: new Map() };
            _metrics_cache.set(font, metrics);
        }
        return metrics.font;
    }
    exports.font_metrics = font_metrics;
    function glyph_metrics(glyph, font) {
        let metrics = _metrics_cache.get(font);
        if (metrics == null) {
            font_metrics(font);
            metrics = _metrics_cache.get(font);
        }
        let glyph_metrics = metrics.glyphs.get(glyph);
        if (glyph_metrics == null) {
            glyph_metrics = _glyph_metrics(glyph, font);
            metrics.glyphs.set(glyph, glyph_metrics);
        }
        return glyph_metrics;
    }
    exports.glyph_metrics = glyph_metrics;
},
/* models/canvas/cartesian_frame.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const categorical_scale_1 = require(145) /* ../scales/categorical_scale */;
    const log_scale_1 = require(157) /* ../scales/log_scale */;
    const range1d_1 = require(156) /* ../ranges/range1d */;
    const data_range1d_1 = require(159) /* ../ranges/data_range1d */;
    const factor_range_1 = require(104) /* ../ranges/factor_range */;
    const bbox_1 = require(99) /* ../../core/util/bbox */;
    const object_1 = require(13) /* ../../core/util/object */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    class CartesianFrame {
        constructor(in_x_scale, in_y_scale, x_range, y_range, extra_x_ranges = {}, extra_y_ranges = {}) {
            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._bbox = new bbox_1.BBox();
            assert_1.assert(in_x_scale.source_range == null && in_x_scale.target_range == null);
            assert_1.assert(in_y_scale.source_range == null && in_y_scale.target_range == null);
            this._configure_scales();
        }
        get bbox() {
            return this._bbox;
        }
        _get_ranges(range, extra_ranges) {
            return new Map(object_1.entries(Object.assign(Object.assign({}, extra_ranges), { default: range })));
        }
        /*protected*/ _get_scales(scale, ranges, frame_range) {
            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 derived_scale = 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._x_ranges, this._x_target);
            this._y_scales = this._get_scales(this.in_y_scale, this._y_ranges, this._y_target);
        }
        _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 x_scales() {
            return this._x_scales;
        }
        get y_scales() {
            return this._y_scales;
        }
        get x_scale() {
            return this._x_scales.get("default");
        }
        get y_scale() {
            return this._y_scales.get("default");
        }
        /** @deprecated */
        get xscales() {
            return object_1.to_object(this.x_scales);
        }
        /** @deprecated */
        get yscales() {
            return object_1.to_object(this.y_scales);
        }
    }
    exports.CartesianFrame = CartesianFrame;
    CartesianFrame.__name__ = "CartesianFrame";
},
/* models/scales/categorical_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(146) /* ./scale */;
    class CategoricalScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const [factor, offset] = this._linear_compute_state();
            const range = this.source_range;
            return (x) => factor * range.synthetic(x) + offset;
        }
        compute(x) {
            return super._linear_compute(this.source_range.synthetic(x));
        }
        v_compute(xs) {
            return super._linear_v_compute(this.source_range.v_synthetic(xs));
        }
        invert(xprime) {
            return this._linear_invert(xprime);
        }
        v_invert(xprimes) {
            return this._linear_v_invert(xprimes);
        }
    }
    exports.CategoricalScale = CategoricalScale;
    CategoricalScale.__name__ = "CategoricalScale";
},
/* models/scales/scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transforms_1 = require(147) /* ../transforms */;
    const range_1 = require(105) /* ../ranges/range */;
    const range1d_1 = require(156) /* ../ranges/range1d */;
    const types_1 = require(24) /* ../../core/types */;
    class Scale extends transforms_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        static init_Scale() {
            this.internal(({ Ref }) => ({
                source_range: [Ref(range_1.Range)],
                target_range: [Ref(range1d_1.Range1d)],
            }));
        }
        r_compute(x0, x1) {
            if (this.target_range.is_reversed)
                return [this.compute(x1), this.compute(x0)];
            else
                return [this.compute(x0), this.compute(x1)];
        }
        r_invert(sx0, sx1) {
            if (this.target_range.is_reversed)
                return [this.invert(sx1), this.invert(sx0)];
            else
                return [this.invert(sx0), this.invert(sx1)];
        }
        // These are needed by both LinearScale and CategoricalScale and this is the
        // only common ancestor. TODO: Proper MI/Mixin would be better.
        _linear_compute(x) {
            const [factor, offset] = this._linear_compute_state();
            return factor * x + offset;
        }
        _linear_v_compute(xs) {
            const [factor, offset] = this._linear_compute_state();
            const result = new types_1.ScreenArray(xs.length);
            for (let i = 0; i < xs.length; i++)
                result[i] = factor * xs[i] + offset;
            return result;
        }
        _linear_invert(xprime) {
            const [factor, offset] = this._linear_compute_state();
            return (xprime - offset) / factor;
        }
        _linear_v_invert(xprimes) {
            const [factor, offset] = this._linear_compute_state();
            const result = new Float64Array(xprimes.length);
            for (let i = 0; i < xprimes.length; i++)
                result[i] = (xprimes[i] - offset) / factor;
            return result;
        }
        /*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.Scale = Scale;
    Scale.__name__ = "Scale";
    Scale.init_Scale();
},
/* models/transforms/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_transform_1 = require(148) /* ./customjs_transform */;
    __esExport("CustomJSTransform", customjs_transform_1.CustomJSTransform);
    var dodge_1 = require(150) /* ./dodge */;
    __esExport("Dodge", dodge_1.Dodge);
    var interpolator_1 = require(152) /* ./interpolator */;
    __esExport("Interpolator", interpolator_1.Interpolator);
    var jitter_1 = require(153) /* ./jitter */;
    __esExport("Jitter", jitter_1.Jitter);
    var linear_interpolator_1 = require(154) /* ./linear_interpolator */;
    __esExport("LinearInterpolator", linear_interpolator_1.LinearInterpolator);
    var step_interpolator_1 = require(155) /* ./step_interpolator */;
    __esExport("StepInterpolator", step_interpolator_1.StepInterpolator);
    var transform_1 = require(149) /* ./transform */;
    __esExport("Transform", transform_1.Transform);
},
/* models/transforms/customjs_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(149) /* ./transform */;
    const object_1 = require(13) /* ../../core/util/object */;
    const string_1 = require(34) /* ../../core/util/string */;
    class CustomJSTransform extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        static init_CustomJSTransform() {
            this.define(({ Unknown, String, Dict }) => ({
                args: [Dict(Unknown), {}],
                func: [String, ""],
                v_func: [String, ""],
            }));
        }
        get names() {
            return object_1.keys(this.args);
        }
        get values() {
            return object_1.values(this.args);
        }
        _make_transform(name, func) {
            return new Function(...this.names, name, 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;
    CustomJSTransform.__name__ = "CustomJSTransform";
    CustomJSTransform.init_CustomJSTransform();
},
/* models/transforms/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    class Transform extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Transform = Transform;
    Transform.__name__ = "Transform";
},
/* models/transforms/dodge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const range_transform_1 = require(151) /* ./range_transform */;
    class Dodge extends range_transform_1.RangeTransform {
        constructor(attrs) {
            super(attrs);
        }
        static init_Dodge() {
            this.define(({ Number }) => ({
                value: [Number, 0],
            }));
        }
        _compute(x) {
            return x + this.value;
        }
    }
    exports.Dodge = Dodge;
    Dodge.__name__ = "Dodge";
    Dodge.init_Dodge();
},
/* models/transforms/range_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(149) /* ./transform */;
    const range_1 = require(105) /* ../ranges/range */;
    const factor_range_1 = require(104) /* ../ranges/factor_range */;
    const types_1 = require(24) /* ../../core/types */;
    const types_2 = require(8) /* ../../core/util/types */;
    class RangeTransform extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        static init_RangeTransform() {
            this.define(({ Ref, Nullable }) => ({
                range: [Nullable(Ref(range_1.Range)), null],
            }));
        }
        v_compute(xs0) {
            let xs;
            if (this.range instanceof factor_range_1.FactorRange)
                xs = this.range.v_synthetic(xs0);
            else if (types_2.isArrayableOf(xs0, types_2.isNumber))
                xs = xs0;
            else
                throw new Error("unexpected");
            const result = new (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 (types_2.isNumber(x))
                return this._compute(x);
            else
                throw new Error("unexpected");
        }
    }
    exports.RangeTransform = RangeTransform;
    RangeTransform.__name__ = "RangeTransform";
    RangeTransform.init_RangeTransform();
},
/* models/transforms/interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(149) /* ./transform */;
    const columnar_data_source_1 = require(57) /* ../sources/columnar_data_source */;
    const types_1 = require(24) /* ../../core/types */;
    const array_1 = require(9) /* ../../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;
        }
        static init_Interpolator() {
            this.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],
            }));
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.change, () => this._sorted_dirty = true);
        }
        v_compute(xs) {
            const ArrayType = 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 (types_2.isString(this.x) && types_2.isString(this.y) && this.data != null) {
                const column_names = this.data.columns();
                if (!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 (!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 (types_2.isArray(this.x) && 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 (types_1.infer_type(tsx))(n);
            this._y_sorted = new (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;
    Interpolator.__name__ = "Interpolator";
    Interpolator.init_Interpolator();
},
/* models/transforms/jitter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const range_transform_1 = require(151) /* ./range_transform */;
    const enums_1 = require(20) /* ../../core/enums */;
    const bokeh_math = tslib_1.__importStar(require(10) /* ../../core/util/math */);
    class Jitter extends range_transform_1.RangeTransform {
        constructor(attrs) {
            super(attrs);
        }
        static init_Jitter() {
            this.define(({ Number }) => ({
                mean: [Number, 0],
                width: [Number, 1],
                distribution: [enums_1.Distribution, "uniform"],
            }));
        }
        v_compute(xs0) {
            if (this.previous_values != null && this.previous_values.length == xs0.length)
                return this.previous_values;
            this.previous_values = super.v_compute(xs0);
            return this.previous_values;
        }
        _compute(x) {
            switch (this.distribution) {
                case "uniform":
                    return x + this.mean + (bokeh_math.random() - 0.5) * this.width;
                case "normal":
                    return x + bokeh_math.rnorm(this.mean, this.width);
            }
        }
    }
    exports.Jitter = Jitter;
    Jitter.__name__ = "Jitter";
    Jitter.init_Jitter();
},
/* models/transforms/linear_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(9) /* ../../core/util/array */;
    const interpolator_1 = require(152) /* ./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 = 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) {
    __esModule();
    const interpolator_1 = require(152) /* ./interpolator */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(9) /* ../../core/util/array */;
    class StepInterpolator extends interpolator_1.Interpolator {
        constructor(attrs) {
            super(attrs);
        }
        static init_StepInterpolator() {
            this.define(() => ({
                mode: [enums_1.StepMode, "after"],
            }));
        }
        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 = array_1.find_last_index(this._x_sorted, num => x >= num);
                    break;
                }
                case "before": {
                    ind = array_1.find_index(this._x_sorted, num => x <= num);
                    break;
                }
                case "center": {
                    const diffs = array_1.map(this._x_sorted, (tx) => Math.abs(tx - x));
                    const mdiff = array_1.min(diffs);
                    ind = 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;
    StepInterpolator.__name__ = "StepInterpolator";
    StepInterpolator.init_StepInterpolator();
},
/* models/ranges/range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const range_1 = require(105) /* ./range */;
    class Range1d extends range_1.Range {
        constructor(attrs) {
            super(attrs);
        }
        static init_Range1d() {
            this.define(({ Number, Nullable }) => ({
                start: [Number, 0],
                end: [Number, 1],
                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;
                        },
                    }],
            }));
        }
        _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.setv({ bounds: [min, max] }, { silent: true });
            }
        }
        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 Range1d({ 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 Range1d({ start, end });
        }
    }
    exports.Range1d = Range1d;
    Range1d.__name__ = "Range1d";
    Range1d.init_Range1d();
},
/* models/scales/log_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_scale_1 = require(158) /* ./continuous_scale */;
    const types_1 = require(24) /* ../../core/types */;
    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;
                }
            };
        }
        compute(x) {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            let value;
            if (inter_factor == 0)
                value = 0;
            else {
                const _x = (Math.log(x) - inter_offset) / inter_factor;
                if (isFinite(_x))
                    value = _x * factor + offset;
                else
                    value = NaN;
            }
            return value;
        }
        v_compute(xs) {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            const result = new types_1.ScreenArray(xs.length);
            if (inter_factor == 0) {
                for (let i = 0; i < xs.length; i++)
                    result[i] = 0;
            }
            else {
                for (let i = 0; i < xs.length; i++) {
                    const _x = (Math.log(xs[i]) - inter_offset) / inter_factor;
                    let value;
                    if (isFinite(_x))
                        value = _x * factor + offset;
                    else
                        value = NaN;
                    result[i] = value;
                }
            }
            return result;
        }
        invert(xprime) {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            const value = (xprime - offset) / factor;
            return Math.exp(inter_factor * value + inter_offset);
        }
        v_invert(xprimes) {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            const result = new Float64Array(xprimes.length);
            for (let i = 0; i < xprimes.length; i++) {
                const value = (xprimes[i] - offset) / factor;
                result[i] = Math.exp(inter_factor * value + inter_offset);
            }
            return result;
        }
        _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.log(start) / Math.log(10);
                    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) - Math.log(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/continuous_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(146) /* ./scale */;
    class ContinuousScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContinuousScale = ContinuousScale;
    ContinuousScale.__name__ = "ContinuousScale";
},
/* models/ranges/data_range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_range_1 = require(160) /* ./data_range */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(9) /* ../../core/util/array */;
    const logging_1 = require(19) /* ../../core/logging */;
    const bbox = tslib_1.__importStar(require(99) /* ../../core/util/bbox */);
    const util_1 = require(161) /* ../util */;
    class DataRange1d extends data_range_1.DataRange {
        constructor(attrs) {
            super(attrs);
            this.have_updated_interactively = false;
        }
        static init_DataRange1d() {
            this.define(({ Boolean, Number, Nullable }) => ({
                start: [Number],
                end: [Number],
                range_padding: [Number, 0.1],
                range_padding_units: [enums_1.PaddingUnits, "percent"],
                flipped: [Boolean, false],
                follow: [Nullable(enums_1.StartEnd), null],
                follow_interval: [Nullable(Number), null],
                default_span: [Number, 2.0],
                only_visible: [Boolean, false],
            }));
            this.internal(({ Enum }) => ({
                scale_hint: [Enum("log", "auto"), "auto"],
            }));
        }
        initialize() {
            super.initialize();
            this._initial_start = this.start;
            this._initial_end = this.end;
            this._initial_range_padding = this.range_padding;
            this._initial_range_padding_units = this.range_padding_units;
            this._initial_follow = this.follow;
            this._initial_follow_interval = this.follow_interval;
            this._initial_default_span = this.default_span;
            this._plot_bounds = new Map();
        }
        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, names } = this;
            const all_renderers = array_1.concat(this.plots.map((plot) => plot.data_renderers));
            return util_1.compute_renderers(renderers.length == 0 ? "auto" : renderers, all_renderers, names);
        }
        /*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 rect of plot_bounds) {
                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.log(min) / Math.log(10);
                }
                else {
                    let log_min, log_max;
                    if (this.range_padding_units == "percent") {
                        log_min = Math.log(min) / Math.log(10);
                        log_max = Math.log(max) / Math.log(10);
                        span = (log_max - log_min) * (1 + range_padding);
                    }
                    else {
                        log_min = Math.log(min - range_padding) / Math.log(10);
                        log_max = Math.log(max + range_padding) / Math.log(10);
                        span = log_max - log_min;
                    }
                    center = (log_min + log_max) / 2.0;
                }
                start = 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.values(), 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.setv({ bounds: [start, end] }, { silent: true });
                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;
    DataRange1d.__name__ = "DataRange1d";
    DataRange1d.init_DataRange1d();
},
/* models/ranges/data_range.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const range_1 = require(105) /* ./range */;
    const data_renderer_1 = require(62) /* ../renderers/data_renderer */;
    class DataRange extends range_1.Range {
        constructor(attrs) {
            super(attrs);
        }
        static init_DataRange() {
            this.define(({ String, Array, Ref }) => ({
                names: [Array(String), []],
                renderers: [Array(Ref(data_renderer_1.DataRenderer)), []],
            }));
        }
    }
    exports.DataRange = DataRange;
    DataRange.__name__ = "DataRange";
    DataRange.init_DataRange();
},
/* models/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(9) /* ../core/util/array */;
    function compute_renderers(renderers, all_renderers, names) {
        if (renderers == null)
            return [];
        let result = renderers == "auto" ? all_renderers : renderers;
        if (names.length > 0)
            result = result.filter((r) => array_1.includes(names, r.name));
        return result;
    }
    exports.compute_renderers = compute_renderers;
},
/* models/axes/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var axis_1 = require(163) /* ./axis */;
    __esExport("Axis", axis_1.Axis);
    var categorical_axis_1 = require(170) /* ./categorical_axis */;
    __esExport("CategoricalAxis", categorical_axis_1.CategoricalAxis);
    var continuous_axis_1 = require(173) /* ./continuous_axis */;
    __esExport("ContinuousAxis", continuous_axis_1.ContinuousAxis);
    var datetime_axis_1 = require(174) /* ./datetime_axis */;
    __esExport("DatetimeAxis", datetime_axis_1.DatetimeAxis);
    var linear_axis_1 = require(175) /* ./linear_axis */;
    __esExport("LinearAxis", linear_axis_1.LinearAxis);
    var log_axis_1 = require(192) /* ./log_axis */;
    __esExport("LogAxis", log_axis_1.LogAxis);
    var mercator_axis_1 = require(195) /* ./mercator_axis */;
    __esExport("MercatorAxis", mercator_axis_1.MercatorAxis);
},
/* models/axes/axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const guide_renderer_1 = require(164) /* ../renderers/guide_renderer */;
    const ticker_1 = require(165) /* ../tickers/ticker */;
    const tick_formatter_1 = require(166) /* ../formatters/tick_formatter */;
    const labeling_1 = require(169) /* ../policies/labeling */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const types_1 = require(24) /* ../../core/types */;
    const side_panel_1 = require(140) /* ../../core/layout/side_panel */;
    const array_1 = require(9) /* ../../core/util/array */;
    const types_2 = require(8) /* ../../core/util/types */;
    const graphics_1 = require(167) /* ../../core/graphics */;
    const factor_range_1 = require(104) /* ../ranges/factor_range */;
    const { abs } = Math;
    class AxisView extends guide_renderer_1.GuideRendererView {
        update_layout() {
            this.layout = new side_panel_1.SideLayout(this.panel, () => this.get_size(), true);
        }
        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;
        }
        _render() {
            var _a;
            if (!this.is_renderable)
                return;
            const { tick_coords, extents } = this;
            const ctx = this.layer.ctx;
            ctx.save();
            this._draw_rule(ctx, extents);
            this._draw_major_ticks(ctx, extents, tick_coords);
            this._draw_minor_ticks(ctx, extents, tick_coords);
            this._draw_major_labels(ctx, extents, tick_coords);
            this._draw_axis_label(ctx, extents, tick_coords);
            (_a = this._paint) === null || _a === void 0 ? void 0 : _a.call(this, ctx, extents, tick_coords);
            ctx.restore();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.plot_view.request_layout());
        }
        get needs_clip() {
            return this.model.fixed_location != null;
        }
        // drawing sub functions -----------------------------------------------------
        _draw_rule(ctx, _extents) {
            if (!this.visuals.axis_line.doit)
                return;
            const [xs, ys] = this.rule_coords;
            const [sxs, sys] = this.coordinates.map_to_screen(xs, ys);
            const [nx, ny] = this.normals;
            const [xoff, yoff] = this.offsets;
            this.visuals.axis_line.set_value(ctx);
            ctx.beginPath();
            for (let i = 0; i < sxs.length; i++) {
                const sx = Math.round(sxs[i] + nx * xoff);
                const sy = Math.round(sys[i] + ny * yoff);
                ctx.lineTo(sx, sy);
            }
            ctx.stroke();
        }
        _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, this.panel.side, standoff, visuals);
        }
        _axis_label_extent() {
            const text = this.model.axis_label;
            if (!text)
                return 0;
            const axis_label = new graphics_1.TextBox({ text });
            axis_label.angle = this.panel.get_label_angle_heuristic("parallel");
            axis_label.visuals = this.visuals.axis_label_text;
            const size = axis_label.size();
            const extent = this.dimension == 0 ? size.height : size.width;
            const standoff = this.model.axis_label_standoff;
            const padding = 3;
            return extent > 0 ? standoff + extent + padding : 0;
        }
        _draw_axis_label(ctx, extents, _tick_coords) {
            const text = this.model.axis_label;
            if (!text || this.model.fixed_location != null)
                return;
            const axis_label = new graphics_1.TextBox({ text });
            axis_label.angle = this.panel.get_label_angle_heuristic("parallel");
            axis_label.visuals = this.visuals.axis_label_text;
            const [sx, sy] = (() => {
                const { bbox } = this.layout;
                switch (this.panel.side) {
                    case "above":
                        return [bbox.hcenter, bbox.bottom];
                    case "below":
                        return [bbox.hcenter, bbox.top];
                    case "left":
                        return [bbox.right, bbox.vcenter];
                    case "right":
                        return [bbox.left, bbox.vcenter];
                }
            })();
            const [nx, ny] = this.normals;
            const standoff = extents.tick + extents.tick_label + this.model.axis_label_standoff;
            const { vertical_align, align } = this.panel.get_label_text_heuristics("parallel");
            axis_label.position = {
                sx: sx + nx * standoff,
                sy: sy + ny * standoff,
                x_anchor: align,
                y_anchor: vertical_align,
            };
            axis_label.align = align;
            axis_label.paint(ctx);
        }
        _draw_ticks(ctx, coords, tin, tout, visuals) {
            if (!visuals.doit)
                return;
            const [x, y] = coords;
            const [sxs, sys] = this.coordinates.map_to_screen(x, y);
            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, _side, standoff, visuals) {
            if (!visuals.doit || labels.length == 0)
                return;
            const [dxs, dys] = coords;
            const [sxs, sys] = this.coordinates.map_to_screen(dxs, dys);
            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;
            labels.angle = angle;
            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.parent.canvas_view.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() {
            return this.model.major_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: array_1.sum(tick_labels),
                axis_label: this._axis_label_extent(),
            };
        }
        _oriented_labels_extent(labels, orient, standoff, visuals) {
            if (labels.length == 0)
                return 0;
            const angle = this.panel.get_label_angle_heuristic(orient);
            labels.visuals = visuals;
            labels.angle = angle;
            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_overrides } = this.model;
            for (let i = 0; i < ticks.length; i++) {
                const override = major_label_overrides[ticks[i]];
                if (override != null)
                    labels[i] = new graphics_1.TextBox({ text: override });
            }
            return new graphics_1.GraphicsBoxes(labels);
        }
        get offsets() {
            // If we have a fixed_position then we should respect that exactly and
            // not apply any offsets (https://github.com/bokeh/bokeh/issues/8552)
            if (this.model.fixed_location != null)
                return [0, 0];
            const { frame } = this.plot_view;
            let [xoff, yoff] = [0, 0];
            switch (this.panel.side) {
                case "below":
                    yoff = abs(this.layout.bbox.top - frame.bbox.bottom);
                    break;
                case "above":
                    yoff = abs(this.layout.bbox.bottom - frame.bbox.top);
                    break;
                case "right":
                    xoff = abs(this.layout.bbox.left - frame.bbox.right);
                    break;
                case "left":
                    xoff = abs(this.layout.bbox.right - frame.bbox.left);
                    break;
            }
            return [xoff, yoff];
        }
        get ranges() {
            const i = this.dimension;
            const j = (i + 1) % 2;
            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 = (i + 1) % 2;
            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 tick_coords() {
            const i = this.dimension;
            const j = (i + 1) % 2;
            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 (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);
                throw new Error("unexpected");
            }
            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;
            }
        }
        // }}}
        serializable_state() {
            return Object.assign(Object.assign({}, super.serializable_state()), { bbox: this.layout.bbox.box });
        }
    }
    exports.AxisView = AxisView;
    AxisView.__name__ = "AxisView";
    class Axis extends guide_renderer_1.GuideRenderer {
        constructor(attrs) {
            super(attrs);
        }
        static init_Axis() {
            this.prototype.default_view = AxisView;
            this.mixins([
                ["axis_", mixins.Line],
                ["major_tick_", mixins.Line],
                ["minor_tick_", mixins.Line],
                ["major_label_", mixins.Text],
                ["axis_label_", mixins.Text],
            ]);
            this.define(({ Any, Int, Number, String, Ref, Dict, Tuple, Or, Nullable, Auto }) => ({
                bounds: [Or(Tuple(Number, Number), Auto), "auto"],
                ticker: [Ref(ticker_1.Ticker)],
                formatter: [Ref(tick_formatter_1.TickFormatter)],
                axis_label: [Nullable(String), ""],
                axis_label_standoff: [Int, 5],
                major_label_standoff: [Int, 5],
                major_label_orientation: [Or(enums_1.TickLabelOrientation, Number), "horizontal"],
                major_label_overrides: [Dict(String), {}],
                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],
            }));
            this.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",
            });
        }
    }
    exports.Axis = Axis;
    Axis.__name__ = "Axis";
    Axis.init_Axis();
},
/* models/renderers/guide_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const renderer_1 = require(41) /* ./renderer */;
    class GuideRendererView extends renderer_1.RendererView {
    }
    exports.GuideRendererView = GuideRendererView;
    GuideRendererView.__name__ = "GuideRendererView";
    class GuideRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        static init_GuideRenderer() {
            this.override({
                level: "guide",
            });
        }
    }
    exports.GuideRenderer = GuideRenderer;
    GuideRenderer.__name__ = "GuideRenderer";
    GuideRenderer.init_GuideRenderer();
},
/* models/tickers/ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../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(53) /* ../../model */;
    const graphics_1 = require(167) /* ../../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";
},
/* core/graphics.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const bbox_1 = require(99) /* ./util/bbox */;
    const text_1 = require(143) /* ./util/text */;
    const array_1 = require(9) /* ./util/array */;
    const types_1 = require(8) /* ./util/types */;
    const affine_1 = require(168) /* ./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;
        }
        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)
                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)
                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 {
        constructor({ text }) {
            super();
            this.align = "left";
            this.text = text;
        }
        //padding: Padding
        set visuals(v) {
            const color = v.text_color.get_value();
            const alpha = v.text_alpha.get_value();
            const style = v.text_font_style.get_value();
            let size = v.text_font_size.get_value();
            const face = v.text_font.get_value();
            const { font_size_scale } = this;
            if (font_size_scale != 1.0) {
                const match = size.match(/^\s*(\d+(\.\d+)?)px\s*$/);
                if (match != null) {
                    const [, px] = match;
                    const npx = Number(px);
                    if (!isNaN(npx))
                        size = `${npx * font_size_scale}px`;
                }
            }
            const font = `${style} ${size} ${face}`;
            this.font = font;
            this.color = color_1.color2css(color, alpha);
            this.line_height = v.text_line_height.get_value();
        }
        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";
                /*
                const {font} = this
                const fmetrics = font_metrics(font)
          
                let max_ascent = 0
                let max_descent = 0
                for (const c of this.text) {
                  const metrics = glyph_metrics(c, font)
                  max_ascent = Math.max(metrics.ascent)
                  max_descent = Math.max(metrics.descent)
                }
          
                const ascent = (() => {
                  if (max_ascent > fmetrics.cap_height)
                    return "ascent"
                  else if (max_ascent > fmetrics.x_height)
                    return "cap"
                  else
                    return "x"
                })()
          
                return max_descent > 0 ? `${ascent}_descent` as const : ascent
                */
            }
        }
        _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 = 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) => 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 = 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 = "left", y_anchor = "center" } = this.position;
            const x = sx - (() => {
                if (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 (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 = 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) => 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 = array_1.max(widths) * w_scale;
            const height = (text_height + line_spacing * (nlines - 1)) * h_scale;
            ctx.save();
            ctx.fillStyle = this.color;
            ctx.font = this.font;
            ctx.textAlign = "left";
            ctx.textBaseline = "alphabetic";
            const { sx, sy } = this.position;
            const { align } = this;
            const { angle } = this;
            if (angle) {
                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) => exports.text_width(word, font));
                    const word_spacing = (width - array_1.sum(word_widths)) / (nwords - 1);
                    for (let j = 0; j < nwords; j++) {
                        ctx.fillText(words[j], xij, y);
                        xij += word_widths[j] + word_spacing;
                    }
                    y += /*heights[i]*/ text_line.height + line_spacing;
                }
            }
            else {
                for (let i = 0; i < nlines; i++) {
                    const xi = x + (() => {
                        switch (align) {
                            case "left": return 0;
                            case "center": return 0.5 * (width - widths[i]);
                            case "right": return width - widths[i];
                        }
                    })();
                    ctx.fillStyle = this.color;
                    ctx.fillText(lines[i], xi, y + /*ascents[i]*/ text_line.ascent);
                    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 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 } = 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) {
                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 = "left", y_anchor = "center" } = this.position;
            const x = sx - (() => {
                if (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 (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;
        }
        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 = 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/affine.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    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})`;
        }
        clone() {
            const { a, b, c, d, e, f } = this;
            return new AffineTransform(a, b, c, d, e, f);
        }
        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) {
            const s = sin(angle);
            const c = cos(angle);
            return this.transform(c, s, -s, c, 0, 0);
        }
        rotate_ccw(angle) {
            return this.rotate(-angle);
        }
        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);
        }
    }
    exports.AffineTransform = AffineTransform;
    AffineTransform.__name__ = "AffineTransform";
},
/* models/policies/labeling.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const object_1 = require(13) /* ../../core/util/object */;
    const string_1 = require(34) /* ../../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);
        }
        static init_NoOverlap() {
            this.define(({ Number }) => ({
                min_distance: [Number, 5],
            }));
        }
        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;
    NoOverlap.__name__ = "NoOverlap";
    NoOverlap.init_NoOverlap();
    class CustomLabelingPolicy extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        static init_CustomLabelingPolicy() {
            this.define(({ Unknown, String, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            }));
        }
        get names() {
            return object_1.keys(this.args);
        }
        get values() {
            return object_1.values(this.args);
        }
        get func() {
            const code = string_1.use_strict(this.code);
            return new types_2.GeneratorFunction("indices", "bboxes", "distance", ...this.names, code);
        }
        filter(indices, bboxes, distance) {
            const obj = Object.create(null);
            const generator = this.func.call(obj, indices, bboxes, distance, ...this.values);
            let result = generator.next();
            if (result.done && result.value !== undefined) {
                const { value } = result;
                if (value instanceof types_2.Indices)
                    return value;
                else if (value === undefined)
                    return indices;
                else if (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 (!result.done);
                return types_2.Indices.from_indices(indices.size, array);
            }
        }
    }
    exports.CustomLabelingPolicy = CustomLabelingPolicy;
    CustomLabelingPolicy.__name__ = "CustomLabelingPolicy";
    CustomLabelingPolicy.init_CustomLabelingPolicy();
},
/* models/axes/categorical_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const axis_1 = require(163) /* ./axis */;
    const categorical_ticker_1 = require(171) /* ../tickers/categorical_ticker */;
    const categorical_tick_formatter_1 = require(172) /* ../formatters/categorical_tick_formatter */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const graphics_1 = require(167) /* ../../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 || range.tops.length < 2 || !this.visuals.separator_line.doit)
                return;
            const dim = this.dimension;
            const alt = (dim + 1) % 2;
            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, this.panel.side, 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) => 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 = (i + 1) % 2;
            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);
        }
        static init_CategoricalAxis() {
            this.prototype.default_view = CategoricalAxisView;
            this.mixins([
                ["separator_", mixins.Line],
                ["group_", mixins.Text],
                ["subgroup_", mixins.Text],
            ]);
            this.define(({ Number, Or }) => ({
                group_label_orientation: [Or(enums_1.TickLabelOrientation, Number), "parallel"],
                subgroup_label_orientation: [Or(enums_1.TickLabelOrientation, Number), "parallel"],
            }));
            this.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",
            });
        }
    }
    exports.CategoricalAxis = CategoricalAxis;
    CategoricalAxis.__name__ = "CategoricalAxis";
    CategoricalAxis.init_CategoricalAxis();
},
/* models/tickers/categorical_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ticker_1 = require(165) /* ./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(166) /* ./tick_formatter */;
    const array_1 = require(9) /* ../../core/util/array */;
    class CategoricalTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, _opts) {
            return 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(163) /* ./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) {
    __esModule();
    const linear_axis_1 = require(175) /* ./linear_axis */;
    const datetime_tick_formatter_1 = require(180) /* ../formatters/datetime_tick_formatter */;
    const datetime_ticker_1 = require(185) /* ../tickers/datetime_ticker */;
    class DatetimeAxisView extends linear_axis_1.LinearAxisView {
    }
    exports.DatetimeAxisView = DatetimeAxisView;
    DatetimeAxisView.__name__ = "DatetimeAxisView";
    class DatetimeAxis extends linear_axis_1.LinearAxis {
        constructor(attrs) {
            super(attrs);
        }
        static init_DatetimeAxis() {
            this.prototype.default_view = DatetimeAxisView;
            this.override({
                ticker: () => new datetime_ticker_1.DatetimeTicker(),
                formatter: () => new datetime_tick_formatter_1.DatetimeTickFormatter(),
            });
        }
    }
    exports.DatetimeAxis = DatetimeAxis;
    DatetimeAxis.__name__ = "DatetimeAxis";
    DatetimeAxis.init_DatetimeAxis();
},
/* models/axes/linear_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_axis_1 = require(173) /* ./continuous_axis */;
    const basic_tick_formatter_1 = require(176) /* ../formatters/basic_tick_formatter */;
    const basic_ticker_1 = require(177) /* ../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);
        }
        static init_LinearAxis() {
            this.prototype.default_view = LinearAxisView;
            this.override({
                ticker: () => new basic_ticker_1.BasicTicker(),
                formatter: () => new basic_tick_formatter_1.BasicTickFormatter(),
            });
        }
    }
    exports.LinearAxis = LinearAxis;
    LinearAxis.__name__ = "LinearAxis";
    LinearAxis.init_LinearAxis();
},
/* models/formatters/basic_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(166) /* ./tick_formatter */;
    const string_1 = require(34) /* ../../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;
        }
        static init_BasicTickFormatter() {
            this.define(({ Boolean, Int, Auto, Or }) => ({
                precision: [Or(Int, Auto), "auto"],
                use_scientific: [Boolean, true],
                power_limit_high: [Int, 5],
                power_limit_low: [Int, -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(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] = string_1.to_fixed(ticks[0], x);
                    for (let i = 1; i < ticks.length; i++) {
                        labels[i] = 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;
    BasicTickFormatter.__name__ = "BasicTickFormatter";
    BasicTickFormatter.init_BasicTickFormatter();
},
/* 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/tickers/adaptive_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    const array_1 = require(9) /* ../../core/util/array */;
    const math_1 = require(10) /* ../../core/util/math */;
    class AdaptiveTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_AdaptiveTicker() {
            this.define(({ Number, Array, Nullable }) => ({
                base: [Number, 10.0],
                mantissas: [Array(Number), [1, 2, 5]],
                min_interval: [Number, 0.0],
                max_interval: [Nullable(Number), null],
            }));
        }
        get_min_interval() {
            return this.min_interval;
        }
        get_max_interval() {
            var _a;
            return (_a = this.max_interval) !== null && _a !== void 0 ? _a : 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.
        initialize() {
            super.initialize();
            const prefix_mantissa = array_1.nth(this.mantissas, -1) / this.base;
            const suffix_mantissa = array_1.nth(this.mantissas, 0) * this.base;
            this.extended_mantissas = [prefix_mantissa, ...this.mantissas, suffix_mantissa];
            this.base_factor = 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(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[array_1.argmin(errors)];
            const interval = best_mantissa * ideal_magnitude;
            return math_1.clamp(interval, this.get_min_interval(), this.get_max_interval());
        }
    }
    exports.AdaptiveTicker = AdaptiveTicker;
    AdaptiveTicker.__name__ = "AdaptiveTicker";
    AdaptiveTicker.init_AdaptiveTicker();
},
/* models/tickers/continuous_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ticker_1 = require(165) /* ./ticker */;
    const array_1 = require(9) /* ../../core/util/array */;
    class ContinuousTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        static init_ContinuousTicker() {
            this.define(({ Int }) => ({
                num_minor_ticks: [Int, 5],
                desired_num_ticks: [Int, 6],
            }));
        }
        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 = 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 = 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;
    ContinuousTicker.__name__ = "ContinuousTicker";
    ContinuousTicker.init_ContinuousTicker();
},
/* models/formatters/datetime_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const timezone_1 = tslib_1.__importDefault(require(181) /* timezone */);
    const tick_formatter_1 = require(166) /* ./tick_formatter */;
    const logging_1 = require(19) /* ../../core/logging */;
    const templating_1 = require(182) /* ../../core/util/templating */;
    const array_1 = require(9) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    function _us(t) {
        // From double-precision unix (millisecond) timestamp get
        // microsecond since last second. Precision seems to run
        // out around the hundreds of nanoseconds scale, so rounding
        // to the nearest microsecond should round to a nice
        // microsecond / millisecond tick.
        return Math.round(((t / 1000) % 1) * 1000000);
    }
    function _array(t) {
        return timezone_1.default(t, "%Y %m %d %H %M %S").split(/\s+/).map(e => parseInt(e, 10));
    }
    function _strftime(t, format) {
        if (types_1.isFunction(format)) {
            return format(t);
        }
        else {
            // Python's datetime library augments the microsecond directive %f, which is not
            // supported by the javascript library timezone: http://bigeasy.github.io/timezone/.
            // Use a regular expression to replace %f directive with microseconds.
            // TODO: what should we do for negative microsecond strings?
            const microsecond_replacement_string = templating_1.sprintf("$1%06d", _us(t));
            format = format.replace(/((^|[^%])(%%)*)%f/, microsecond_replacement_string);
            if (format.indexOf("%") == -1) {
                // timezone seems to ignore any strings without any formatting directives,
                // and just return the time argument back instead of the string argument.
                // But we want the string argument, in case a user supplies a format string
                // which doesn't contain a formatting directive or is only using %f.
                return format;
            }
            return timezone_1.default(t, format);
        }
    }
    // Labels of time units, from finest to coarsest.
    const format_order = [
        'microseconds', 'milliseconds', 'seconds', 'minsec', 'minutes', 'hourmin', 'hours', 'days', 'months', 'years',
    ];
    class DatetimeTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
            // Whether or not to strip the leading zeros on tick labels.
            this.strip_leading_zeros = true;
        }
        static init_DatetimeTickFormatter() {
            this.define(({ String, Array }) => ({
                microseconds: [Array(String), ['%fus']],
                milliseconds: [Array(String), ['%3Nms', '%S.%3Ns']],
                seconds: [Array(String), ['%Ss']],
                minsec: [Array(String), [':%M:%S']],
                minutes: [Array(String), [':%M', '%Mm']],
                hourmin: [Array(String), ['%H:%M']],
                hours: [Array(String), ['%Hh', '%H:%M']],
                days: [Array(String), ['%m/%d', '%a%d']],
                months: [Array(String), ['%m/%Y', '%b %Y']],
                years: [Array(String), ['%Y']],
            }));
        }
        initialize() {
            super.initialize();
            // TODO (bev) trigger update on format change
            this._update_width_formats();
        }
        _update_width_formats() {
            const now = +timezone_1.default(new Date());
            const _widths = function (fmt_strings) {
                const sizes = fmt_strings.map((fmt_string) => _strftime(now, fmt_string).length);
                const sorted = array_1.sort_by(array_1.zip(sizes, fmt_strings), ([size]) => size);
                return array_1.unzip(sorted);
            };
            this._width_formats = {
                microseconds: _widths(this.microseconds),
                milliseconds: _widths(this.milliseconds),
                seconds: _widths(this.seconds),
                minsec: _widths(this.minsec),
                minutes: _widths(this.minutes),
                hourmin: _widths(this.hourmin),
                hours: _widths(this.hours),
                days: _widths(this.days),
                months: _widths(this.months),
                years: _widths(this.years),
            };
        }
        // FIXME There is some unfortunate flicker when panning/zooming near the
        // span boundaries.
        // FIXME Rounding is weird at the 20-us scale and below.
        _get_resolution_str(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_secs = resolution_secs * 1.1;
            switch (false) {
                case !(adjusted_secs < 1e-3): return "microseconds";
                case !(adjusted_secs < 1.0): return "milliseconds";
                case !(adjusted_secs < 60): return span_secs >= 60 ? "minsec" : "seconds";
                case !(adjusted_secs < 3600): return span_secs >= 3600 ? "hourmin" : "minutes";
                case !(adjusted_secs < (24 * 3600)): return "hours";
                case !(adjusted_secs < (31 * 24 * 3600)): return "days";
                case !(adjusted_secs < (365 * 24 * 3600)): return "months";
                default: return "years";
            }
        }
        doFormat(ticks, _opts) {
            // In order to pick the right set of labels, we need to determine
            // the resolution of the ticks.  We can do this using a ticker if
            // it's provided, or by computing the resolution from the actual
            // ticks we've been given.
            if (ticks.length == 0)
                return [];
            const span = Math.abs(ticks[ticks.length - 1] - ticks[0]) / 1000.0;
            const r = span / (ticks.length - 1);
            const resol = this._get_resolution_str(r, span);
            const [, [format]] = this._width_formats[resol];
            // Apply the format to the tick values
            const labels = [];
            const resol_ndx = format_order.indexOf(resol);
            // This dictionary maps the name of a time resolution (in @format_order)
            // to its index in a time.localtime() timetuple.  The default is to map
            // everything to index 0, which is year.  This is not ideal; it might cause
            // a problem with the tick at midnight, january 1st, 0 a.d. being incorrectly
            // promoted at certain tick resolutions.
            const time_tuple_ndx_for_resol = {};
            for (const fmt of format_order) {
                time_tuple_ndx_for_resol[fmt] = 0;
            }
            time_tuple_ndx_for_resol.seconds = 5;
            time_tuple_ndx_for_resol.minsec = 4;
            time_tuple_ndx_for_resol.minutes = 4;
            time_tuple_ndx_for_resol.hourmin = 3;
            time_tuple_ndx_for_resol.hours = 3;
            // As we format each tick, check to see if we are at a boundary of the
            // next higher unit of time.  If so, replace the current format with one
            // from that resolution.  This is not the best heuristic in the world,
            // but it works!  There is some trickiness here due to having to deal
            // with hybrid formats in a reasonable manner.
            for (const t of ticks) {
                let s, tm;
                try {
                    tm = _array(t);
                    s = _strftime(t, format);
                }
                catch (error) {
                    logging_1.logger.warn(`unable to format tick for timestamp value ${t}`);
                    logging_1.logger.warn(` - ${error}`);
                    labels.push("ERR");
                    continue;
                }
                let hybrid_handled = false;
                let next_ndx = resol_ndx;
                // The way to check that we are at the boundary of the next unit of
                // time is by checking that we have 0 units of the resolution, i.e.
                // we are at zero minutes, so display hours, or we are at zero seconds,
                // so display minutes (and if that is zero as well, then display hours).
                while (tm[time_tuple_ndx_for_resol[format_order[next_ndx]]] == 0) {
                    let next_format;
                    next_ndx += 1;
                    if (next_ndx == format_order.length)
                        break;
                    if ((resol == "minsec" || resol == "hourmin") && !hybrid_handled) {
                        if ((resol == "minsec" && tm[4] == 0 && tm[5] != 0) || (resol == "hourmin" && tm[3] == 0 && tm[4] != 0)) {
                            next_format = this._width_formats[format_order[resol_ndx - 1]][1][0];
                            s = _strftime(t, next_format);
                            break;
                        }
                        else {
                            hybrid_handled = true;
                        }
                    }
                    next_format = this._width_formats[format_order[next_ndx]][1][0];
                    s = _strftime(t, next_format);
                }
                // TODO: should expose this in api. %H, %d, etc use leading zeros and
                // users might prefer to see them lined up correctly.
                if (this.strip_leading_zeros) {
                    let ss = s.replace(/^0+/g, "");
                    if (ss != s && isNaN(parseInt(ss))) {
                        // If the string can now be parsed as starting with an integer, then
                        // leave all zeros stripped, otherwise start with a zero. Hence:
                        // A label such as '000ms' should leave one zero.
                        // A label such as '001ms' or '0-1ms' should not leave a leading zero.
                        ss = `0${ss}`;
                    }
                    labels.push(ss);
                }
                else
                    labels.push(s);
            }
            return labels;
        }
    }
    exports.DatetimeTickFormatter = DatetimeTickFormatter;
    DatetimeTickFormatter.__name__ = "DatetimeTickFormatter";
    DatetimeTickFormatter.init_DatetimeTickFormatter();
},
/* timezone/index.js */ function _(require, module, exports, __esModule, __esExport) {
    !function (definition) {
        if (typeof module == "object" && module.exports)
            module.exports = definition();
        else if (typeof define == "function")
            define(definition);
        else
            this.tz = definition();
    }(function () {
        /*
          function die () {
            console.log.apply(console, __slice.call(arguments, 0));
            return process.exit(1);
          }
        
          function say () { return console.log.apply(console, __slice.call(arguments, 0)) }
        */
        function actualize(entry, rule, year) {
            var actualized, date = rule.day[1];
            do {
                actualized = new Date(Date.UTC(year, rule.month, Math.abs(date++)));
            } while (rule.day[0] < 7 && actualized.getUTCDay() != rule.day[0]);
            actualized = {
                clock: rule.clock,
                sort: actualized.getTime(),
                rule: rule,
                save: rule.save * 6e4,
                offset: entry.offset
            };
            actualized[actualized.clock] = actualized.sort + rule.time * 6e4;
            if (actualized.posix) {
                actualized.wallclock = actualized[actualized.clock] + (entry.offset + rule.saved);
            }
            else {
                actualized.posix = actualized[actualized.clock] - (entry.offset + rule.saved);
            }
            return actualized;
        }
        function find(request, clock, time) {
            var i, I, entry, found, zone = request[request.zone], actualized = [], abbrev, rules, j, year = new Date(time).getUTCFullYear(), off = 1;
            for (i = 1, I = zone.length; i < I; i++)
                if (zone[i][clock] <= time)
                    break;
            entry = zone[i];
            if (entry.rules) {
                rules = request[entry.rules];
                for (j = year + 1; j >= year - off; --j)
                    for (i = 0, I = rules.length; i < I; i++)
                        if (rules[i].from <= j && j <= rules[i].to)
                            actualized.push(actualize(entry, rules[i], j));
                        else if (rules[i].to < j && off == 1)
                            off = j - rules[i].to;
                actualized.sort(function (a, b) { return a.sort - b.sort; });
                for (i = 0, I = actualized.length; i < I; i++) {
                    if (time >= actualized[i][clock] && actualized[i][actualized[i].clock] > entry[actualized[i].clock])
                        found = actualized[i];
                }
            }
            if (found) {
                if (abbrev = /^(.*)\/(.*)$/.exec(entry.format)) {
                    found.abbrev = abbrev[found.save ? 2 : 1];
                }
                else {
                    found.abbrev = entry.format.replace(/%s/, found.rule.letter);
                }
            }
            return found || entry;
        }
        function convertToWallclock(request, posix) {
            if (request.zone == "UTC")
                return posix;
            request.entry = find(request, "posix", posix);
            return posix + request.entry.offset + request.entry.save;
        }
        function convertToPOSIX(request, wallclock) {
            if (request.zone == "UTC")
                return wallclock;
            var entry, diff;
            request.entry = entry = find(request, "wallclock", wallclock);
            diff = wallclock - entry.wallclock;
            return 0 < diff && diff < entry.save ? null : wallclock - entry.offset - entry.save;
        }
        function adjust(request, posix, match) {
            var increment = +(match[1] + 1) // conversion necessary for week day addition
            , offset = match[2] * increment, index = UNITS.indexOf(match[3].toLowerCase()), date;
            if (index > 9) {
                posix += offset * TIME[index - 10];
            }
            else {
                date = new Date(convertToWallclock(request, posix));
                if (index < 7) {
                    while (offset) {
                        date.setUTCDate(date.getUTCDate() + increment);
                        if (date.getUTCDay() == index)
                            offset -= increment;
                    }
                }
                else if (index == 7) {
                    date.setUTCFullYear(date.getUTCFullYear() + offset);
                }
                else if (index == 8) {
                    date.setUTCMonth(date.getUTCMonth() + offset);
                }
                else {
                    date.setUTCDate(date.getUTCDate() + offset);
                }
                if ((posix = convertToPOSIX(request, date.getTime())) == null) {
                    posix = convertToPOSIX(request, date.getTime() + 864e5 * increment) - 864e5 * increment;
                }
            }
            return posix;
        }
        function convert(vargs) {
            if (!vargs.length)
                return "1.0.23";
            var request = Object.create(this), adjustments = [], i, I, $, argument, date;
            for (i = 0; i < vargs.length; i++) { // leave the for loop alone, it works.
                argument = vargs[i];
                // https://twitter.com/bigeasy/status/215112186572439552
                if (Array.isArray(argument)) {
                    if (!i && !isNaN(argument[1])) {
                        date = argument;
                    }
                    else {
                        argument.splice.apply(vargs, [i--, 1].concat(argument));
                    }
                }
                else if (isNaN(argument)) {
                    $ = typeof argument;
                    if ($ == "string") {
                        if (~argument.indexOf("%")) {
                            request.format = argument;
                        }
                        else if (!i && argument == "*") {
                            date = argument;
                        }
                        else if (!i && ($ = /^(\d{4})-(\d{2})-(\d{2})(?:[T\s](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|(([+-])(\d{2}(:\d{2}){0,2})))?)?$/.exec(argument))) {
                            date = [];
                            date.push.apply(date, $.slice(1, 8));
                            if ($[9]) {
                                date.push($[10] + 1);
                                date.push.apply(date, $[11].split(/:/));
                            }
                            else if ($[8]) {
                                date.push(1);
                            }
                        }
                        else if (/^\w{2,3}_\w{2}$/.test(argument)) {
                            request.locale = argument;
                        }
                        else if ($ = UNIT_RE.exec(argument)) {
                            adjustments.push($);
                        }
                        else {
                            request.zone = argument;
                        }
                    }
                    else if ($ == "function") {
                        if ($ = argument.call(request))
                            return $;
                    }
                    else if (/^\w{2,3}_\w{2}$/.test(argument.name)) {
                        request[argument.name] = argument;
                    }
                    else if (argument.zones) {
                        for ($ in argument.zones)
                            request[$] = argument.zones[$];
                        for ($ in argument.rules)
                            request[$] = argument.rules[$];
                    }
                }
                else if (!i) {
                    date = argument;
                }
            }
            if (!request[request.locale])
                delete request.locale;
            if (!request[request.zone])
                delete request.zone;
            if (date != null) {
                if (date == "*") {
                    date = request.clock();
                }
                else if (Array.isArray(date)) {
                    $ = [];
                    I = !date[7];
                    for (i = 0; i < 11; i++)
                        $[i] = +(date[i] || 0); // conversion necessary for decrement
                    --$[1]; // Grr..
                    date = Date.UTC.apply(Date.UTC, $) + -$[7] * ($[8] * 36e5 + $[9] * 6e4 + $[10] * 1e3);
                }
                else {
                    date = Math.floor(date);
                }
                if (!isNaN(date)) {
                    if (I)
                        date = convertToPOSIX(request, date);
                    if (date == null)
                        return date;
                    for (i = 0, I = adjustments.length; i < I; i++) {
                        date = adjust(request, date, adjustments[i]);
                    }
                    if (!request.format)
                        return date;
                    $ = new Date(convertToWallclock(request, date));
                    return request.format.replace(/%([-0_^]?)(:{0,3})(\d*)(.)/g, function (value, flag, colons, padding, specifier) {
                        var f, fill = "0", pad;
                        if (f = request[specifier]) {
                            value = String(f.call(request, $, date, flag, colons.length));
                            if ((flag || f.style) == "_")
                                fill = " ";
                            pad = flag == "-" ? 0 : f.pad || 0;
                            while (value.length < pad)
                                value = fill + value;
                            pad = flag == "-" ? 0 : padding || f.pad;
                            while (value.length < pad)
                                value = fill + value;
                            if (specifier == "N" && pad < value.length)
                                value = value.slice(0, pad);
                            if (flag == "^")
                                value = value.toUpperCase();
                        }
                        return value;
                    });
                }
            }
            return function () { return request.convert(arguments); };
        }
        var context = { clock: function () { return +(new Date()); },
            zone: "UTC",
            entry: { abbrev: "UTC", offset: 0, save: 0 },
            UTC: 1,
            z: function (date, posix, flag, delimiters) {
                var offset = this.entry.offset + this.entry.save, seconds = Math.abs(offset / 1000), parts = [], part = 3600, i, z;
                for (i = 0; i < 3; i++) {
                    parts.push(("0" + Math.floor(seconds / part)).slice(-2));
                    seconds %= part;
                    part /= 60;
                }
                if (flag == "^" && !offset)
                    return "Z";
                if (flag == "^")
                    delimiters = 3;
                if (delimiters == 3) {
                    z = parts.join(":");
                    z = z.replace(/:00$/, "");
                    if (flag != "^")
                        z = z.replace(/:00$/, "");
                }
                else if (delimiters) {
                    z = parts.slice(0, delimiters + 1).join(":");
                    if (flag == "^")
                        z = z.replace(/:00$/, "");
                }
                else {
                    z = parts.slice(0, 2).join("");
                }
                z = (offset < 0 ? "-" : "+") + z;
                z = z.replace(/([-+])(0)/, { "_": " $1", "-": "$1" }[flag] || "$1$2");
                return z;
            },
            "%": function (date) { return "%"; },
            n: function (date) { return "\n"; },
            t: function (date) { return "\t"; },
            U: function (date) { return weekOfYear(date, 0); },
            W: function (date) { return weekOfYear(date, 1); },
            V: function (date) { return isoWeek(date)[0]; },
            G: function (date) { return isoWeek(date)[1]; },
            g: function (date) { return isoWeek(date)[1] % 100; },
            j: function (date) { return Math.floor((date.getTime() - Date.UTC(date.getUTCFullYear(), 0)) / 864e5) + 1; },
            s: function (date) { return Math.floor(date.getTime() / 1000); },
            C: function (date) { return Math.floor(date.getUTCFullYear() / 100); },
            N: function (date) { return date.getTime() % 1000 * 1000000; },
            m: function (date) { return date.getUTCMonth() + 1; },
            Y: function (date) { return date.getUTCFullYear(); },
            y: function (date) { return date.getUTCFullYear() % 100; },
            H: function (date) { return date.getUTCHours(); },
            M: function (date) { return date.getUTCMinutes(); },
            S: function (date) { return date.getUTCSeconds(); },
            e: function (date) { return date.getUTCDate(); },
            d: function (date) { return date.getUTCDate(); },
            u: function (date) { return date.getUTCDay() || 7; },
            w: function (date) { return date.getUTCDay(); },
            l: function (date) { return date.getUTCHours() % 12 || 12; },
            I: function (date) { return date.getUTCHours() % 12 || 12; },
            k: function (date) { return date.getUTCHours(); },
            Z: function (date) { return this.entry.abbrev; },
            a: function (date) { return this[this.locale].day.abbrev[date.getUTCDay()]; },
            A: function (date) { return this[this.locale].day.full[date.getUTCDay()]; },
            h: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()]; },
            b: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()]; },
            B: function (date) { return this[this.locale].month.full[date.getUTCMonth()]; },
            P: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)].toLowerCase(); },
            p: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)]; },
            R: function (date, posix) { return this.convert([posix, "%H:%M"]); },
            T: function (date, posix) { return this.convert([posix, "%H:%M:%S"]); },
            D: function (date, posix) { return this.convert([posix, "%m/%d/%y"]); },
            F: function (date, posix) { return this.convert([posix, "%Y-%m-%d"]); },
            x: function (date, posix) { return this.convert([posix, this[this.locale].date]); },
            r: function (date, posix) { return this.convert([posix, this[this.locale].time12 || '%I:%M:%S']); },
            X: function (date, posix) { return this.convert([posix, this[this.locale].time24]); },
            c: function (date, posix) { return this.convert([posix, this[this.locale].dateTime]); },
            convert: convert,
            locale: "en_US",
            en_US: {
                date: "%m/%d/%Y",
                time24: "%I:%M:%S %p",
                time12: "%I:%M:%S %p",
                dateTime: "%a %d %b %Y %I:%M:%S %p %Z",
                meridiem: ["AM", "PM"],
                month: {
                    abbrev: "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|"),
                    full: "January|February|March|April|May|June|July|August|September|October|November|December".split("|")
                },
                day: {
                    abbrev: "Sun|Mon|Tue|Wed|Thu|Fri|Sat".split("|"),
                    full: "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|")
                }
            }
        };
        var UNITS = "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|year|month|day|hour|minute|second|millisecond", UNIT_RE = new RegExp("^\\s*([+-])(\\d+)\\s+(" + UNITS + ")s?\\s*$", "i"), TIME = [36e5, 6e4, 1e3, 1];
        UNITS = UNITS.toLowerCase().split("|");
        "delmHMSUWVgCIky".replace(/./g, function (e) { context[e].pad = 2; });
        context.N.pad = 9;
        context.j.pad = 3;
        context.k.style = "_";
        context.l.style = "_";
        context.e.style = "_";
        function weekOfYear(date, startOfWeek) {
            var diff, nyd, weekStart;
            nyd = new Date(Date.UTC(date.getUTCFullYear(), 0));
            diff = Math.floor((date.getTime() - nyd.getTime()) / 864e5);
            if (nyd.getUTCDay() == startOfWeek) {
                weekStart = 0;
            }
            else {
                weekStart = 7 - nyd.getUTCDay() + startOfWeek;
                if (weekStart == 8) {
                    weekStart = 1;
                }
            }
            return diff >= weekStart ? Math.floor((diff - weekStart) / 7) + 1 : 0;
        }
        function isoWeek(date) {
            var nyd, nyy, week;
            nyy = date.getUTCFullYear();
            nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
            week = weekOfYear(date, 1) + (nyd > 1 && nyd <= 4 ? 1 : 0);
            if (!week) {
                nyy = date.getUTCFullYear() - 1;
                nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
                week = nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29) ? 53 : 52;
                return [week, date.getUTCFullYear() - 1];
            }
            else if (week == 53 && !(nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29))) {
                return [1, date.getUTCFullYear() + 1];
            }
            else {
                return [week, date.getUTCFullYear()];
            }
        }
        return function () { return context.convert(arguments); };
    });
},
/* core/util/templating.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const Numbro = tslib_1.__importStar(require(183) /* @bokeh/numbro */);
    const sprintf_js_1 = require(184) /* sprintf-js */;
    const timezone_1 = tslib_1.__importDefault(require(181) /* timezone */);
    const kinds_1 = require(21) /* ../kinds */;
    const types_1 = require(8) /* ./types */;
    exports.FormatterType = kinds_1.Enum("numeral", "printf", "datetime");
    exports.DEFAULT_FORMATTERS = {
        numeral: (value, format, _special_vars) => Numbro.format(value, format),
        datetime: (value, format, _special_vars) => timezone_1.default(value, format),
        printf: (value, format, _special_vars) => sprintf(format, value),
    };
    function sprintf(format, ...args) {
        return sprintf_js_1.sprintf(format, ...args);
    }
    exports.sprintf = sprintf;
    function basic_formatter(value, _format, _special_vars) {
        if (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 (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, i) {
        const column = data_source.get_column(name);
        // missing column
        if (column == null)
            return null;
        // typical (non-image) index
        if (types_1.isNumber(i))
            return column[i];
        // image index
        const data = column[i.index];
        if (types_1.isTypedArray(data) || types_1.isArray(data)) {
            // inspect array of arrays
            if (types_1.isArray(data[0])) {
                const row = data[i.dim2];
                return row[i.dim1];
            }
            else
                return data[i.flat_index]; // inspect flat array
        }
        else
            return data; // inspect per-image scalar data
    }
    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 (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 ? 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 ? 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;
},
/* @bokeh/numbro/numbro.js */ function _(require, module, exports, __esModule, __esExport) {
    /*!
     * numbro.js
     * version : 1.6.2
     * author : Företagsplatsen AB
     * license : MIT
     * http://www.foretagsplatsen.se
     */
    /************************************
        Constants
    ************************************/
    var numbro, VERSION = '1.6.2', 
    // internal storage for culture config files
    cultures = {}, 
    // Todo: Remove in 2.0.0
    languages = cultures, currentCulture = 'en-US', zeroFormat = null, defaultFormat = '0,0', defaultCurrencyFormat = '0$', 
    // check for nodeJS
    hasModule = (typeof module !== 'undefined' && module.exports), 
    // default culture
    enUS = {
        delimiters: {
            thousands: ',',
            decimal: '.'
        },
        abbreviations: {
            thousand: 'k',
            million: 'm',
            billion: 'b',
            trillion: 't'
        },
        ordinal: function (number) {
            var b = number % 10;
            return (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                    (b === 2) ? 'nd' :
                        (b === 3) ? 'rd' : 'th';
        },
        currency: {
            symbol: '$',
            position: 'prefix'
        },
        defaults: {
            currencyFormat: ',0000 a'
        },
        formats: {
            fourDigits: '0000 a',
            fullWithTwoDecimals: '$ ,0.00',
            fullWithTwoDecimalsNoCurrency: ',0.00'
        }
    };
    /************************************
        Constructors
    ************************************/
    // Numbro prototype object
    function Numbro(number) {
        this._value = number;
    }
    function zeroes(count) {
        var i, ret = '';
        for (i = 0; i < count; i++) {
            ret += '0';
        }
        return ret;
    }
    /**
     * Implementation of toFixed() for numbers with exponent > 21
     *
     *
     */
    function toFixedLarge(value, precision) {
        var mantissa, beforeDec, afterDec, exponent, str;
        str = value.toString();
        mantissa = str.split('e')[0];
        exponent = str.split('e')[1];
        beforeDec = mantissa.split('.')[0];
        afterDec = mantissa.split('.')[1] || '';
        str = beforeDec + afterDec + zeroes(exponent - afterDec.length);
        if (precision > 0) {
            str += '.' + zeroes(precision);
        }
        return str;
    }
    /**
     * Implementation of toFixed() that treats floats more like decimals
     *
     * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
     * problems for accounting- and finance-related software.
     */
    function toFixed(value, precision, roundingFunction, optionals) {
        var power = Math.pow(10, precision), optionalsRegExp, output;
        if (value.toFixed(0).search('e') > -1) {
            // Above 1e21, toFixed returns scientific notation, which
            // is useless and unexpected
            output = toFixedLarge(value, precision);
        }
        else {
            //roundingFunction = (roundingFunction !== undefined ? roundingFunction : Math.round);
            // Multiply up by precision, round accurately, then divide and use native toFixed():
            output = (roundingFunction(value * power) / power).toFixed(precision);
        }
        if (optionals) {
            optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
            output = output.replace(optionalsRegExp, '');
        }
        return output;
    }
    /************************************
        Formatting
    ************************************/
    // determine what type of formatting we need to do
    function formatNumbro(value, format, roundingFunction) {
        var output;
        // TODO: do something with `language`
        // figure out what kind of format we are dealing with
        if (format.indexOf('$') > -1) { // currency!!!!!
            output = formatCurrency(value, format, roundingFunction);
        }
        else if (format.indexOf('%') > -1) { // percentage
            output = formatPercentage(value, format, roundingFunction);
        }
        else if (format.indexOf(':') > -1) { // time
            output = formatTime(value);
        }
        else { // plain ol' numbers or bytes
            output = formatNumber(value, format, roundingFunction);
        }
        // return string
        return output;
    }
    function formatCurrency(value, originalFormat, roundingFunction) {
        var format = originalFormat, symbolIndex = format.indexOf('$'), openParenIndex = format.indexOf('('), plusSignIndex = format.indexOf('+'), minusSignIndex = format.indexOf('-'), space = '', decimalSeparator = '', spliceIndex, output;
        if (format.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            if (cultures[currentCulture].currency.position === 'infix') {
                decimalSeparator = cultures[currentCulture].currency.symbol;
                if (cultures[currentCulture].currency.spaceSeparated) {
                    decimalSeparator = ' ' + decimalSeparator + ' ';
                }
            }
            else if (cultures[currentCulture].currency.spaceSeparated) {
                space = ' ';
            }
        }
        else {
            // check for space before or after currency
            if (format.indexOf(' $') > -1) {
                space = ' ';
                format = format.replace(' $', '');
            }
            else if (format.indexOf('$ ') > -1) {
                space = ' ';
                format = format.replace('$ ', '');
            }
            else {
                format = format.replace('$', '');
            }
        }
        // Format The Number
        output = formatNumber(value, format, roundingFunction, decimalSeparator);
        if (originalFormat.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            switch (cultures[currentCulture].currency.position) {
                case 'postfix':
                    if (output.indexOf(')') > -1) {
                        output = output.split('');
                        output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                        output = output.join('');
                    }
                    else {
                        output = output + space + cultures[currentCulture].currency.symbol;
                    }
                    break;
                case 'infix':
                    break;
                case 'prefix':
                    if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
                        output = output.split('');
                        spliceIndex = Math.max(openParenIndex, minusSignIndex) + 1;
                        output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                        output = output.join('');
                    }
                    else {
                        output = cultures[currentCulture].currency.symbol + space + output;
                    }
                    break;
                default:
                    throw Error('Currency position should be among ["prefix", "infix", "postfix"]');
            }
        }
        else {
            // position the symbol
            if (symbolIndex <= 1) {
                if (output.indexOf('(') > -1 || output.indexOf('+') > -1 || output.indexOf('-') > -1) {
                    output = output.split('');
                    spliceIndex = 1;
                    if (symbolIndex < openParenIndex || symbolIndex < plusSignIndex || symbolIndex < minusSignIndex) {
                        // the symbol appears before the "(", "+" or "-"
                        spliceIndex = 0;
                    }
                    output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                    output = output.join('');
                }
                else {
                    output = cultures[currentCulture].currency.symbol + space + output;
                }
            }
            else {
                if (output.indexOf(')') > -1) {
                    output = output.split('');
                    output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                    output = output.join('');
                }
                else {
                    output = output + space + cultures[currentCulture].currency.symbol;
                }
            }
        }
        return output;
    }
    function formatPercentage(value, format, roundingFunction) {
        var space = '', output;
        value = value * 100;
        // check for space before %
        if (format.indexOf(' %') > -1) {
            space = ' ';
            format = format.replace(' %', '');
        }
        else {
            format = format.replace('%', '');
        }
        output = formatNumber(value, format, roundingFunction);
        if (output.indexOf(')') > -1) {
            output = output.split('');
            output.splice(-1, 0, space + '%');
            output = output.join('');
        }
        else {
            output = output + space + '%';
        }
        return output;
    }
    function formatTime(value) {
        var hours = Math.floor(value / 60 / 60), minutes = Math.floor((value - (hours * 60 * 60)) / 60), seconds = Math.round(value - (hours * 60 * 60) - (minutes * 60));
        return hours + ':' +
            ((minutes < 10) ? '0' + minutes : minutes) + ':' +
            ((seconds < 10) ? '0' + seconds : seconds);
    }
    function formatNumber(value, format, roundingFunction, sep) {
        var negP = false, signed = false, optDec = false, abbr = '', i, abbrK = false, // force abbreviation to thousands
        abbrM = false, // force abbreviation to millions
        abbrB = false, // force abbreviation to billions
        abbrT = false, // force abbreviation to trillions
        abbrForce = false, // force abbreviation
        bytes = '', ord = '', abs = Math.abs(value), binarySuffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'], decimalSuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max, power, totalLength, length, minimumPrecision, pow, w, intPrecision, precision, prefix, postfix, thousands, d = '', forcedNeg = false, neg = false, indexOpenP, size, indexMinus, paren = '', minlen;
        // check if number is zero and a custom zero format has been set
        if (value === 0 && zeroFormat !== null) {
            return zeroFormat;
        }
        if (!isFinite(value)) {
            return '' + value;
        }
        if (format.indexOf('{') === 0) {
            var end = format.indexOf('}');
            if (end === -1) {
                throw Error('Format should also contain a "}"');
            }
            prefix = format.slice(1, end);
            format = format.slice(end + 1);
        }
        else {
            prefix = '';
        }
        if (format.indexOf('}') === format.length - 1) {
            var start = format.indexOf('{');
            if (start === -1) {
                throw Error('Format should also contain a "{"');
            }
            postfix = format.slice(start + 1, -1);
            format = format.slice(0, start + 1);
        }
        else {
            postfix = '';
        }
        // check for min length
        var info;
        if (format.indexOf('.') === -1) {
            info = format.match(/([0-9]+).*/);
        }
        else {
            info = format.match(/([0-9]+)\..*/);
        }
        minlen = info === null ? -1 : info[1].length;
        // see if we should use parentheses for negative number or if we should prefix with a sign
        // if both are present we default to parentheses
        if (format.indexOf('-') !== -1) {
            forcedNeg = true;
        }
        if (format.indexOf('(') > -1) {
            negP = true;
            format = format.slice(1, -1);
        }
        else if (format.indexOf('+') > -1) {
            signed = true;
            format = format.replace(/\+/g, '');
        }
        // see if abbreviation is wanted
        if (format.indexOf('a') > -1) {
            intPrecision = format.split('.')[0].match(/[0-9]+/g) || ['0'];
            intPrecision = parseInt(intPrecision[0], 10);
            // check if abbreviation is specified
            abbrK = format.indexOf('aK') >= 0;
            abbrM = format.indexOf('aM') >= 0;
            abbrB = format.indexOf('aB') >= 0;
            abbrT = format.indexOf('aT') >= 0;
            abbrForce = abbrK || abbrM || abbrB || abbrT;
            // check for space before abbreviation
            if (format.indexOf(' a') > -1) {
                abbr = ' ';
                format = format.replace(' a', '');
            }
            else {
                format = format.replace('a', '');
            }
            totalLength = Math.floor(Math.log(abs) / Math.LN10) + 1;
            minimumPrecision = totalLength % 3;
            minimumPrecision = minimumPrecision === 0 ? 3 : minimumPrecision;
            if (intPrecision && abs !== 0) {
                length = Math.floor(Math.log(abs) / Math.LN10) + 1 - intPrecision;
                pow = 3 * ~~((Math.min(intPrecision, totalLength) - minimumPrecision) / 3);
                abs = abs / Math.pow(10, pow);
                if (format.indexOf('.') === -1 && intPrecision > 3) {
                    format += '[.]';
                    size = length === 0 ? 0 : 3 * ~~(length / 3) - length;
                    size = size < 0 ? size + 3 : size;
                    for (i = 0; i < size; i++) {
                        format += '0';
                    }
                }
            }
            if (Math.floor(Math.log(Math.abs(value)) / Math.LN10) + 1 !== intPrecision) {
                if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
                    // trillion
                    abbr = abbr + cultures[currentCulture].abbreviations.trillion;
                    value = value / Math.pow(10, 12);
                }
                else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
                    // billion
                    abbr = abbr + cultures[currentCulture].abbreviations.billion;
                    value = value / Math.pow(10, 9);
                }
                else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
                    // million
                    abbr = abbr + cultures[currentCulture].abbreviations.million;
                    value = value / Math.pow(10, 6);
                }
                else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
                    // thousand
                    abbr = abbr + cultures[currentCulture].abbreviations.thousand;
                    value = value / Math.pow(10, 3);
                }
            }
        }
        // see if we are formatting binary bytes
        if (format.indexOf('b') > -1) {
            // check for space before
            if (format.indexOf(' b') > -1) {
                bytes = ' ';
                format = format.replace(' b', '');
            }
            else {
                format = format.replace('b', '');
            }
            for (power = 0; power <= binarySuffixes.length; power++) {
                min = Math.pow(1024, power);
                max = Math.pow(1024, power + 1);
                if (value >= min && value < max) {
                    bytes = bytes + binarySuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }
        // see if we are formatting decimal bytes
        if (format.indexOf('d') > -1) {
            // check for space before
            if (format.indexOf(' d') > -1) {
                bytes = ' ';
                format = format.replace(' d', '');
            }
            else {
                format = format.replace('d', '');
            }
            for (power = 0; power <= decimalSuffixes.length; power++) {
                min = Math.pow(1000, power);
                max = Math.pow(1000, power + 1);
                if (value >= min && value < max) {
                    bytes = bytes + decimalSuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }
        // see if ordinal is wanted
        if (format.indexOf('o') > -1) {
            // check for space before
            if (format.indexOf(' o') > -1) {
                ord = ' ';
                format = format.replace(' o', '');
            }
            else {
                format = format.replace('o', '');
            }
            if (cultures[currentCulture].ordinal) {
                ord = ord + cultures[currentCulture].ordinal(value);
            }
        }
        if (format.indexOf('[.]') > -1) {
            optDec = true;
            format = format.replace('[.]', '.');
        }
        w = value.toString().split('.')[0];
        precision = format.split('.')[1];
        thousands = format.indexOf(',');
        if (precision) {
            if (precision.indexOf('*') !== -1) {
                d = toFixed(value, value.toString().split('.')[1].length, roundingFunction);
            }
            else {
                if (precision.indexOf('[') > -1) {
                    precision = precision.replace(']', '');
                    precision = precision.split('[');
                    d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length);
                }
                else {
                    d = toFixed(value, precision.length, roundingFunction);
                }
            }
            w = d.split('.')[0];
            if (d.split('.')[1].length) {
                var p = sep ? abbr + sep : cultures[currentCulture].delimiters.decimal;
                d = p + d.split('.')[1];
            }
            else {
                d = '';
            }
            if (optDec && Number(d.slice(1)) === 0) {
                d = '';
            }
        }
        else {
            w = toFixed(value, null, roundingFunction);
        }
        // format number
        if (w.indexOf('-') > -1) {
            w = w.slice(1);
            neg = true;
        }
        if (w.length < minlen) {
            w = new Array(minlen - w.length + 1).join('0') + w;
        }
        if (thousands > -1) {
            w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' +
                cultures[currentCulture].delimiters.thousands);
        }
        if (format.indexOf('.') === 0) {
            w = '';
        }
        indexOpenP = format.indexOf('(');
        indexMinus = format.indexOf('-');
        if (indexOpenP < indexMinus) {
            paren = ((negP && neg) ? '(' : '') + (((forcedNeg && neg) || (!negP && neg)) ? '-' : '');
        }
        else {
            paren = (((forcedNeg && neg) || (!negP && neg)) ? '-' : '') + ((negP && neg) ? '(' : '');
        }
        return prefix +
            paren + ((!neg && signed && value !== 0) ? '+' : '') +
            w + d +
            ((ord) ? ord : '') +
            ((abbr && !sep) ? abbr : '') +
            ((bytes) ? bytes : '') +
            ((negP && neg) ? ')' : '') +
            postfix;
    }
    /************************************
        Top Level Functions
    ************************************/
    numbro = function (input) {
        if (numbro.isNumbro(input)) {
            input = input.value();
        }
        else if (input === 0 || typeof input === 'undefined') {
            input = 0;
        }
        else if (!Number(input)) {
            input = numbro.fn.unformat(input);
        }
        return new Numbro(Number(input));
    };
    // version number
    numbro.version = VERSION;
    // compare numbro object
    numbro.isNumbro = function (obj) {
        return obj instanceof Numbro;
    };
    /**
     * This function allow the user to set a new language with a fallback if
     * the language does not exist. If no fallback language is provided,
     * it fallbacks to english.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `setCulture` should be used instead.
     */
    numbro.setLanguage = function (newLanguage, fallbackLanguage) {
        console.warn('`setLanguage` is deprecated since version 1.6.0. Use `setCulture` instead');
        var key = newLanguage, prefix = newLanguage.split('-')[0], matchingLanguage = null;
        if (!languages[key]) {
            Object.keys(languages).forEach(function (language) {
                if (!matchingLanguage && language.split('-')[0] === prefix) {
                    matchingLanguage = language;
                }
            });
            key = matchingLanguage || fallbackLanguage || 'en-US';
        }
        chooseCulture(key);
    };
    /**
     * This function allow the user to set a new culture with a fallback if
     * the culture does not exist. If no fallback culture is provided,
     * it fallbacks to "en-US".
     */
    numbro.setCulture = function (newCulture, fallbackCulture) {
        var key = newCulture, suffix = newCulture.split('-')[1], matchingCulture = null;
        if (!cultures[key]) {
            if (suffix) {
                Object.keys(cultures).forEach(function (language) {
                    if (!matchingCulture && language.split('-')[1] === suffix) {
                        matchingCulture = language;
                    }
                });
            }
            key = matchingCulture || fallbackCulture || 'en-US';
        }
        chooseCulture(key);
    };
    /**
     * This function will load languages and then set the global language.  If
     * no arguments are passed in, it will simply return the current global
     * language key.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.language = function (key, values) {
        console.warn('`language` is deprecated since version 1.6.0. Use `culture` instead');
        if (!key) {
            return currentCulture;
        }
        if (key && !values) {
            if (!languages[key]) {
                throw new Error('Unknown language : ' + key);
            }
            chooseCulture(key);
        }
        if (values || !languages[key]) {
            setCulture(key, values);
        }
        return numbro;
    };
    /**
     * This function will load cultures and then set the global culture.  If
     * no arguments are passed in, it will simply return the current global
     * culture code.
     */
    numbro.culture = function (code, values) {
        if (!code) {
            return currentCulture;
        }
        if (code && !values) {
            if (!cultures[code]) {
                throw new Error('Unknown culture : ' + code);
            }
            chooseCulture(code);
        }
        if (values || !cultures[code]) {
            setCulture(code, values);
        }
        return numbro;
    };
    /**
     * This function provides access to the loaded language data.  If
     * no arguments are passed in, it will simply return the current
     * global language object.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.languageData = function (key) {
        console.warn('`languageData` is deprecated since version 1.6.0. Use `cultureData` instead');
        if (!key) {
            return languages[currentCulture];
        }
        if (!languages[key]) {
            throw new Error('Unknown language : ' + key);
        }
        return languages[key];
    };
    /**
     * This function provides access to the loaded culture data.  If
     * no arguments are passed in, it will simply return the current
     * global culture object.
     */
    numbro.cultureData = function (code) {
        if (!code) {
            return cultures[currentCulture];
        }
        if (!cultures[code]) {
            throw new Error('Unknown culture : ' + code);
        }
        return cultures[code];
    };
    numbro.culture('en-US', enUS);
    /**
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `cultures` should be used instead.
     */
    numbro.languages = function () {
        console.warn('`languages` is deprecated since version 1.6.0. Use `cultures` instead');
        return languages;
    };
    numbro.cultures = function () {
        return cultures;
    };
    numbro.zeroFormat = function (format) {
        zeroFormat = typeof (format) === 'string' ? format : null;
    };
    numbro.defaultFormat = function (format) {
        defaultFormat = typeof (format) === 'string' ? format : '0.0';
    };
    numbro.defaultCurrencyFormat = function (format) {
        defaultCurrencyFormat = typeof (format) === 'string' ? format : '0$';
    };
    numbro.validate = function (val, culture) {
        var _decimalSep, _thousandSep, _currSymbol, _valArray, _abbrObj, _thousandRegEx, cultureData, temp;
        //coerce val to string
        if (typeof val !== 'string') {
            val += '';
            if (console.warn) {
                console.warn('Numbro.js: Value is not string. It has been co-erced to: ', val);
            }
        }
        //trim whitespaces from either sides
        val = val.trim();
        //if val is just digits return true
        if (!!val.match(/^\d+$/)) {
            return true;
        }
        //if val is empty return false
        if (val === '') {
            return false;
        }
        //get the decimal and thousands separator from numbro.cultureData
        try {
            //check if the culture is understood by numbro. if not, default it to current culture
            cultureData = numbro.cultureData(culture);
        }
        catch (e) {
            cultureData = numbro.cultureData(numbro.culture());
        }
        //setup the delimiters and currency symbol based on culture
        _currSymbol = cultureData.currency.symbol;
        _abbrObj = cultureData.abbreviations;
        _decimalSep = cultureData.delimiters.decimal;
        if (cultureData.delimiters.thousands === '.') {
            _thousandSep = '\\.';
        }
        else {
            _thousandSep = cultureData.delimiters.thousands;
        }
        // validating currency symbol
        temp = val.match(/^[^\d]+/);
        if (temp !== null) {
            val = val.substr(1);
            if (temp[0] !== _currSymbol) {
                return false;
            }
        }
        //validating abbreviation symbol
        temp = val.match(/[^\d]+$/);
        if (temp !== null) {
            val = val.slice(0, -1);
            if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million &&
                temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
                return false;
            }
        }
        _thousandRegEx = new RegExp(_thousandSep + '{2}');
        if (!val.match(/[^\d.,]/g)) {
            _valArray = val.split(_decimalSep);
            if (_valArray.length > 2) {
                return false;
            }
            else {
                if (_valArray.length < 2) {
                    return (!!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
                }
                else {
                    if (_valArray[0].length === 1) {
                        return (!!_valArray[0].match(/^\d+$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));
                    }
                    else {
                        return (!!_valArray[0].match(/^\d+.*\d$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));
                    }
                }
            }
        }
        return false;
    };
    /************************************
        Helpers
    ************************************/
    function setCulture(code, values) {
        cultures[code] = values;
    }
    function chooseCulture(code) {
        currentCulture = code;
        var defaults = cultures[code].defaults;
        if (defaults && defaults.format) {
            numbro.defaultFormat(defaults.format);
        }
        if (defaults && defaults.currencyFormat) {
            numbro.defaultCurrencyFormat(defaults.currencyFormat);
        }
    }
    function format(input, formatString, language, roundingFunction) {
        if (language != null && language !== numbro.culture()) {
            numbro.setCulture(language);
        }
        return formatNumbro(Number(input), formatString != null ? formatString : defaultFormat, roundingFunction == null ? Math.round : roundingFunction);
    }
    module.exports = { "format": format };
},
/* sprintf-js/src/sprintf.js */ function _(require, module, exports, __esModule, __esExport) {
    /* global window, exports, define */
    !function () {
        'use strict';
        var re = {
            not_string: /[^s]/,
            not_bool: /[^t]/,
            not_type: /[^T]/,
            not_primitive: /[^v]/,
            number: /[diefg]/,
            numeric_arg: /[bcdiefguxX]/,
            json: /[j]/,
            not_json: /[^j]/,
            text: /^[^\x25]+/,
            modulo: /^\x25{2}/,
            placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
            key: /^([a-z_][a-z_\d]*)/i,
            key_access: /^\.([a-z_][a-z_\d]*)/i,
            index_access: /^\[(\d+)\]/,
            sign: /^[+-]/
        };
        function sprintf(key) {
            // `arguments` is not an array, but should be fine for this call
            return sprintf_format(sprintf_parse(key), arguments);
        }
        function vsprintf(fmt, argv) {
            return sprintf.apply(null, [fmt].concat(argv || []));
        }
        function sprintf_format(parse_tree, argv) {
            var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign;
            for (i = 0; i < tree_length; i++) {
                if (typeof parse_tree[i] === 'string') {
                    output += parse_tree[i];
                }
                else if (typeof parse_tree[i] === 'object') {
                    ph = parse_tree[i]; // convenience purposes only
                    if (ph.keys) { // keyword argument
                        arg = argv[cursor];
                        for (k = 0; k < ph.keys.length; k++) {
                            if (arg == undefined) {
                                throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
                            }
                            arg = arg[ph.keys[k]];
                        }
                    }
                    else if (ph.param_no) { // positional argument (explicit)
                        arg = argv[ph.param_no];
                    }
                    else { // positional argument (implicit)
                        arg = argv[cursor++];
                    }
                    if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                        arg = arg();
                    }
                    if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                        throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg));
                    }
                    if (re.number.test(ph.type)) {
                        is_positive = arg >= 0;
                    }
                    switch (ph.type) {
                        case 'b':
                            arg = parseInt(arg, 10).toString(2);
                            break;
                        case 'c':
                            arg = String.fromCharCode(parseInt(arg, 10));
                            break;
                        case 'd':
                        case 'i':
                            arg = parseInt(arg, 10);
                            break;
                        case 'j':
                            arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
                            break;
                        case 'e':
                            arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
                            break;
                        case 'f':
                            arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
                            break;
                        case 'g':
                            arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
                            break;
                        case 'o':
                            arg = (parseInt(arg, 10) >>> 0).toString(8);
                            break;
                        case 's':
                            arg = String(arg);
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 't':
                            arg = String(!!arg);
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'T':
                            arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'u':
                            arg = parseInt(arg, 10) >>> 0;
                            break;
                        case 'v':
                            arg = arg.valueOf();
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'x':
                            arg = (parseInt(arg, 10) >>> 0).toString(16);
                            break;
                        case 'X':
                            arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
                            break;
                    }
                    if (re.json.test(ph.type)) {
                        output += arg;
                    }
                    else {
                        if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                            sign = is_positive ? '+' : '-';
                            arg = arg.toString().replace(re.sign, '');
                        }
                        else {
                            sign = '';
                        }
                        pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
                        pad_length = ph.width - (sign + arg).length;
                        pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '';
                        output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg);
                    }
                }
            }
            return output;
        }
        var sprintf_cache = Object.create(null);
        function sprintf_parse(fmt) {
            if (sprintf_cache[fmt]) {
                return sprintf_cache[fmt];
            }
            var _fmt = fmt, match, parse_tree = [], arg_names = 0;
            while (_fmt) {
                if ((match = re.text.exec(_fmt)) !== null) {
                    parse_tree.push(match[0]);
                }
                else if ((match = re.modulo.exec(_fmt)) !== null) {
                    parse_tree.push('%');
                }
                else if ((match = re.placeholder.exec(_fmt)) !== null) {
                    if (match[2]) {
                        arg_names |= 1;
                        var field_list = [], replacement_field = match[2], field_match = [];
                        if ((field_match = re.key.exec(replacement_field)) !== null) {
                            field_list.push(field_match[1]);
                            while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                                if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                    field_list.push(field_match[1]);
                                }
                                else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                    field_list.push(field_match[1]);
                                }
                                else {
                                    throw new SyntaxError('[sprintf] failed to parse named argument key');
                                }
                            }
                        }
                        else {
                            throw new SyntaxError('[sprintf] failed to parse named argument key');
                        }
                        match[2] = field_list;
                    }
                    else {
                        arg_names |= 2;
                    }
                    if (arg_names === 3) {
                        throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
                    }
                    parse_tree.push({
                        placeholder: match[0],
                        param_no: match[1],
                        keys: match[2],
                        sign: match[3],
                        pad_char: match[4],
                        align: match[5],
                        width: match[6],
                        precision: match[7],
                        type: match[8]
                    });
                }
                else {
                    throw new SyntaxError('[sprintf] unexpected placeholder');
                }
                _fmt = _fmt.substring(match[0].length);
            }
            return sprintf_cache[fmt] = parse_tree;
        }
        /**
         * export to either browser or node.js
         */
        /* eslint-disable quote-props */
        if (typeof exports !== 'undefined') {
            exports['sprintf'] = sprintf;
            exports['vsprintf'] = vsprintf;
        }
        if (typeof window !== 'undefined') {
            window['sprintf'] = sprintf;
            window['vsprintf'] = vsprintf;
            if (typeof define === 'function' && define['amd']) {
                define(function () {
                    return {
                        'sprintf': sprintf,
                        'vsprintf': vsprintf
                    };
                });
            }
        }
        /* eslint-enable quote-props */
    }(); // eslint-disable-line
},
/* models/tickers/datetime_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(9) /* ../../core/util/array */;
    const adaptive_ticker_1 = require(178) /* ./adaptive_ticker */;
    const composite_ticker_1 = require(186) /* ./composite_ticker */;
    const days_ticker_1 = require(187) /* ./days_ticker */;
    const months_ticker_1 = require(190) /* ./months_ticker */;
    const years_ticker_1 = require(191) /* ./years_ticker */;
    const util_1 = require(189) /* ./util */;
    class DatetimeTicker extends composite_ticker_1.CompositeTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_DatetimeTicker() {
            this.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: array_1.range(1, 32) }),
                    new days_ticker_1.DaysTicker({ days: 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: array_1.range(0, 12, 1) }),
                    new months_ticker_1.MonthsTicker({ months: array_1.range(0, 12, 2) }),
                    new months_ticker_1.MonthsTicker({ months: array_1.range(0, 12, 4) }),
                    new months_ticker_1.MonthsTicker({ months: array_1.range(0, 12, 6) }),
                    // Years
                    new years_ticker_1.YearsTicker({}),
                ],
            });
        }
    }
    exports.DatetimeTicker = DatetimeTicker;
    DatetimeTicker.__name__ = "DatetimeTicker";
    DatetimeTicker.init_DatetimeTicker();
},
/* models/tickers/composite_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    const array_1 = require(9) /* ../../core/util/array */;
    class CompositeTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_CompositeTicker() {
            this.define(({ Array, Ref }) => ({
                tickers: [Array(Ref(continuous_ticker_1.ContinuousTicker)), []],
            }));
        }
        // 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 = [
                array_1.sorted_index(this.min_intervals, ideal_interval) - 1,
                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 (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 = 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;
    CompositeTicker.__name__ = "CompositeTicker";
    CompositeTicker.init_CompositeTicker();
},
/* models/tickers/days_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const single_interval_ticker_1 = require(188) /* ./single_interval_ticker */;
    const util_1 = require(189) /* ./util */;
    const array_1 = require(9) /* ../../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 = util_1.last_month_no_later_than(new Date(start_time));
        const end_date = 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(util_1.copy_date(date));
            date.setUTCMonth(date.getUTCMonth() + 1);
            if (date > end_date)
                break;
        }
        return dates;
    }
    class DaysTicker extends single_interval_ticker_1.SingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_DaysTicker() {
            this.define(({ Int, Array }) => ({
                days: [Array(Int), []],
            }));
            this.override({
                num_minor_ticks: 0,
            });
        }
        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 = 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 interval = this.interval;
            const day_dates = array_1.concat(month_dates.map((date) => days_of_month(date, 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;
    DaysTicker.__name__ = "DaysTicker";
    DaysTicker.init_DaysTicker();
},
/* models/tickers/single_interval_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    class SingleIntervalTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_SingleIntervalTicker() {
            this.define(({ Number }) => ({
                interval: [Number],
            }));
        }
        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.SingleIntervalTicker = SingleIntervalTicker;
    SingleIntervalTicker.__name__ = "SingleIntervalTicker";
    SingleIntervalTicker.init_SingleIntervalTicker();
},
/* 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/months_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const single_interval_ticker_1 = require(188) /* ./single_interval_ticker */;
    const util_1 = require(189) /* ./util */;
    const array_1 = require(9) /* ../../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 = util_1.last_year_no_later_than(new Date(start_time));
        const end_date = 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(util_1.copy_date(date));
            date.setUTCFullYear(date.getUTCFullYear() + 1);
            if (date > end_date)
                break;
        }
        return dates;
    }
    class MonthsTicker extends single_interval_ticker_1.SingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_MonthsTicker() {
            this.define(({ Int, Array }) => ({
                months: [Array(Int), []],
            }));
        }
        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 = util_1.copy_date(year_date);
                    month_date.setUTCMonth(month);
                    return month_date;
                });
            };
            const month_dates = 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;
    MonthsTicker.__name__ = "MonthsTicker";
    MonthsTicker.init_MonthsTicker();
},
/* models/tickers/years_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const basic_ticker_1 = require(177) /* ./basic_ticker */;
    const single_interval_ticker_1 = require(188) /* ./single_interval_ticker */;
    const util_1 = require(189) /* ./util */;
    class YearsTicker extends single_interval_ticker_1.SingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            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 = util_1.last_year_no_later_than(new Date(data_low)).getUTCFullYear();
            const end_year = 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/axes/log_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_axis_1 = require(173) /* ./continuous_axis */;
    const log_tick_formatter_1 = require(193) /* ../formatters/log_tick_formatter */;
    const log_ticker_1 = require(194) /* ../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);
        }
        static init_LogAxis() {
            this.prototype.default_view = LogAxisView;
            this.override({
                ticker: () => new log_ticker_1.LogTicker(),
                formatter: () => new log_tick_formatter_1.LogTickFormatter(),
            });
        }
    }
    exports.LogAxis = LogAxis;
    LogAxis.__name__ = "LogAxis";
    LogAxis.init_LogAxis();
},
/* models/formatters/log_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(166) /* ./tick_formatter */;
    const basic_tick_formatter_1 = require(176) /* ./basic_tick_formatter */;
    const log_ticker_1 = require(194) /* ../tickers/log_ticker */;
    const graphics_1 = require(167) /* ../../core/graphics */;
    const { log, round } = Math;
    class LogTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static init_LogTickFormatter() {
            this.define(({ Ref, Nullable }) => ({
                ticker: [Nullable(Ref(log_ticker_1.LogTicker)), null],
            }));
        }
        initialize() {
            super.initialize();
            this.basic_formatter = new basic_tick_formatter_1.BasicTickFormatter();
        }
        format_graphics(ticks, opts) {
            var _a, _b;
            if (ticks.length == 0)
                return [];
            const base = (_b = (_a = this.ticker) === null || _a === void 0 ? void 0 : _a.base) !== null && _b !== void 0 ? _b : 10;
            const expos = this._exponents(ticks, base);
            if (expos == null)
                return this.basic_formatter.format_graphics(ticks, opts);
            else {
                return expos.map((expo) => {
                    const b = new graphics_1.TextBox({ text: basic_tick_formatter_1.unicode_replace(`${base}`) });
                    const e = new graphics_1.TextBox({ text: 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 _a, _b;
            if (ticks.length == 0)
                return [];
            const base = (_b = (_a = this.ticker) === null || _a === void 0 ? void 0 : _a.base) !== null && _b !== void 0 ? _b : 10;
            const expos = this._exponents(ticks, base);
            if (expos == null)
                return this.basic_formatter.doFormat(ticks, opts);
            else
                return expos.map((expo) => basic_tick_formatter_1.unicode_replace(`${base}^${expo}`));
        }
    }
    exports.LogTickFormatter = LogTickFormatter;
    LogTickFormatter.__name__ = "LogTickFormatter";
    LogTickFormatter.init_LogTickFormatter();
},
/* models/tickers/log_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const adaptive_ticker_1 = require(178) /* ./adaptive_ticker */;
    const array_1 = require(9) /* ../../core/util/array */;
    class LogTicker extends adaptive_ticker_1.AdaptiveTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_LogTicker() {
            this.override({
                mantissas: [1, 5],
            });
        }
        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)) {
                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 = 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 = 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 = 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 = 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;
    LogTicker.__name__ = "LogTicker";
    LogTicker.init_LogTicker();
},
/* models/axes/mercator_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const axis_1 = require(163) /* ./axis */;
    const linear_axis_1 = require(175) /* ./linear_axis */;
    const mercator_tick_formatter_1 = require(196) /* ../formatters/mercator_tick_formatter */;
    const mercator_ticker_1 = require(197) /* ../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);
        }
        static init_MercatorAxis() {
            this.prototype.default_view = MercatorAxisView;
            this.override({
                ticker: () => new mercator_ticker_1.MercatorTicker({ dimension: "lat" }),
                formatter: () => new mercator_tick_formatter_1.MercatorTickFormatter({ dimension: "lat" }),
            });
        }
    }
    exports.MercatorAxis = MercatorAxis;
    MercatorAxis.__name__ = "MercatorAxis";
    MercatorAxis.init_MercatorAxis();
},
/* models/formatters/mercator_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const basic_tick_formatter_1 = require(176) /* ./basic_tick_formatter */;
    const enums_1 = require(20) /* ../../core/enums */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    class MercatorTickFormatter extends basic_tick_formatter_1.BasicTickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static init_MercatorTickFormatter() {
            this.define(({ Nullable }) => ({
                dimension: [Nullable(enums_1.LatLon), null],
            }));
        }
        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;
    MercatorTickFormatter.__name__ = "MercatorTickFormatter";
    MercatorTickFormatter.init_MercatorTickFormatter();
},
/* models/tickers/mercator_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const basic_ticker_1 = require(177) /* ./basic_ticker */;
    const enums_1 = require(20) /* ../../core/enums */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    class MercatorTicker extends basic_ticker_1.BasicTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_MercatorTicker() {
            this.define(({ Nullable }) => ({
                dimension: [Nullable(enums_1.LatLon), null],
            }));
        }
        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] = 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 (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 (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 (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 (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;
    MercatorTicker.__name__ = "MercatorTicker";
    MercatorTicker.init_MercatorTicker();
},
/* 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(177) /* ./basic_ticker */;
    __esExport("BasicTicker", basic_ticker_1.BasicTicker);
    var categorical_ticker_1 = require(171) /* ./categorical_ticker */;
    __esExport("CategoricalTicker", categorical_ticker_1.CategoricalTicker);
    var composite_ticker_1 = require(186) /* ./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(185) /* ./datetime_ticker */;
    __esExport("DatetimeTicker", datetime_ticker_1.DatetimeTicker);
    var days_ticker_1 = require(187) /* ./days_ticker */;
    __esExport("DaysTicker", days_ticker_1.DaysTicker);
    var fixed_ticker_1 = require(199) /* ./fixed_ticker */;
    __esExport("FixedTicker", fixed_ticker_1.FixedTicker);
    var log_ticker_1 = require(194) /* ./log_ticker */;
    __esExport("LogTicker", log_ticker_1.LogTicker);
    var mercator_ticker_1 = require(197) /* ./mercator_ticker */;
    __esExport("MercatorTicker", mercator_ticker_1.MercatorTicker);
    var months_ticker_1 = require(190) /* ./months_ticker */;
    __esExport("MonthsTicker", months_ticker_1.MonthsTicker);
    var single_interval_ticker_1 = require(188) /* ./single_interval_ticker */;
    __esExport("SingleIntervalTicker", single_interval_ticker_1.SingleIntervalTicker);
    var ticker_1 = require(165) /* ./ticker */;
    __esExport("Ticker", ticker_1.Ticker);
    var years_ticker_1 = require(191) /* ./years_ticker */;
    __esExport("YearsTicker", years_ticker_1.YearsTicker);
    var binned_ticker_1 = require(200) /* ./binned_ticker */;
    __esExport("BinnedTicker", binned_ticker_1.BinnedTicker);
},
/* models/tickers/fixed_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_ticker_1 = require(179) /* ./continuous_ticker */;
    class FixedTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        static init_FixedTicker() {
            this.define(({ Number, Array }) => ({
                ticks: [Array(Number), []],
                minor_ticks: [Array(Number), []],
            }));
        }
        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;
    FixedTicker.__name__ = "FixedTicker";
    FixedTicker.init_FixedTicker();
},
/* models/tickers/binned_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ticker_1 = require(165) /* ./ticker */;
    const scanning_color_mapper_1 = require(201) /* ../mappers/scanning_color_mapper */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    class BinnedTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        static init_BinnedTicker() {
            this.define(({ Number, Ref, Or, Auto }) => ({
                mapper: [Ref(scanning_color_mapper_1.ScanningColorMapper)],
                num_major_ticks: [Or(Number, Auto), 8],
            }));
        }
        get_ticks(data_low, data_high, _range, _cross_loc) {
            const { binning } = this.mapper.metrics;
            const k_low = Math.max(0, arrayable_1.left_edge_index(data_low, binning));
            const k_high = Math.min(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;
    BinnedTicker.__name__ = "BinnedTicker";
    BinnedTicker.init_BinnedTicker();
},
/* models/mappers/scanning_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(202) /* ./continuous_color_mapper */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    class ScanningColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        cmap(d, palette, low_color, high_color, edges) {
            if (d < edges.binning[0])
                return low_color;
            if (d > edges.binning[edges.binning.length - 1])
                return high_color;
            const key = arrayable_1.left_edge_index(d, edges.binning);
            return palette[key];
        }
    }
    exports.ScanningColorMapper = ScanningColorMapper;
    ScanningColorMapper.__name__ = "ScanningColorMapper";
},
/* models/mappers/continuous_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const color_mapper_1 = require(203) /* ./color_mapper */;
    const glyph_renderer_1 = require(61) /* ../renderers/glyph_renderer */;
    const array_1 = require(9) /* ../../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;
        }
        static init_ContinuousColorMapper() {
            this.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)))), []],
                };
            });
        }
        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());
                }
            };
            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 types_1.isArray(fields) ? fields : [fields]) {
                    let array = renderer.data_source.get_column(field);
                    array = renderer.view.indices.select(array);
                    const masked = renderer.view.masked;
                    const selected = renderer.data_source.selected.indices;
                    let subset;
                    if (masked != null && selected.length > 0)
                        subset = array_1.intersection([...masked], selected);
                    else if (masked != null)
                        subset = [...masked];
                    else if (selected.length > 0)
                        subset = selected;
                    if (subset != null) {
                        array = array_1.map(subset, (i) => array[i]);
                    }
                    if (array.length > 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 = !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, this._scan_data);
            }
        }
        _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 });
        }
    }
    exports.ContinuousColorMapper = ContinuousColorMapper;
    ContinuousColorMapper.__name__ = "ContinuousColorMapper";
    ContinuousColorMapper.init_ContinuousColorMapper();
},
/* models/mappers/color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mapper_1 = require(204) /* ./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 */;
    // export for testing
    function _convert_color(color) {
        return color_1.encode_rgba(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");
        }
        static init_ColorMapper() {
            this.define(({ Color, Array }) => ({
                palette: [Array(Color)],
                nan_color: [Color, "gray"],
            }));
        }
        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 values = new types_1.ColorArray(xs.length);
                    self._v_compute(xs, values, palette, colors);
                    return new Uint8ClampedArray(platform_1.to_big_endian(values).buffer);
                },
            };
        }
        _colors(conv) {
            return { nan_color: conv(this.nan_color) };
        }
    }
    exports.ColorMapper = ColorMapper;
    ColorMapper.__name__ = "ColorMapper";
    ColorMapper.init_ColorMapper();
},
/* models/mappers/mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(149) /* ../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/formatters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var basic_tick_formatter_1 = require(176) /* ./basic_tick_formatter */;
    __esExport("BasicTickFormatter", basic_tick_formatter_1.BasicTickFormatter);
    var categorical_tick_formatter_1 = require(172) /* ./categorical_tick_formatter */;
    __esExport("CategoricalTickFormatter", categorical_tick_formatter_1.CategoricalTickFormatter);
    var datetime_tick_formatter_1 = require(180) /* ./datetime_tick_formatter */;
    __esExport("DatetimeTickFormatter", datetime_tick_formatter_1.DatetimeTickFormatter);
    var func_tick_formatter_1 = require(206) /* ./func_tick_formatter */;
    __esExport("FuncTickFormatter", func_tick_formatter_1.FuncTickFormatter);
    var log_tick_formatter_1 = require(193) /* ./log_tick_formatter */;
    __esExport("LogTickFormatter", log_tick_formatter_1.LogTickFormatter);
    var mercator_tick_formatter_1 = require(196) /* ./mercator_tick_formatter */;
    __esExport("MercatorTickFormatter", mercator_tick_formatter_1.MercatorTickFormatter);
    var numeral_tick_formatter_1 = require(207) /* ./numeral_tick_formatter */;
    __esExport("NumeralTickFormatter", numeral_tick_formatter_1.NumeralTickFormatter);
    var printf_tick_formatter_1 = require(208) /* ./printf_tick_formatter */;
    __esExport("PrintfTickFormatter", printf_tick_formatter_1.PrintfTickFormatter);
    var tick_formatter_1 = require(166) /* ./tick_formatter */;
    __esExport("TickFormatter", tick_formatter_1.TickFormatter);
},
/* models/formatters/func_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(166) /* ./tick_formatter */;
    const object_1 = require(13) /* ../../core/util/object */;
    const string_1 = require(34) /* ../../core/util/string */;
    class FuncTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static init_FuncTickFormatter() {
            this.define(({ Unknown, String, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            }));
        }
        get names() {
            return object_1.keys(this.args);
        }
        get values() {
            return object_1.values(this.args);
        }
        /*protected*/ _make_func() {
            const code = 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.FuncTickFormatter = FuncTickFormatter;
    FuncTickFormatter.__name__ = "FuncTickFormatter";
    FuncTickFormatter.init_FuncTickFormatter();
},
/* models/formatters/numeral_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const Numbro = tslib_1.__importStar(require(183) /* @bokeh/numbro */);
    const tick_formatter_1 = require(166) /* ./tick_formatter */;
    const enums_1 = require(20) /* ../../core/enums */;
    class NumeralTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static init_NumeralTickFormatter() {
            this.define(({ String }) => ({
                // TODO (bev) all of these could be tightened up
                format: [String, "0,0"],
                language: [String, "en"],
                rounding: [enums_1.RoundingFunction, "round"],
            }));
        }
        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;
    NumeralTickFormatter.__name__ = "NumeralTickFormatter";
    NumeralTickFormatter.init_NumeralTickFormatter();
},
/* models/formatters/printf_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(166) /* ./tick_formatter */;
    const templating_1 = require(182) /* ../../core/util/templating */;
    class PrintfTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        static init_PrintfTickFormatter() {
            this.define(({ String }) => ({
                format: [String, "%s"],
            }));
        }
        doFormat(ticks, _opts) {
            return ticks.map((tick) => templating_1.sprintf(this.format, tick));
        }
    }
    exports.PrintfTickFormatter = PrintfTickFormatter;
    PrintfTickFormatter.__name__ = "PrintfTickFormatter";
    PrintfTickFormatter.init_PrintfTickFormatter();
},
/* models/mappers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_color_mapper_1 = require(210) /* ./categorical_color_mapper */;
    __esExport("CategoricalColorMapper", categorical_color_mapper_1.CategoricalColorMapper);
    var categorical_marker_mapper_1 = require(212) /* ./categorical_marker_mapper */;
    __esExport("CategoricalMarkerMapper", categorical_marker_mapper_1.CategoricalMarkerMapper);
    var categorical_pattern_mapper_1 = require(213) /* ./categorical_pattern_mapper */;
    __esExport("CategoricalPatternMapper", categorical_pattern_mapper_1.CategoricalPatternMapper);
    var continuous_color_mapper_1 = require(202) /* ./continuous_color_mapper */;
    __esExport("ContinuousColorMapper", continuous_color_mapper_1.ContinuousColorMapper);
    var color_mapper_1 = require(203) /* ./color_mapper */;
    __esExport("ColorMapper", color_mapper_1.ColorMapper);
    var linear_color_mapper_1 = require(214) /* ./linear_color_mapper */;
    __esExport("LinearColorMapper", linear_color_mapper_1.LinearColorMapper);
    var log_color_mapper_1 = require(215) /* ./log_color_mapper */;
    __esExport("LogColorMapper", log_color_mapper_1.LogColorMapper);
    var scanning_color_mapper_1 = require(201) /* ./scanning_color_mapper */;
    __esExport("ScanningColorMapper", scanning_color_mapper_1.ScanningColorMapper);
    var eqhist_color_mapper_1 = require(216) /* ./eqhist_color_mapper */;
    __esExport("EqHistColorMapper", eqhist_color_mapper_1.EqHistColorMapper);
},
/* models/mappers/categorical_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const categorical_mapper_1 = require(211) /* ./categorical_mapper */;
    const color_mapper_1 = require(203) /* ./color_mapper */;
    const factor_range_1 = require(104) /* ../ranges/factor_range */;
    class CategoricalColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        static init_CategoricalColorMapper() {
            this.define(({ Number, Nullable }) => ({
                factors: [factor_range_1.FactorSeq],
                start: [Number, 0],
                end: [Nullable(Number), null],
            }));
        }
        _v_compute(data, values, palette, { nan_color }) {
            categorical_mapper_1.cat_v_compute(data, this.factors, palette, values, this.start, this.end, nan_color);
        }
    }
    exports.CategoricalColorMapper = CategoricalColorMapper;
    CategoricalColorMapper.__name__ = "CategoricalColorMapper";
    CategoricalColorMapper.init_CategoricalColorMapper();
},
/* models/mappers/categorical_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const types_1 = require(8) /* ../../core/util/types */;
    function _cat_equals(a, b) {
        if (a.length != b.length)
            return false;
        for (let i = 0, end = a.length; i < end; i++) {
            if (a[i] !== b[i])
                return false;
        }
        return true;
    }
    exports._cat_equals = _cat_equals;
    function cat_v_compute(data, factors, targets, values, start, end, extra_value) {
        const N = data.length;
        for (let i = 0; i < N; i++) {
            let d = data[i];
            let key;
            if (types_1.isString(d))
                key = arrayable_1.index_of(factors, d);
            else {
                if (start != null) {
                    if (end != null)
                        d = d.slice(start, end);
                    else
                        d = d.slice(start);
                }
                else if (end != null)
                    d = d.slice(0, end);
                if (d.length == 1)
                    key = arrayable_1.index_of(factors, d[0]);
                else
                    key = arrayable_1.find_index(factors, (x) => _cat_equals(x, d));
            }
            let value;
            if (key < 0 || key >= targets.length)
                value = extra_value;
            else
                value = targets[key];
            values[i] = value;
        }
    }
    exports.cat_v_compute = cat_v_compute;
},
/* models/mappers/categorical_marker_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const categorical_mapper_1 = require(211) /* ./categorical_mapper */;
    const factor_range_1 = require(104) /* ../ranges/factor_range */;
    const mapper_1 = require(204) /* ./mapper */;
    const enums_1 = require(20) /* ../../core/enums */;
    class CategoricalMarkerMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        static init_CategoricalMarkerMapper() {
            this.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"],
            }));
        }
        v_compute(xs) {
            const values = new Array(xs.length);
            categorical_mapper_1.cat_v_compute(xs, this.factors, this.markers, values, this.start, this.end, this.default_value);
            return values;
        }
    }
    exports.CategoricalMarkerMapper = CategoricalMarkerMapper;
    CategoricalMarkerMapper.__name__ = "CategoricalMarkerMapper";
    CategoricalMarkerMapper.init_CategoricalMarkerMapper();
},
/* models/mappers/categorical_pattern_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const categorical_mapper_1 = require(211) /* ./categorical_mapper */;
    const factor_range_1 = require(104) /* ../ranges/factor_range */;
    const mapper_1 = require(204) /* ./mapper */;
    const enums_1 = require(20) /* ../../core/enums */;
    class CategoricalPatternMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        static init_CategoricalPatternMapper() {
            this.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, " "],
            }));
        }
        v_compute(xs) {
            const values = new Array(xs.length);
            categorical_mapper_1.cat_v_compute(xs, this.factors, this.patterns, values, this.start, this.end, this.default_value);
            return values;
        }
    }
    exports.CategoricalPatternMapper = CategoricalPatternMapper;
    CategoricalPatternMapper.__name__ = "CategoricalPatternMapper";
    CategoricalPatternMapper.init_CategoricalPatternMapper();
},
/* models/mappers/linear_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(202) /* ./continuous_color_mapper */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    class LinearColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        scan(data, n) {
            const low = this.low != null ? this.low : arrayable_1.min(data);
            const high = this.high != null ? this.high : arrayable_1.max(data);
            const norm_factor = 1 / (high - low);
            const normed_interval = 1 / n;
            return { max: high, min: low, norm_factor, normed_interval };
        }
        cmap(d, palette, low_color, high_color, scan_data) {
            // This handles the edge case where d == high, since the code below maps
            // values exactly equal to high to palette.length, which is greater than
            // max_key
            const max_key = palette.length - 1;
            if (d == scan_data.max) {
                return palette[max_key];
            }
            const normed_d = (d - scan_data.min) * scan_data.norm_factor;
            const key = Math.floor(normed_d / scan_data.normed_interval);
            if (key < 0)
                return low_color;
            else if (key > max_key)
                return high_color;
            else
                return palette[key];
        }
    }
    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(202) /* ./continuous_color_mapper */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    class LogColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        scan(data, n) {
            const low = this.low != null ? this.low : arrayable_1.min(data);
            const high = this.high != null ? this.high : arrayable_1.max(data);
            const scale = n / (Math.log(high) - Math.log(low)); // subtract the low offset
            return { max: high, min: low, scale };
        }
        cmap(d, palette, low_color, high_color, scan_data) {
            const max_key = palette.length - 1;
            if (d > scan_data.max) {
                return high_color;
            }
            // This handles the edge case where d == high, since the code below maps
            // values exactly equal to high to palette.length, which is greater than
            // max_key
            if (d == scan_data.max)
                return palette[max_key];
            else if (d < scan_data.min)
                return low_color;
            // Get the key
            const log = Math.log(d) - Math.log(scan_data.min); // subtract the low offset
            let key = Math.floor(log * scan_data.scale);
            // Deal with upper bound
            if (key > max_key) {
                key = max_key;
            }
            return palette[key];
        }
    }
    exports.LogColorMapper = LogColorMapper;
    LogColorMapper.__name__ = "LogColorMapper";
},
/* models/mappers/eqhist_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scanning_color_mapper_1 = require(201) /* ./scanning_color_mapper */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const array_1 = require(9) /* ../../core/util/array */;
    const logging_1 = require(19) /* ../../core/logging */;
    class EqHistColorMapper extends scanning_color_mapper_1.ScanningColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        static init_EqHistColorMapper() {
            this.define(({ Int }) => ({
                bins: [Int, 256 * 256],
            }));
        }
        scan(data, n) {
            const low = this.low != null ? this.low : arrayable_1.min(data);
            const high = this.high != null ? this.high : arrayable_1.max(data);
            const nbins = this.bins;
            const eq_bin_edges = array_1.linspace(low, high, nbins + 1);
            const hist = arrayable_1.bin_counts(data, eq_bin_edges);
            const eq_bin_centers = new Array(nbins);
            for (let i = 0, length = eq_bin_edges.length; i < length - 1; i++) {
                const left = eq_bin_edges[i];
                const right = eq_bin_edges[i + 1];
                eq_bin_centers[i] = (left + right) / 2;
            }
            // CDFs
            const cdf = array_1.cumsum(hist);
            const cdf_max = cdf[cdf.length - 1];
            const norm_cdf = arrayable_1.map(cdf, (x) => x / cdf_max);
            // Iteratively find as many finite bins as there are colors
            let finite_bins = n - 1;
            let binning = [];
            let iterations = 0;
            let guess = n * 2;
            while ((finite_bins != n) && (iterations < 4) && (finite_bins != 0)) {
                const ratio = guess / finite_bins;
                if (ratio > 1000) {
                    // Abort if distribution is extremely skewed
                    break;
                }
                guess = Math.round(Math.max(n * ratio, n));
                // Interpolate
                const palette_edges = array_1.range(0, guess);
                const palette_cdf = arrayable_1.map(norm_cdf, (x) => x * (guess - 1));
                binning = arrayable_1.interpolate(palette_edges, palette_cdf, eq_bin_centers);
                // Evaluate binning
                const uniq_bins = array_1.uniq(binning);
                finite_bins = uniq_bins.length - 1;
                iterations++;
            }
            if (finite_bins == 0) {
                binning = [low, high];
                for (let j = 0; j < n - 1; j++)
                    binning.push(high);
            }
            else {
                binning = binning.slice(binning.length - n - 1);
                if (finite_bins != n)
                    logging_1.logger.warn("EqHistColorMapper warning: Histogram equalization did not converge.");
            }
            // XXX: should this be guaranteed by the above algorithm?
            binning[0] = low;
            binning[binning.length - 1] = high;
            return { min: low, max: high, binning };
        }
    }
    exports.EqHistColorMapper = EqHistColorMapper;
    EqHistColorMapper.__name__ = "EqHistColorMapper";
    EqHistColorMapper.init_EqHistColorMapper();
},
/* models/scales/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_scale_1 = require(145) /* ./categorical_scale */;
    __esExport("CategoricalScale", categorical_scale_1.CategoricalScale);
    var continuous_scale_1 = require(158) /* ./continuous_scale */;
    __esExport("ContinuousScale", continuous_scale_1.ContinuousScale);
    var linear_scale_1 = require(218) /* ./linear_scale */;
    __esExport("LinearScale", linear_scale_1.LinearScale);
    var linear_interpolation_scale_1 = require(219) /* ./linear_interpolation_scale */;
    __esExport("LinearInterpolationScale", linear_interpolation_scale_1.LinearInterpolationScale);
    var log_scale_1 = require(157) /* ./log_scale */;
    __esExport("LogScale", log_scale_1.LogScale);
    var scale_1 = require(146) /* ./scale */;
    __esExport("Scale", scale_1.Scale);
},
/* models/scales/linear_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_scale_1 = require(158) /* ./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;
        }
        compute(x) {
            return this._linear_compute(x);
        }
        v_compute(xs) {
            return this._linear_v_compute(xs);
        }
        invert(xprime) {
            return this._linear_invert(xprime);
        }
        v_invert(xprimes) {
            return this._linear_v_invert(xprimes);
        }
    }
    exports.LinearScale = LinearScale;
    LinearScale.__name__ = "LinearScale";
},
/* models/scales/linear_interpolation_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(146) /* ./scale */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    class LinearInterpolationScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        static init_LinearInterpolationScale() {
            this.internal(({ Arrayable }) => ({
                binning: [Arrayable],
            }));
        }
        get s_compute() {
            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 = arrayable_1.map(vs, (v) => {
                if (v < min_val)
                    return min_val;
                if (v > max_val)
                    return max_val;
                const k = arrayable_1.left_edge_index(v, binning);
                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_v_compute(vvs);
        }
        invert(xprime) {
            return xprime;
        }
        v_invert(xprimes) {
            return new Float64Array(xprimes);
        }
    }
    exports.LinearInterpolationScale = LinearInterpolationScale;
    LinearInterpolationScale.__name__ = "LinearInterpolationScale";
    LinearInterpolationScale.init_LinearInterpolationScale();
},
/* models/ranges/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var data_range_1 = require(160) /* ./data_range */;
    __esExport("DataRange", data_range_1.DataRange);
    var data_range1d_1 = require(159) /* ./data_range1d */;
    __esExport("DataRange1d", data_range1d_1.DataRange1d);
    var factor_range_1 = require(104) /* ./factor_range */;
    __esExport("FactorRange", factor_range_1.FactorRange);
    var range_1 = require(105) /* ./range */;
    __esExport("Range", range_1.Range);
    var range1d_1 = require(156) /* ./range1d */;
    __esExport("Range1d", range1d_1.Range1d);
},
/* core/layout/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(141) /* ./types */;
    __esExport("Sizeable", types_1.Sizeable);
    __esExport("SizingPolicy", types_1.SizingPolicy);
    var layoutable_1 = require(142) /* ./layoutable */;
    __esExport("Layoutable", layoutable_1.Layoutable);
    __esExport("LayoutItem", layoutable_1.LayoutItem);
    var alignments_1 = require(222) /* ./alignments */;
    __esExport("HStack", alignments_1.HStack);
    __esExport("VStack", alignments_1.VStack);
    var grid_1 = require(223) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
    __esExport("Row", grid_1.Row);
    __esExport("Column", grid_1.Column);
    var html_1 = require(224) /* ./html */;
    __esExport("ContentBox", html_1.ContentBox);
    __esExport("VariadicBox", html_1.VariadicBox);
},
/* core/layout/alignments.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layoutable_1 = require(142) /* ./layoutable */;
    const bbox_1 = require(99) /* ../util/bbox */;
    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 = Math.max(height, size_hint.height);
            }
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            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 = Math.max(width, size_hint.width);
                height += size_hint.height;
            }
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            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);
            const bbox = this.absolute ? outer : outer.relative();
            const { left, right, top, bottom } = bbox;
            const vcenter = Math.round(bbox.vcenter);
            const hcenter = Math.round(bbox.hcenter);
            for (const layout of this.children) {
                const { margin, halign, valign } = 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(141) /* ./types */;
    const layoutable_1 = require(142) /* ./layoutable */;
    const types_2 = require(8) /* ../util/types */;
    const bbox_1 = require(99) /* ../util/bbox */;
    const array_1 = require(9) /* ../util/array */;
    const { max, round } = Math;
    class DefaultMap {
        constructor(def) {
            this.def = def;
            this._map = new Map();
        }
        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));
        }
    }
    DefaultMap.__name__ = "DefaultMap";
    class Container {
        constructor() {
            this._items = [];
            this._nrows = 0;
            this._ncols = 0;
        }
        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);
        }
        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;
        }
    }
    Container.__name__ = "Container";
    class Grid extends layoutable_1.Layoutable {
        constructor(items = []) {
            super();
            this.items = items;
            this.rows = "auto";
            this.cols = "auto";
            this.spacing = 0;
        }
        *[Symbol.iterator]() {
            for (const { layout } of this.items) {
                yield layout;
            }
        }
        is_width_expanding() {
            if (super.is_width_expanding())
                return true;
            if (this.sizing.width_policy == "fixed")
                return false;
            const { cols } = this._state;
            return 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 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, col_span } of this.items) {
                if (layout.sizing.visible) {
                    const r0 = row;
                    const c0 = col;
                    const r1 = row + (row_span != null ? row_span : 1) - 1;
                    const c1 = col + (col_span != null ? col_span : 1) - 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 = 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 (types_2.isNumber(sizing))
                        return { policy: "fixed", height: sizing };
                    else if (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 (row.policy == "auto") {
                    if (array_1.some(items.row(y), (layout) => layout.is_height_expanding()))
                        rows[y] = { policy: "max", flex: 1, align };
                    else
                        rows[y] = { policy: "min", align };
                }
                else
                    throw new Error("unrechable");
            }
            const cols = new Array(ncols);
            for (let x = 0; x < ncols; x++) {
                const col = (() => {
                    var _a;
                    const sizing = 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 (types_2.isNumber(sizing))
                        return { policy: "fixed", width: sizing };
                    else if (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 (col.policy == "auto") {
                    if (array_1.some(items.col(x), (layout) => layout.is_width_expanding()))
                        cols[x] = { policy: "max", flex: 1, align };
                    else
                        cols[x] = { policy: "min", align };
                }
                else
                    throw new Error("unrechable");
            }
            const [rspacing, cspacing] = 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: array_1.sum(row_heights) + (nrows - 1) * rspacing,
                width: 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 distribute_height = (size_hint) => {
                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 = size_hint.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 -= size_hint.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;
                            size_hint.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 = size_hint.row_heights[y];
                            const cutoff = round(overflow_height / nadjustable);
                            size_hint.row_heights[y] = max(height - cutoff, 0);
                            overflow_height -= cutoff > height ? height : cutoff;
                            nadjustable--;
                        }
                    }
                }
            };
            const distribute_width = (size_hint) => {
                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 = size_hint.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 -= size_hint.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;
                            size_hint.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 = size_hint.col_widths[x];
                            const cutoff = round(overflow_width / nadjustable);
                            size_hint.col_widths[x] = max(width - cutoff, 0);
                            overflow_width -= cutoff > width ? width : cutoff;
                            nadjustable--;
                        }
                    }
                }
            };
            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,
                };
            });
            distribute_height(preferred);
            distribute_width(preferred);
            const adjusted = this._measure_cells((y, x) => {
                return {
                    width: preferred.col_widths[x],
                    height: preferred.row_heights[y],
                };
            });
            distribute_height(adjusted);
            distribute_width(adjusted);
            const { row_heights, col_widths } = adjusted;
            const size = this._measure_totals(row_heights, col_widths);
            return { size, row_heights, col_widths };
        }
        _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 } = this._measure_grid(outer);
            const { size_hints } = this._measure_cells((y, x) => {
                return {
                    width: col_widths[x],
                    height: row_heights[y],
                };
            });
            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 ? 0 : outer.top; r < nrows; r++) {
                const row = rows[r];
                row.top = top;
                top += row.height + rspacing;
            }
            for (let c = 0, left = !this.absolute ? 0 : 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/html.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layoutable_1 = require(142) /* ./layoutable */;
    const types_1 = require(141) /* ./types */;
    const dom_1 = require(43) /* ../dom */;
    class ContentBox extends layoutable_1.ContentLayoutable {
        constructor(el) {
            super();
            this.content_size = dom_1.unsized(el, () => new types_1.Sizeable(dom_1.size(el)));
        }
        _content_size() {
            return this.content_size;
        }
    }
    exports.ContentBox = ContentBox;
    ContentBox.__name__ = "ContentBox";
    class VariadicBox extends layoutable_1.Layoutable {
        constructor(el) {
            super();
            this.el = el;
        }
        _measure(viewport) {
            const bounded = new types_1.Sizeable(viewport).bounded_to(this.sizing.size);
            return dom_1.sized(this.el, bounded, () => {
                const content = new types_1.Sizeable(dom_1.content_size(this.el));
                const { border, padding } = dom_1.extents(this.el);
                return content.grow_by(border).grow_by(padding).map(Math.ceil);
            });
        }
    }
    exports.VariadicBox = VariadicBox;
    VariadicBox.__name__ = "VariadicBox";
    class CachedVariadicBox extends VariadicBox {
        constructor(el) {
            super(el);
            this._cache = new Map();
        }
        _measure(viewport) {
            const { width, height } = viewport;
            const key = `${width},${height}`;
            let size_hint = this._cache.get(key);
            if (size_hint == null) {
                size_hint = super._measure(viewport);
                this._cache.set(key, size_hint);
            }
            return size_hint;
        }
        invalidate_cache() {
            this._cache.clear();
        }
    }
    exports.CachedVariadicBox = CachedVariadicBox;
    CachedVariadicBox.__name__ = "CachedVariadicBox";
},
/* core/layout/border.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(141) /* ./types */;
    const layoutable_1 = require(142) /* ./layoutable */;
    const bbox_1 = require(99) /* ../util/bbox */;
    class BorderLayout extends layoutable_1.Layoutable {
        constructor() {
            super(...arguments);
            this.min_border = { left: 0, top: 0, right: 0, bottom: 0 };
            this.padding = { left: 0, top: 0, right: 0, bottom: 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 width_policy != "fixed" && height_policy != "fixed";
            })();
            return { width, height, inner: { left, right, top, bottom }, align };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            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 }));
        }
    }
    exports.BorderLayout = BorderLayout;
    BorderLayout.__name__ = "BorderLayout";
},
/* models/annotations/label.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(139) /* ./text_annotation */;
    const math_1 = require(10) /* ../../core/util/math */;
    const text_1 = require(143) /* ../../core/util/text */;
    const enums_1 = require(20) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    class LabelView extends text_annotation_1.TextAnnotationView {
        _get_size() {
            const { ctx } = this.layer;
            this.visuals.text.set_value(ctx);
            const { width } = ctx.measureText(this.model.text);
            const { height } = text_1.font_metrics(ctx.font);
            return { width, height };
        }
        _render() {
            const { angle, angle_units } = this.model;
            const rotation = math_1.resolve_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 = this.model.x_units == "data" ? xscale.compute(this.model.x) : panel.bbox.xview.compute(this.model.x);
            let sy = this.model.y_units == "data" ? yscale.compute(this.model.y) : panel.bbox.yview.compute(this.model.y);
            sx += this.model.x_offset;
            sy -= this.model.y_offset;
            const draw = this.model.render_mode == 'canvas' ? this._canvas_text.bind(this) : this._css_text.bind(this);
            draw(this.layer.ctx, this.model.text, sx, sy, rotation);
        }
    }
    exports.LabelView = LabelView;
    LabelView.__name__ = "LabelView";
    class Label extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_Label() {
            this.prototype.default_view = LabelView;
            this.mixins([
                mixins.Text,
                ["border_", mixins.Line],
                ["background_", mixins.Fill],
            ]);
            this.define(({ Number, String, Angle }) => ({
                x: [Number],
                x_units: [enums_1.SpatialUnits, "data"],
                y: [Number],
                y_units: [enums_1.SpatialUnits, "data"],
                text: [String, ""],
                angle: [Angle, 0],
                angle_units: [enums_1.AngleUnits, "rad"],
                x_offset: [Number, 0],
                y_offset: [Number, 0],
            }));
            this.override({
                background_fill_color: null,
                border_line_color: null,
            });
        }
    }
    exports.Label = Label;
    Label.__name__ = "Label";
    Label.init_Label();
},
/* models/annotations/label_set.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(139) /* ./text_annotation */;
    const data_annotation_1 = require(56) /* ./data_annotation */;
    const column_data_source_1 = require(130) /* ../sources/column_data_source */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const dom_1 = require(43) /* ../../core/dom */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const text_1 = require(143) /* ../../core/util/text */;
    class LabelSetView extends text_annotation_1.TextAnnotationView {
        // XXX: can't inherit DataAnnotation currently
        set_data(source) {
            data_annotation_1.DataAnnotationView.prototype.set_data.call(this, source);
        }
        initialize() {
            super.initialize();
            this.set_data(this.model.source);
            if (this.model.render_mode == 'css') {
                for (let i = 0, end = this.text.length; i < end; i++) {
                    const el = dom_1.div({ style: { display: "none" } });
                    this.el.appendChild(el);
                }
            }
        }
        connect_signals() {
            super.connect_signals();
            const render = () => {
                this.set_data(this.model.source);
                if (this.model.render_mode == "css")
                    this.render();
                else
                    this.request_render();
            };
            this.connect(this.model.change, render);
            this.connect(this.model.source.streaming, render);
            this.connect(this.model.source.patching, render);
            this.connect(this.model.source.change, render);
        }
        _calculate_text_dimensions(ctx, text) {
            const { width } = ctx.measureText(text);
            const { height } = text_1.font_metrics(this.visuals.text.font_value(0));
            return [width, height];
        }
        _map_data() {
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const sx = this.model.x_units == "data" ? xscale.v_compute(this._x) : panel.bbox.xview.v_compute(this._x);
            const sy = this.model.y_units == "data" ? yscale.v_compute(this._y) : panel.bbox.yview.v_compute(this._y);
            return [sx, sy];
        }
        _render() {
            const draw = this.model.render_mode == 'canvas' ? this._v_canvas_text.bind(this) : this._v_css_text.bind(this);
            const { ctx } = this.layer;
            const [sx, sy] = this._map_data();
            for (let i = 0, end = this.text.length; i < end; i++) {
                draw(ctx, i, this.text.get(i), sx[i] + this.x_offset.get(i), sy[i] - this.y_offset.get(i), this.angle.get(i));
            }
        }
        _get_size() {
            const { ctx } = this.layer;
            this.visuals.text.set_vectorize(ctx, 0);
            const { width } = ctx.measureText(this.text.get(0));
            const { height } = text_1.font_metrics(ctx.font);
            return { width, height };
        }
        _v_canvas_text(ctx, i, text, sx, sy, angle) {
            this.visuals.text.set_vectorize(ctx, i);
            const bbox_dims = this._calculate_bounding_box_dimensions(ctx, text);
            ctx.save();
            ctx.beginPath();
            ctx.translate(sx, sy);
            ctx.rotate(angle);
            ctx.rect(bbox_dims[0], bbox_dims[1], bbox_dims[2], bbox_dims[3]);
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_vectorize(ctx, i);
                ctx.fill();
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_vectorize(ctx, i);
                ctx.stroke();
            }
            if (this.visuals.text.doit) {
                this.visuals.text.set_vectorize(ctx, i);
                ctx.fillText(text, 0, 0);
            }
            ctx.restore();
        }
        _v_css_text(ctx, i, text, sx, sy, angle) {
            const el = this.el.children[i];
            el.textContent = text;
            this.visuals.text.set_vectorize(ctx, i);
            const [x, y] = this._calculate_bounding_box_dimensions(ctx, text);
            el.style.position = "absolute";
            el.style.left = `${sx + x}px`;
            el.style.top = `${sy + y}px`;
            el.style.color = ctx.fillStyle;
            el.style.font = ctx.font;
            el.style.lineHeight = "normal"; // needed to prevent ipynb css override
            if (angle) {
                el.style.transform = `rotate(${angle}rad)`;
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_vectorize(ctx, i);
                el.style.backgroundColor = ctx.fillStyle;
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_vectorize(ctx, i);
                // attempt to support vector-style ("8 4 8") line dashing for css mode
                el.style.borderStyle = ctx.lineDash.length < 2 ? "solid" : "dashed";
                el.style.borderWidth = `${ctx.lineWidth}px`;
                el.style.borderColor = ctx.strokeStyle;
            }
            dom_1.display(el);
        }
    }
    exports.LabelSetView = LabelSetView;
    LabelSetView.__name__ = "LabelSetView";
    class LabelSet extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_LabelSet() {
            this.prototype.default_view = LabelSetView;
            this.mixins([
                mixins.TextVector,
                ["border_", mixins.LineVector],
                ["background_", mixins.FillVector],
            ]);
            this.define(({ Ref }) => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                y: [p.YCoordinateSpec, { field: "y" }],
                x_units: [enums_1.SpatialUnits, "data"],
                y_units: [enums_1.SpatialUnits, "data"],
                text: [p.StringSpec, { field: "text" }],
                angle: [p.AngleSpec, 0],
                x_offset: [p.NumberSpec, { value: 0 }],
                y_offset: [p.NumberSpec, { value: 0 }],
                source: [Ref(column_data_source_1.ColumnDataSource), () => new column_data_source_1.ColumnDataSource()],
            }));
            this.override({
                background_fill_color: null,
                border_line_color: null,
            });
        }
    }
    exports.LabelSet = LabelSet;
    LabelSet.__name__ = "LabelSet";
    LabelSet.init_LabelSet();
},
/* models/annotations/legend.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(40) /* ./annotation */;
    const legend_item_1 = require(229) /* ./legend_item */;
    const enums_1 = require(20) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const signaling_1 = require(15) /* ../../core/signaling */;
    const side_panel_1 = require(140) /* ../../core/layout/side_panel */;
    const text_1 = require(143) /* ../../core/util/text */;
    const bbox_1 = require(99) /* ../../core/util/bbox */;
    const array_1 = require(9) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    class LegendView extends annotation_1.AnnotationView {
        update_layout() {
            const { panel } = this;
            if (panel != null)
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size());
            else
                this.layout = undefined;
        }
        cursor(_sx, _sy) {
            return this.model.click_policy == "none" ? null : "pointer";
        }
        get legend_padding() {
            return this.model.border_line_color != null ? this.model.padding : 0;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
            this.connect(this.model.item_change, () => this.request_render());
        }
        compute_legend_bbox() {
            const legend_names = this.model.get_legend_names();
            const { glyph_height, glyph_width } = this.model;
            const { label_height, label_width } = this.model;
            this.max_label_height = array_1.max([text_1.font_metrics(this.visuals.label_text.font_value()).height, label_height, glyph_height]);
            // this is to measure text properties
            const { ctx } = this.layer;
            ctx.save();
            this.visuals.label_text.set_value(ctx);
            this.text_widths = new Map();
            for (const name of legend_names) {
                this.text_widths.set(name, array_1.max([ctx.measureText(name).width, label_width]));
            }
            this.visuals.title_text.set_value(ctx);
            this.title_height = this.model.title ? text_1.font_metrics(this.visuals.title_text.font_value()).height + this.model.title_standoff : 0;
            this.title_width = this.model.title ? ctx.measureText(this.model.title).width : 0;
            ctx.restore();
            const max_label_width = Math.max(array_1.max([...this.text_widths.values()]), 0);
            const legend_margin = this.model.margin;
            const { legend_padding } = this;
            const legend_spacing = this.model.spacing;
            const { label_standoff } = this.model;
            let legend_height, legend_width;
            if (this.model.orientation == "vertical") {
                legend_height = legend_names.length * this.max_label_height + Math.max(legend_names.length - 1, 0) * legend_spacing + 2 * legend_padding + this.title_height;
                legend_width = array_1.max([(max_label_width + glyph_width + label_standoff + 2 * legend_padding), this.title_width + 2 * legend_padding]);
            }
            else {
                let item_width = 2 * legend_padding + Math.max(legend_names.length - 1, 0) * legend_spacing;
                for (const [, width] of this.text_widths) {
                    item_width += array_1.max([width, label_width]) + glyph_width + label_standoff;
                }
                legend_width = array_1.max([this.title_width + 2 * legend_padding, item_width]);
                legend_height = this.max_label_height + this.title_height + 2 * legend_padding;
            }
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const [hr, vr] = panel.bbox.ranges;
            const { location } = this.model;
            let sx, sy;
            if (types_1.isString(location)) {
                switch (location) {
                    case 'top_left':
                        sx = hr.start + legend_margin;
                        sy = vr.start + legend_margin;
                        break;
                    case 'top':
                    case 'top_center':
                        sx = (hr.end + hr.start) / 2 - legend_width / 2;
                        sy = vr.start + legend_margin;
                        break;
                    case 'top_right':
                        sx = hr.end - legend_margin - legend_width;
                        sy = vr.start + legend_margin;
                        break;
                    case 'bottom_right':
                        sx = hr.end - legend_margin - legend_width;
                        sy = vr.end - legend_margin - legend_height;
                        break;
                    case 'bottom':
                    case 'bottom_center':
                        sx = (hr.end + hr.start) / 2 - legend_width / 2;
                        sy = vr.end - legend_margin - legend_height;
                        break;
                    case 'bottom_left':
                        sx = hr.start + legend_margin;
                        sy = vr.end - legend_margin - legend_height;
                        break;
                    case 'left':
                    case 'center_left':
                        sx = hr.start + legend_margin;
                        sy = (vr.end + vr.start) / 2 - legend_height / 2;
                        break;
                    case 'center':
                    case 'center_center':
                        sx = (hr.end + hr.start) / 2 - legend_width / 2;
                        sy = (vr.end + vr.start) / 2 - legend_height / 2;
                        break;
                    case 'right':
                    case 'center_right':
                        sx = hr.end - legend_margin - legend_width;
                        sy = (vr.end + vr.start) / 2 - legend_height / 2;
                        break;
                }
            }
            else if (types_1.isArray(location) && location.length == 2) {
                const [vx, vy] = location;
                sx = panel.bbox.xview.compute(vx);
                sy = panel.bbox.yview.compute(vy) - legend_height;
            }
            else
                assert_1.unreachable();
            return new bbox_1.BBox({ left: sx, top: sy, width: legend_width, height: legend_height });
        }
        interactive_bbox() {
            return this.compute_legend_bbox();
        }
        interactive_hit(sx, sy) {
            const bbox = this.interactive_bbox();
            return bbox.contains(sx, sy);
        }
        on_hit(sx, sy) {
            let yoffset;
            const { glyph_width } = this.model;
            const { legend_padding } = this;
            const legend_spacing = this.model.spacing;
            const { label_standoff } = this.model;
            let xoffset = (yoffset = legend_padding);
            const legend_bbox = this.compute_legend_bbox();
            const vertical = this.model.orientation == "vertical";
            for (const item of this.model.items) {
                const labels = item.get_labels_list_from_label_prop();
                for (const label of labels) {
                    const x1 = legend_bbox.x + xoffset;
                    const y1 = legend_bbox.y + yoffset + this.title_height;
                    let w, h;
                    if (vertical)
                        [w, h] = [legend_bbox.width - 2 * legend_padding, this.max_label_height];
                    else
                        [w, h] = [this.text_widths.get(label) + glyph_width + label_standoff, this.max_label_height];
                    const bbox = new bbox_1.BBox({ left: x1, top: y1, width: w, height: h });
                    if (bbox.contains(sx, sy)) {
                        switch (this.model.click_policy) {
                            case "hide": {
                                for (const r of item.renderers)
                                    r.visible = !r.visible;
                                break;
                            }
                            case "mute": {
                                for (const r of item.renderers)
                                    r.muted = !r.muted;
                                break;
                            }
                        }
                        return true;
                    }
                    if (vertical)
                        yoffset += this.max_label_height + legend_spacing;
                    else
                        xoffset += this.text_widths.get(label) + glyph_width + label_standoff + legend_spacing;
                }
            }
            return false;
        }
        _render() {
            if (this.model.items.length == 0)
                return;
            // set a backref on render so that items can later signal item_change upates
            // on the model to trigger a re-render
            for (const item of this.model.items) {
                item.legend = this.model;
            }
            const { ctx } = this.layer;
            const bbox = this.compute_legend_bbox();
            ctx.save();
            this._draw_legend_box(ctx, bbox);
            this._draw_legend_items(ctx, bbox);
            this._draw_title(ctx, bbox);
            ctx.restore();
        }
        _draw_legend_box(ctx, bbox) {
            ctx.beginPath();
            ctx.rect(bbox.x, bbox.y, bbox.width, bbox.height);
            this.visuals.background_fill.set_value(ctx);
            ctx.fill();
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_value(ctx);
                ctx.stroke();
            }
        }
        _draw_legend_items(ctx, bbox) {
            const { glyph_width, glyph_height } = this.model;
            const { legend_padding } = this;
            const legend_spacing = this.model.spacing;
            const { label_standoff } = this.model;
            let xoffset = legend_padding;
            let yoffset = legend_padding;
            const vertical = this.model.orientation == "vertical";
            for (const item of this.model.items) {
                const labels = item.get_labels_list_from_label_prop();
                const field = item.get_field_from_label_prop();
                if (labels.length == 0)
                    continue;
                const active = (() => {
                    switch (this.model.click_policy) {
                        case "none": return true;
                        case "hide": return array_1.every(item.renderers, r => r.visible);
                        case "mute": return array_1.every(item.renderers, r => !r.muted);
                    }
                })();
                for (const label of labels) {
                    const x1 = bbox.x + xoffset;
                    const y1 = bbox.y + yoffset + this.title_height;
                    const x2 = x1 + glyph_width;
                    const y2 = y1 + glyph_height;
                    if (vertical)
                        yoffset += this.max_label_height + legend_spacing;
                    else
                        xoffset += this.text_widths.get(label) + glyph_width + label_standoff + legend_spacing;
                    this.visuals.label_text.set_value(ctx);
                    ctx.fillText(label, x2 + label_standoff, y1 + this.max_label_height / 2.0);
                    for (const r of item.renderers) {
                        const view = this.plot_view.renderer_view(r);
                        view === null || view === void 0 ? void 0 : view.draw_legend(ctx, x1, x2, y1, y2, field, label, item.index);
                    }
                    if (!active) {
                        let w, h;
                        if (vertical)
                            [w, h] = [bbox.width - 2 * legend_padding, this.max_label_height];
                        else
                            [w, h] = [this.text_widths.get(label) + glyph_width + label_standoff, this.max_label_height];
                        ctx.beginPath();
                        ctx.rect(x1, y1, w, h);
                        this.visuals.inactive_fill.set_value(ctx);
                        ctx.fill();
                    }
                }
            }
        }
        _draw_title(ctx, bbox) {
            const { title } = this.model;
            if (!title || !this.visuals.title_text.doit)
                return;
            ctx.save();
            ctx.translate(bbox.x0, bbox.y0 + this.title_height);
            this.visuals.title_text.set_value(ctx);
            ctx.fillText(title, this.legend_padding, this.legend_padding - this.model.title_standoff);
            ctx.restore();
        }
        _get_size() {
            const { width, height } = this.compute_legend_bbox();
            return {
                width: width + 2 * this.model.margin,
                height: height + 2 * this.model.margin,
            };
        }
    }
    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");
        }
        static init_Legend() {
            this.prototype.default_view = LegendView;
            this.mixins([
                ["label_", mixins.Text],
                ["title_", mixins.Text],
                ["inactive_", mixins.Fill],
                ["border_", mixins.Line],
                ["background_", mixins.Fill],
            ]);
            this.define(({ Number, String, Array, Tuple, Or, Ref, Nullable }) => ({
                orientation: [enums_1.Orientation, "vertical"],
                location: [Or(enums_1.LegendLocation, Tuple(Number, Number)), "top_right"],
                title: [Nullable(String), null],
                title_standoff: [Number, 5],
                label_standoff: [Number, 5],
                glyph_height: [Number, 20],
                glyph_width: [Number, 20],
                label_height: [Number, 20],
                label_width: [Number, 20],
                margin: [Number, 10],
                padding: [Number, 10],
                spacing: [Number, 3],
                items: [Array(Ref(legend_item_1.LegendItem)), []],
                click_policy: [enums_1.LegendClickPolicy, "none"],
            }));
            this.override({
                border_line_color: "#e5e5e5",
                border_line_alpha: 0.5,
                border_line_width: 1,
                background_fill_color: "#ffffff",
                background_fill_alpha: 0.95,
                inactive_fill_color: "white",
                inactive_fill_alpha: 0.7,
                label_text_font_size: "13px",
                label_text_baseline: "middle",
                title_text_font_size: "13px",
                title_text_font_style: "italic",
            });
        }
        get_legend_names() {
            const legend_names = [];
            for (const item of this.items) {
                const labels = item.get_labels_list_from_label_prop();
                legend_names.push(...labels);
            }
            return legend_names;
        }
    }
    exports.Legend = Legend;
    Legend.__name__ = "Legend";
    Legend.init_Legend();
},
/* models/annotations/legend_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(53) /* ../../model */;
    const glyph_renderer_1 = require(61) /* ../renderers/glyph_renderer */;
    const columnar_data_source_1 = require(57) /* ../sources/columnar_data_source */;
    const vectorization_1 = require(230) /* ../../core/vectorization */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const logging_1 = require(19) /* ../../core/logging */;
    const array_1 = require(9) /* ../../core/util/array */;
    class LegendItem extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_LegendItem() {
            this.define(({ Int, Array, Ref, Nullable }) => ({
                label: [p.NullStringSpec, null],
                renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
                index: [Nullable(Int), null],
            }));
        }
        /*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;
                if (source != null) {
                    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 (source != null && !array_1.includes(source.columns(), field)) {
                    return false;
                }
            }
            return true;
        }
        initialize() {
            super.initialize();
            this.legend = null;
            this.connect(this.change, () => { var _a; return (_a = this.legend) === null || _a === void 0 ? void 0 : _a.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 vectorization_1.isField(label) ? label.field : null;
        }
        get_labels_list_from_label_prop() {
            // Always return a list of the labels
            if (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[0] && this.renderers[0].data_source != null)
                    source = this.renderers[0].data_source;
                else
                    return ["No source found"];
                if (source instanceof columnar_data_source_1.ColumnarDataSource) {
                    const data = source.get_column(field);
                    if (data != null)
                        return array_1.uniq(Array.from(data));
                    else
                        return ["Invalid field"];
                }
            }
            return [];
        }
    }
    exports.LegendItem = LegendItem;
    LegendItem.__name__ = "LegendItem";
    LegendItem.init_LegendItem();
},
/* core/vectorization.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ./util/types */;
    function isValue(obj) {
        return types_1.isPlainObject(obj) && "value" in obj;
    }
    exports.isValue = isValue;
    function isField(obj) {
        return types_1.isPlainObject(obj) && "field" in obj;
    }
    exports.isField = isField;
    function isExpr(obj) {
        return types_1.isPlainObject(obj) && "expr" in obj;
    }
    exports.isExpr = isExpr;
},
/* models/annotations/poly_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(40) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    class PolyAnnotationView extends annotation_1.AnnotationView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
        }
        _render() {
            const { xs, ys } = this.model;
            if (xs.length != ys.length)
                return;
            const n = xs.length;
            if (n < 3)
                return;
            const { frame } = this.plot_view;
            const { ctx } = this.layer;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const { screen } = this.model;
            function _calc_dim(values, units, scale, view) {
                if (screen)
                    return values;
                else
                    return units == "data" ? scale.v_compute(values) : view.v_compute(values);
            }
            const sxs = _calc_dim(xs, this.model.xs_units, xscale, frame.bbox.xview);
            const sys = _calc_dim(ys, this.model.ys_units, yscale, frame.bbox.yview);
            ctx.beginPath();
            for (let i = 0; i < n; i++) {
                ctx.lineTo(sxs[i], sys[i]);
            }
            ctx.closePath();
            if (this.visuals.fill.doit) {
                this.visuals.fill.set_value(ctx);
                ctx.fill();
            }
            if (this.visuals.hatch.doit) {
                this.visuals.hatch.set_value(ctx);
                ctx.fill();
            }
            if (this.visuals.line.doit) {
                this.visuals.line.set_value(ctx);
                ctx.stroke();
            }
        }
    }
    exports.PolyAnnotationView = PolyAnnotationView;
    PolyAnnotationView.__name__ = "PolyAnnotationView";
    class PolyAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_PolyAnnotation() {
            this.prototype.default_view = PolyAnnotationView;
            this.mixins([mixins.Line, mixins.Fill, mixins.Hatch]);
            this.define(({ Number, Array }) => ({
                xs: [Array(Number), []],
                xs_units: [enums_1.SpatialUnits, "data"],
                ys: [Array(Number), []],
                ys_units: [enums_1.SpatialUnits, "data"],
            }));
            this.internal(({ Boolean }) => ({
                screen: [Boolean, false],
            }));
            this.override({
                fill_color: "#fff9ba",
                fill_alpha: 0.4,
                line_color: "#cccccc",
                line_alpha: 0.3,
            });
        }
        update({ xs, ys }) {
            this.setv({ xs, ys, screen: true }, { check_eq: false }); // XXX: because of inplace updates in tools
        }
    }
    exports.PolyAnnotation = PolyAnnotation;
    PolyAnnotation.__name__ = "PolyAnnotation";
    PolyAnnotation.init_PolyAnnotation();
},
/* models/annotations/slope.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(40) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(48) /* ../../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;
            let sy_start, sy_end, sx_start, sx_end;
            if (gradient == 0) {
                sy_start = yscale.compute(y_intercept);
                sy_end = sy_start;
                sx_start = frame.bbox.left;
                sx_end = sx_start + frame.bbox.width;
            }
            else {
                sy_start = frame.bbox.top;
                sy_end = sy_start + frame.bbox.height;
                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;
                sx_start = xscale.compute(x_start);
                sx_end = xscale.compute(x_end);
            }
            const { ctx } = this.layer;
            ctx.save();
            ctx.beginPath();
            this.visuals.line.set_value(ctx);
            ctx.moveTo(sx_start, sy_start);
            ctx.lineTo(sx_end, sy_end);
            ctx.stroke();
            ctx.restore();
        }
    }
    exports.SlopeView = SlopeView;
    SlopeView.__name__ = "SlopeView";
    class Slope extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_Slope() {
            this.prototype.default_view = SlopeView;
            this.mixins(mixins.Line);
            this.define(({ Number, Nullable }) => ({
                gradient: [Nullable(Number), null],
                y_intercept: [Nullable(Number), null],
            }));
            this.override({
                line_color: 'black',
            });
        }
    }
    exports.Slope = Slope;
    Slope.__name__ = "Slope";
    Slope.init_Slope();
},
/* models/annotations/span.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(40) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    class SpanView extends annotation_1.AnnotationView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.plot_view.request_paint(this));
        }
        _render() {
            const { location } = this.model;
            if (location == null) {
                return;
            }
            const { frame } = this.plot_view;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const _calc_dim = (scale, view) => {
                if (this.model.location_units == 'data')
                    return scale.compute(location);
                else
                    return this.model.for_hover ? location : view.compute(location);
            };
            let height, sleft, stop, width;
            if (this.model.dimension == 'width') {
                stop = _calc_dim(yscale, frame.bbox.yview);
                sleft = frame.bbox.left;
                width = frame.bbox.width;
                height = this.model.line_width;
            }
            else {
                stop = frame.bbox.top;
                sleft = _calc_dim(xscale, frame.bbox.xview);
                width = this.model.line_width;
                height = frame.bbox.height;
            }
            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);
            }
            ctx.stroke();
            ctx.restore();
        }
    }
    exports.SpanView = SpanView;
    SpanView.__name__ = "SpanView";
    class Span extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_Span() {
            this.prototype.default_view = SpanView;
            this.mixins(mixins.Line);
            this.define(({ Number, Nullable }) => ({
                render_mode: [enums_1.RenderMode, "canvas"],
                location: [Nullable(Number), null],
                location_units: [enums_1.SpatialUnits, "data"],
                dimension: [enums_1.Dimension, "width"],
            }));
            this.internal(({ Boolean }) => ({
                for_hover: [Boolean, false],
            }));
            this.override({
                line_color: 'black',
            });
        }
    }
    exports.Span = Span;
    Span.__name__ = "Span";
    Span.init_Span();
},
/* models/annotations/toolbar_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const annotation_1 = require(40) /* ./annotation */;
    const toolbar_1 = require(235) /* ../tools/toolbar */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const dom_1 = require(43) /* ../../core/dom */;
    const side_panel_1 = require(140) /* ../../core/layout/side_panel */;
    const bbox_1 = require(99) /* ../../core/util/bbox */;
    class ToolbarPanelView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._invalidate_toolbar = true;
            this._previous_bbox = new bbox_1.BBox();
        }
        update_layout() {
            this.layout = new side_panel_1.SideLayout(this.panel, () => this.get_size(), true);
        }
        initialize() {
            super.initialize();
            this.el = dom_1.div();
            this.plot_view.canvas_view.add_event(this.el);
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this._toolbar_view = await build_views_1.build_view(this.model.toolbar, { parent: this });
            this.plot_view.visibility_callbacks.push((visible) => this._toolbar_view.set_visibility(visible));
        }
        remove() {
            this._toolbar_view.remove();
            dom_1.remove(this.el);
            super.remove();
        }
        render() {
            if (!this.model.visible)
                dom_1.undisplay(this.el);
            super.render();
        }
        _render() {
            // TODO: this should be handled by the layout
            const { bbox } = this.layout;
            if (!this._previous_bbox.equals(bbox)) {
                dom_1.position(this.el, bbox);
                this._previous_bbox = bbox;
            }
            if (this._invalidate_toolbar) {
                this.el.style.position = "absolute";
                this.el.style.overflow = "hidden";
                this._toolbar_view.render();
                dom_1.empty(this.el);
                this.el.appendChild(this._toolbar_view.el);
                this._invalidate_toolbar = false;
            }
            dom_1.display(this.el);
        }
        _get_size() {
            const { tools, logo } = this.model.toolbar;
            return {
                width: tools.length * 30 + (logo != null ? 25 : 0),
                height: 30,
            };
        }
    }
    exports.ToolbarPanelView = ToolbarPanelView;
    ToolbarPanelView.__name__ = "ToolbarPanelView";
    class ToolbarPanel extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_ToolbarPanel() {
            this.prototype.default_view = ToolbarPanelView;
            this.define(({ Ref }) => ({
                toolbar: [Ref(toolbar_1.Toolbar)],
            }));
        }
    }
    exports.ToolbarPanel = ToolbarPanel;
    ToolbarPanel.__name__ = "ToolbarPanel";
    ToolbarPanel.init_ToolbarPanel();
},
/* models/tools/toolbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../core/util/object */;
    const tool_1 = require(236) /* ./tool */;
    const gesture_tool_1 = require(237) /* ./gestures/gesture_tool */;
    const inspect_tool_1 = require(247) /* ./inspectors/inspect_tool */;
    const toolbar_base_1 = require(248) /* ./toolbar_base */;
    exports.Drag = tool_1.Tool;
    exports.Inspection = tool_1.Tool;
    exports.Scroll = tool_1.Tool;
    exports.Tap = tool_1.Tool;
    const _get_active_attr = (et) => {
        switch (et) {
            case 'tap': return 'active_tap';
            case 'pan': return 'active_drag';
            case 'pinch':
            case 'scroll': return 'active_scroll';
            case 'multi': return 'active_multi';
        }
        return null;
    };
    const _supports_auto = (et) => {
        return et == 'tap' || et == 'pan';
    };
    class Toolbar extends toolbar_base_1.ToolbarBase {
        constructor(attrs) {
            super(attrs);
        }
        static init_Toolbar() {
            this.prototype.default_view = toolbar_base_1.ToolbarBaseView;
            this.define(({ Or, Ref, Auto, Null, Nullable }) => ({
                active_drag: [Or(Ref(exports.Drag), Auto, Null), "auto"],
                active_inspect: [Or(Ref(exports.Inspection), Auto, Null), "auto"],
                active_scroll: [Or(Ref(exports.Scroll), Auto, Null), "auto"],
                active_tap: [Or(Ref(exports.Tap), Auto, Null), "auto"],
                active_multi: [Nullable(Ref(gesture_tool_1.GestureTool)), null],
            }));
        }
        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());
        }
        _init_tools() {
            super._init_tools();
            if (this.active_inspect == 'auto') {
                // do nothing as all tools are active be default
            }
            else if (this.active_inspect instanceof inspect_tool_1.InspectTool) {
                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;
                }
            }
            else if (types_1.isArray(this.active_inspect)) {
                const active_inspect = 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 (!array_1.includes(this.active_inspect, inspector))
                        inspector.active = false;
                }
            }
            else if (this.active_inspect == null) {
                for (const inspector of this.inspectors)
                    inspector.active = false;
            }
            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 object_1.values(this.gestures)) {
                gesture.tools = array_1.sort_by(gesture.tools, (tool) => tool.default_order);
                for (const tool of gesture.tools) {
                    this.connect(tool.properties.active.change, () => this._active_change(tool));
                }
            }
            for (const [et, gesture] of object_1.entries(this.gestures)) {
                const active_attr = _get_active_attr(et);
                if (active_attr) {
                    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) {
                        if (array_1.includes(this.tools, active_tool)) {
                            _activate_gesture(active_tool);
                        }
                        else {
                            this[active_attr] = null;
                        }
                    }
                }
            }
        }
    }
    exports.Toolbar = Toolbar;
    Toolbar.__name__ = "Toolbar";
    Toolbar.init_Toolbar();
},
/* models/tools/tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const view_1 = require(42) /* ../../core/view */;
    const array_1 = require(9) /* ../../core/util/array */;
    const model_1 = require(53) /* ../../model */;
    class ToolView extends view_1.View {
        get plot_view() {
            return this.parent;
        }
        get plot_model() {
            return this.parent.model;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.active.change, () => {
                if (this.model.active)
                    this.activate();
                else
                    this.deactivate();
            });
        }
        // 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);
        }
        static init_Tool() {
            this.prototype._known_aliases = new Map();
            this.define(({ String, Nullable }) => ({
                description: [Nullable(String), null],
            }));
            this.internal(({ Boolean }) => ({
                active: [Boolean, false],
            }));
        }
        get synthetic_renderers() {
            return [];
        }
        // 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 = [array_1.min([sx0, sx1]), array_1.max([sx0, sx1])];
                sxlim = [array_1.max([sxlim[0], hr.start]), 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 = [array_1.min([sy0, sy1]), array_1.max([sy0, sy1])];
                sylim = [array_1.max([sylim[0], vr.start]), array_1.min([sylim[1], vr.end])];
            }
            else
                sylim = [vr.start, vr.end];
            return [sxlim, sylim];
        }
        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;
    Tool.__name__ = "Tool";
    Tool.init_Tool();
},
/* models/tools/gestures/gesture_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const button_tool_1 = require(238) /* ../button_tool */;
    const on_off_button_1 = require(246) /* ../on_off_button */;
    class GestureToolView extends button_tool_1.ButtonToolView {
    }
    exports.GestureToolView = GestureToolView;
    GestureToolView.__name__ = "GestureToolView";
    class GestureTool extends button_tool_1.ButtonTool {
        constructor(attrs) {
            super(attrs);
            this.button_view = on_off_button_1.OnOffButtonView;
        }
    }
    exports.GestureTool = GestureTool;
    GestureTool.__name__ = "GestureTool";
},
/* models/tools/button_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const hammerjs_1 = tslib_1.__importDefault(require(239) /* hammerjs */);
    const dom_view_1 = require(240) /* ../../core/dom_view */;
    const tool_1 = require(236) /* ./tool */;
    const dom_1 = require(43) /* ../../core/dom */;
    const string_1 = require(34) /* ../../core/util/string */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(9) /* ../../core/util/array */;
    const toolbar_css_1 = tslib_1.__importStar(require(241) /* ../../styles/toolbar.css */), toolbars = toolbar_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(242) /* ../../styles/icons.css */);
    const menus_css_1 = tslib_1.__importDefault(require(243) /* ../../styles/menus.css */);
    const menus_1 = require(244) /* ../../core/util/menus */;
    class ButtonToolButtonView extends dom_view_1.DOMView {
        initialize() {
            super.initialize();
            const items = this.model.menu;
            if (items != null) {
                const location = this.parent.model.toolbar_location;
                const reverse = location == "left" || location == "above";
                const orientation = this.parent.model.horizontal ? "vertical" : "horizontal";
                this._menu = new menus_1.ContextMenu(!reverse ? items : array_1.reversed(items), {
                    orientation,
                    prevent_hide: (event) => event.target == this.el,
                });
            }
            this._hammer = new hammerjs_1.default(this.el, {
                touchAction: "auto",
                inputClass: hammerjs_1.default.TouchMouseInput,
            });
            this.connect(this.model.change, () => this.render());
            this._hammer.on("tap", (e) => {
                var _a;
                if ((_a = this._menu) === null || _a === void 0 ? void 0 : _a.is_open) {
                    this._menu.hide();
                    return;
                }
                if (e.target == this.el) {
                    this._clicked();
                }
            });
            this._hammer.on("press", () => this._pressed());
        }
        remove() {
            var _a;
            this._hammer.destroy();
            (_a = this._menu) === null || _a === void 0 ? void 0 : _a.remove();
            super.remove();
        }
        styles() {
            return [...super.styles(), toolbar_css_1.default, icons_css_1.default, menus_css_1.default];
        }
        css_classes() {
            return super.css_classes().concat(toolbars.toolbar_button);
        }
        render() {
            dom_1.empty(this.el);
            const icon = this.model.computed_icon;
            if (types_1.isString(icon)) {
                if (string_1.startsWith(icon, "data:image"))
                    this.el.style.backgroundImage = "url('" + icon + "')";
                else
                    this.el.classList.add(icon);
            }
            this.el.title = this.model.tooltip;
            if (this._menu != null) {
                this.root.el.appendChild(this._menu.el);
            }
        }
        _pressed() {
            var _a;
            const { left, top, right, bottom } = this.el.getBoundingClientRect();
            const at = (() => {
                switch (this.parent.model.toolbar_location) {
                    case "right":
                        return { right: left, top };
                    case "left":
                        return { left: right, top };
                    case "above":
                        return { left, top: bottom };
                    case "below":
                        return { left, bottom: top };
                }
            })();
            (_a = this._menu) === null || _a === void 0 ? void 0 : _a.toggle(at);
        }
    }
    exports.ButtonToolButtonView = ButtonToolButtonView;
    ButtonToolButtonView.__name__ = "ButtonToolButtonView";
    class ButtonToolView extends tool_1.ToolView {
    }
    exports.ButtonToolView = ButtonToolView;
    ButtonToolView.__name__ = "ButtonToolView";
    class ButtonTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
        }
        static init_ButtonTool() {
            this.internal(({ Boolean }) => ({
                disabled: [Boolean, false],
            }));
        }
        // 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
                return `${tool_name} (${dims == "width" ? "x" : "y"}-axis)`;
        }
        get tooltip() {
            var _a;
            return (_a = this.description) !== null && _a !== void 0 ? _a : this.tool_name;
        }
        get computed_icon() {
            return this.icon;
        }
        get menu() {
            return null;
        }
    }
    exports.ButtonTool = ButtonTool;
    ButtonTool.__name__ = "ButtonTool";
    ButtonTool.init_ButtonTool();
},
/* hammerjs/hammer.js */ function _(require, module, exports, __esModule, __esExport) {
    /*! Hammer.JS - v2.0.7 - 2016-04-22
     * http://hammerjs.github.io/
     *
     * Copyright (c) 2016 Jorik Tangelder;
     * Licensed under the MIT license */
    (function (window, document, exportName, undefined) {
        'use strict';
        var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
        var TEST_ELEMENT = document.createElement('div');
        var TYPE_FUNCTION = 'function';
        var round = Math.round;
        var abs = Math.abs;
        var now = Date.now;
        /**
         * set a timeout with a given scope
         * @param {Function} fn
         * @param {Number} timeout
         * @param {Object} context
         * @returns {number}
         */
        function setTimeoutContext(fn, timeout, context) {
            return setTimeout(bindFn(fn, context), timeout);
        }
        /**
         * if the argument is an array, we want to execute the fn on each entry
         * if it aint an array we don't want to do a thing.
         * this is used by all the methods that accept a single and array argument.
         * @param {*|Array} arg
         * @param {String} fn
         * @param {Object} [context]
         * @returns {Boolean}
         */
        function invokeArrayArg(arg, fn, context) {
            if (Array.isArray(arg)) {
                each(arg, context[fn], context);
                return true;
            }
            return false;
        }
        /**
         * walk objects and arrays
         * @param {Object} obj
         * @param {Function} iterator
         * @param {Object} context
         */
        function each(obj, iterator, context) {
            var i;
            if (!obj) {
                return;
            }
            if (obj.forEach) {
                obj.forEach(iterator, context);
            }
            else if (obj.length !== undefined) {
                i = 0;
                while (i < obj.length) {
                    iterator.call(context, obj[i], i, obj);
                    i++;
                }
            }
            else {
                for (i in obj) {
                    obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
                }
            }
        }
        /**
         * wrap a method with a deprecation warning and stack trace
         * @param {Function} method
         * @param {String} name
         * @param {String} message
         * @returns {Function} A new function wrapping the supplied method.
         */
        function deprecate(method, name, message) {
            var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
            return function () {
                var e = new Error('get-stack-trace');
                var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
                    .replace(/^\s+at\s+/gm, '')
                    .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
                var log = window.console && (window.console.warn || window.console.log);
                if (log) {
                    log.call(window.console, deprecationMessage, stack);
                }
                return method.apply(this, arguments);
            };
        }
        /**
         * extend object.
         * means that properties in dest will be overwritten by the ones in src.
         * @param {Object} target
         * @param {...Object} objects_to_assign
         * @returns {Object} target
         */
        var assign;
        if (typeof Object.assign !== 'function') {
            assign = function assign(target) {
                if (target === undefined || target === null) {
                    throw new TypeError('Cannot convert undefined or null to object');
                }
                var output = Object(target);
                for (var index = 1; index < arguments.length; index++) {
                    var source = arguments[index];
                    if (source !== undefined && source !== null) {
                        for (var nextKey in source) {
                            if (source.hasOwnProperty(nextKey)) {
                                output[nextKey] = source[nextKey];
                            }
                        }
                    }
                }
                return output;
            };
        }
        else {
            assign = Object.assign;
        }
        /**
         * extend object.
         * means that properties in dest will be overwritten by the ones in src.
         * @param {Object} dest
         * @param {Object} src
         * @param {Boolean} [merge=false]
         * @returns {Object} dest
         */
        var extend = deprecate(function extend(dest, src, merge) {
            var keys = Object.keys(src);
            var i = 0;
            while (i < keys.length) {
                if (!merge || (merge && dest[keys[i]] === undefined)) {
                    dest[keys[i]] = src[keys[i]];
                }
                i++;
            }
            return dest;
        }, 'extend', 'Use `assign`.');
        /**
         * merge the values from src in the dest.
         * means that properties that exist in dest will not be overwritten by src
         * @param {Object} dest
         * @param {Object} src
         * @returns {Object} dest
         */
        var merge = deprecate(function merge(dest, src) {
            return extend(dest, src, true);
        }, 'merge', 'Use `assign`.');
        /**
         * simple class inheritance
         * @param {Function} child
         * @param {Function} base
         * @param {Object} [properties]
         */
        function inherit(child, base, properties) {
            var baseP = base.prototype, childP;
            childP = child.prototype = Object.create(baseP);
            childP.constructor = child;
            childP._super = baseP;
            if (properties) {
                assign(childP, properties);
            }
        }
        /**
         * simple function bind
         * @param {Function} fn
         * @param {Object} context
         * @returns {Function}
         */
        function bindFn(fn, context) {
            return function boundFn() {
                return fn.apply(context, arguments);
            };
        }
        /**
         * let a boolean value also be a function that must return a boolean
         * this first item in args will be used as the context
         * @param {Boolean|Function} val
         * @param {Array} [args]
         * @returns {Boolean}
         */
        function boolOrFn(val, args) {
            if (typeof val == TYPE_FUNCTION) {
                return val.apply(args ? args[0] || undefined : undefined, args);
            }
            return val;
        }
        /**
         * use the val2 when val1 is undefined
         * @param {*} val1
         * @param {*} val2
         * @returns {*}
         */
        function ifUndefined(val1, val2) {
            return (val1 === undefined) ? val2 : val1;
        }
        /**
         * addEventListener with multiple events at once
         * @param {EventTarget} target
         * @param {String} types
         * @param {Function} handler
         */
        function addEventListeners(target, types, handler) {
            each(splitStr(types), function (type) {
                target.addEventListener(type, handler, false);
            });
        }
        /**
         * removeEventListener with multiple events at once
         * @param {EventTarget} target
         * @param {String} types
         * @param {Function} handler
         */
        function removeEventListeners(target, types, handler) {
            each(splitStr(types), function (type) {
                target.removeEventListener(type, handler, false);
            });
        }
        /**
         * find if a node is in the given parent
         * @method hasParent
         * @param {HTMLElement} node
         * @param {HTMLElement} parent
         * @return {Boolean} found
         */
        function hasParent(node, parent) {
            while (node) {
                if (node == parent) {
                    return true;
                }
                node = node.parentNode;
            }
            return false;
        }
        /**
         * small indexOf wrapper
         * @param {String} str
         * @param {String} find
         * @returns {Boolean} found
         */
        function inStr(str, find) {
            return str.indexOf(find) > -1;
        }
        /**
         * split string on whitespace
         * @param {String} str
         * @returns {Array} words
         */
        function splitStr(str) {
            return str.trim().split(/\s+/g);
        }
        /**
         * find if a array contains the object using indexOf or a simple polyFill
         * @param {Array} src
         * @param {String} find
         * @param {String} [findByKey]
         * @return {Boolean|Number} false when not found, or the index
         */
        function inArray(src, find, findByKey) {
            if (src.indexOf && !findByKey) {
                return src.indexOf(find);
            }
            else {
                var i = 0;
                while (i < src.length) {
                    if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
                        return i;
                    }
                    i++;
                }
                return -1;
            }
        }
        /**
         * convert array-like objects to real arrays
         * @param {Object} obj
         * @returns {Array}
         */
        function toArray(obj) {
            return Array.prototype.slice.call(obj, 0);
        }
        /**
         * unique array with objects based on a key (like 'id') or just by the array's value
         * @param {Array} src [{id:1},{id:2},{id:1}]
         * @param {String} [key]
         * @param {Boolean} [sort=False]
         * @returns {Array} [{id:1},{id:2}]
         */
        function uniqueArray(src, key, sort) {
            var results = [];
            var values = [];
            var i = 0;
            while (i < src.length) {
                var val = key ? src[i][key] : src[i];
                if (inArray(values, val) < 0) {
                    results.push(src[i]);
                }
                values[i] = val;
                i++;
            }
            if (sort) {
                if (!key) {
                    results = results.sort();
                }
                else {
                    results = results.sort(function sortUniqueArray(a, b) {
                        return a[key] > b[key];
                    });
                }
            }
            return results;
        }
        /**
         * get the prefixed property
         * @param {Object} obj
         * @param {String} property
         * @returns {String|Undefined} prefixed
         */
        function prefixed(obj, property) {
            var prefix, prop;
            var camelProp = property[0].toUpperCase() + property.slice(1);
            var i = 0;
            while (i < VENDOR_PREFIXES.length) {
                prefix = VENDOR_PREFIXES[i];
                prop = (prefix) ? prefix + camelProp : property;
                if (prop in obj) {
                    return prop;
                }
                i++;
            }
            return undefined;
        }
        /**
         * get a unique id
         * @returns {number} uniqueId
         */
        var _uniqueId = 1;
        function uniqueId() {
            return _uniqueId++;
        }
        /**
         * get the window object of an element
         * @param {HTMLElement} element
         * @returns {DocumentView|Window}
         */
        function getWindowForElement(element) {
            var doc = element.ownerDocument || element;
            return (doc.defaultView || doc.parentWindow || window);
        }
        var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
        var SUPPORT_TOUCH = ('ontouchstart' in window);
        var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
        var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
        var INPUT_TYPE_TOUCH = 'touch';
        var INPUT_TYPE_PEN = 'pen';
        var INPUT_TYPE_MOUSE = 'mouse';
        var INPUT_TYPE_KINECT = 'kinect';
        var COMPUTE_INTERVAL = 25;
        var INPUT_START = 1;
        var INPUT_MOVE = 2;
        var INPUT_END = 4;
        var INPUT_CANCEL = 8;
        var DIRECTION_NONE = 1;
        var DIRECTION_LEFT = 2;
        var DIRECTION_RIGHT = 4;
        var DIRECTION_UP = 8;
        var DIRECTION_DOWN = 16;
        var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
        var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
        var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
        var PROPS_XY = ['x', 'y'];
        var PROPS_CLIENT_XY = ['clientX', 'clientY'];
        /**
         * create new input type manager
         * @param {Manager} manager
         * @param {Function} callback
         * @returns {Input}
         * @constructor
         */
        function Input(manager, callback) {
            var self = this;
            this.manager = manager;
            this.callback = callback;
            this.element = manager.element;
            this.target = manager.options.inputTarget;
            // smaller wrapper around the handler, for the scope and the enabled state of the manager,
            // so when disabled the input events are completely bypassed.
            this.domHandler = function (ev) {
                if (boolOrFn(manager.options.enable, [manager])) {
                    self.handler(ev);
                }
            };
            this.init();
        }
        Input.prototype = {
            /**
             * should handle the inputEvent data and trigger the callback
             * @virtual
             */
            handler: function () { },
            /**
             * bind the events
             */
            init: function () {
                this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
                this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
                this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
            },
            /**
             * unbind the events
             */
            destroy: function () {
                this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
                this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
                this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
            }
        };
        /**
         * create new input type manager
         * called by the Manager constructor
         * @param {Hammer} manager
         * @returns {Input}
         */
        function createInputInstance(manager) {
            var Type;
            var inputClass = manager.options.inputClass;
            if (inputClass) {
                Type = inputClass;
            }
            else if (SUPPORT_POINTER_EVENTS) {
                Type = PointerEventInput;
            }
            else if (SUPPORT_ONLY_TOUCH) {
                Type = TouchInput;
            }
            else if (!SUPPORT_TOUCH) {
                Type = MouseInput;
            }
            else {
                Type = TouchMouseInput;
            }
            return new (Type)(manager, inputHandler);
        }
        /**
         * handle input events
         * @param {Manager} manager
         * @param {String} eventType
         * @param {Object} input
         */
        function inputHandler(manager, eventType, input) {
            var pointersLen = input.pointers.length;
            var changedPointersLen = input.changedPointers.length;
            var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
            var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));
            input.isFirst = !!isFirst;
            input.isFinal = !!isFinal;
            if (isFirst) {
                manager.session = {};
            }
            // source event is the normalized value of the domEvents
            // like 'touchstart, mouseup, pointerdown'
            input.eventType = eventType;
            // compute scale, rotation etc
            computeInputData(manager, input);
            // emit secret event
            manager.emit('hammer.input', input);
            manager.recognize(input);
            manager.session.prevInput = input;
        }
        /**
         * extend the data with some usable properties like scale, rotate, velocity etc
         * @param {Object} manager
         * @param {Object} input
         */
        function computeInputData(manager, input) {
            var session = manager.session;
            var pointers = input.pointers;
            var pointersLength = pointers.length;
            // store the first input to calculate the distance and direction
            if (!session.firstInput) {
                session.firstInput = simpleCloneInputData(input);
            }
            // to compute scale and rotation we need to store the multiple touches
            if (pointersLength > 1 && !session.firstMultiple) {
                session.firstMultiple = simpleCloneInputData(input);
            }
            else if (pointersLength === 1) {
                session.firstMultiple = false;
            }
            var firstInput = session.firstInput;
            var firstMultiple = session.firstMultiple;
            var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
            var center = input.center = getCenter(pointers);
            input.timeStamp = now();
            input.deltaTime = input.timeStamp - firstInput.timeStamp;
            input.angle = getAngle(offsetCenter, center);
            input.distance = getDistance(offsetCenter, center);
            computeDeltaXY(session, input);
            input.offsetDirection = getDirection(input.deltaX, input.deltaY);
            var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
            input.overallVelocityX = overallVelocity.x;
            input.overallVelocityY = overallVelocity.y;
            input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;
            input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
            input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
            input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
                session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);
            computeIntervalInputData(session, input);
            // find the correct target
            var target = manager.element;
            if (hasParent(input.srcEvent.target, target)) {
                target = input.srcEvent.target;
            }
            input.target = target;
        }
        function computeDeltaXY(session, input) {
            var center = input.center;
            var offset = session.offsetDelta || {};
            var prevDelta = session.prevDelta || {};
            var prevInput = session.prevInput || {};
            if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
                prevDelta = session.prevDelta = {
                    x: prevInput.deltaX || 0,
                    y: prevInput.deltaY || 0
                };
                offset = session.offsetDelta = {
                    x: center.x,
                    y: center.y
                };
            }
            input.deltaX = prevDelta.x + (center.x - offset.x);
            input.deltaY = prevDelta.y + (center.y - offset.y);
        }
        /**
         * velocity is calculated every x ms
         * @param {Object} session
         * @param {Object} input
         */
        function computeIntervalInputData(session, input) {
            var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction;
            if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
                var deltaX = input.deltaX - last.deltaX;
                var deltaY = input.deltaY - last.deltaY;
                var v = getVelocity(deltaTime, deltaX, deltaY);
                velocityX = v.x;
                velocityY = v.y;
                velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
                direction = getDirection(deltaX, deltaY);
                session.lastInterval = input;
            }
            else {
                // use latest velocity info if it doesn't overtake a minimum period
                velocity = last.velocity;
                velocityX = last.velocityX;
                velocityY = last.velocityY;
                direction = last.direction;
            }
            input.velocity = velocity;
            input.velocityX = velocityX;
            input.velocityY = velocityY;
            input.direction = direction;
        }
        /**
         * create a simple clone from the input used for storage of firstInput and firstMultiple
         * @param {Object} input
         * @returns {Object} clonedInputData
         */
        function simpleCloneInputData(input) {
            // make a simple copy of the pointers because we will get a reference if we don't
            // we only need clientXY for the calculations
            var pointers = [];
            var i = 0;
            while (i < input.pointers.length) {
                pointers[i] = {
                    clientX: round(input.pointers[i].clientX),
                    clientY: round(input.pointers[i].clientY)
                };
                i++;
            }
            return {
                timeStamp: now(),
                pointers: pointers,
                center: getCenter(pointers),
                deltaX: input.deltaX,
                deltaY: input.deltaY
            };
        }
        /**
         * get the center of all the pointers
         * @param {Array} pointers
         * @return {Object} center contains `x` and `y` properties
         */
        function getCenter(pointers) {
            var pointersLength = pointers.length;
            // no need to loop when only one touch
            if (pointersLength === 1) {
                return {
                    x: round(pointers[0].clientX),
                    y: round(pointers[0].clientY)
                };
            }
            var x = 0, y = 0, i = 0;
            while (i < pointersLength) {
                x += pointers[i].clientX;
                y += pointers[i].clientY;
                i++;
            }
            return {
                x: round(x / pointersLength),
                y: round(y / pointersLength)
            };
        }
        /**
         * calculate the velocity between two points. unit is in px per ms.
         * @param {Number} deltaTime
         * @param {Number} x
         * @param {Number} y
         * @return {Object} velocity `x` and `y`
         */
        function getVelocity(deltaTime, x, y) {
            return {
                x: x / deltaTime || 0,
                y: y / deltaTime || 0
            };
        }
        /**
         * get the direction between two points
         * @param {Number} x
         * @param {Number} y
         * @return {Number} direction
         */
        function getDirection(x, y) {
            if (x === y) {
                return DIRECTION_NONE;
            }
            if (abs(x) >= abs(y)) {
                return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
            }
            return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
        }
        /**
         * calculate the absolute distance between two points
         * @param {Object} p1 {x, y}
         * @param {Object} p2 {x, y}
         * @param {Array} [props] containing x and y keys
         * @return {Number} distance
         */
        function getDistance(p1, p2, props) {
            if (!props) {
                props = PROPS_XY;
            }
            var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]];
            return Math.sqrt((x * x) + (y * y));
        }
        /**
         * calculate the angle between two coordinates
         * @param {Object} p1
         * @param {Object} p2
         * @param {Array} [props] containing x and y keys
         * @return {Number} angle
         */
        function getAngle(p1, p2, props) {
            if (!props) {
                props = PROPS_XY;
            }
            var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]];
            return Math.atan2(y, x) * 180 / Math.PI;
        }
        /**
         * calculate the rotation degrees between two pointersets
         * @param {Array} start array of pointers
         * @param {Array} end array of pointers
         * @return {Number} rotation
         */
        function getRotation(start, end) {
            return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
        }
        /**
         * calculate the scale factor between two pointersets
         * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
         * @param {Array} start array of pointers
         * @param {Array} end array of pointers
         * @return {Number} scale
         */
        function getScale(start, end) {
            return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
        }
        var MOUSE_INPUT_MAP = {
            mousedown: INPUT_START,
            mousemove: INPUT_MOVE,
            mouseup: INPUT_END
        };
        var MOUSE_ELEMENT_EVENTS = 'mousedown';
        var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
        /**
         * Mouse events input
         * @constructor
         * @extends Input
         */
        function MouseInput() {
            this.evEl = MOUSE_ELEMENT_EVENTS;
            this.evWin = MOUSE_WINDOW_EVENTS;
            this.pressed = false; // mousedown state
            Input.apply(this, arguments);
        }
        inherit(MouseInput, Input, {
            /**
             * handle mouse events
             * @param {Object} ev
             */
            handler: function MEhandler(ev) {
                var eventType = MOUSE_INPUT_MAP[ev.type];
                // on start we want to have the left mouse button down
                if (eventType & INPUT_START && ev.button === 0) {
                    this.pressed = true;
                }
                if (eventType & INPUT_MOVE && ev.which !== 1) {
                    eventType = INPUT_END;
                }
                // mouse must be down
                if (!this.pressed) {
                    return;
                }
                if (eventType & INPUT_END) {
                    this.pressed = false;
                }
                this.callback(this.manager, eventType, {
                    pointers: [ev],
                    changedPointers: [ev],
                    pointerType: INPUT_TYPE_MOUSE,
                    srcEvent: ev
                });
            }
        });
        var POINTER_INPUT_MAP = {
            pointerdown: INPUT_START,
            pointermove: INPUT_MOVE,
            pointerup: INPUT_END,
            pointercancel: INPUT_CANCEL,
            pointerout: INPUT_CANCEL
        };
        // in IE10 the pointer types is defined as an enum
        var IE10_POINTER_TYPE_ENUM = {
            2: INPUT_TYPE_TOUCH,
            3: INPUT_TYPE_PEN,
            4: INPUT_TYPE_MOUSE,
            5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
        };
        var POINTER_ELEMENT_EVENTS = 'pointerdown';
        var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
        // IE10 has prefixed support, and case-sensitive
        if (window.MSPointerEvent && !window.PointerEvent) {
            POINTER_ELEMENT_EVENTS = 'MSPointerDown';
            POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
        }
        /**
         * Pointer events input
         * @constructor
         * @extends Input
         */
        function PointerEventInput() {
            this.evEl = POINTER_ELEMENT_EVENTS;
            this.evWin = POINTER_WINDOW_EVENTS;
            Input.apply(this, arguments);
            this.store = (this.manager.session.pointerEvents = []);
        }
        inherit(PointerEventInput, Input, {
            /**
             * handle mouse events
             * @param {Object} ev
             */
            handler: function PEhandler(ev) {
                var store = this.store;
                var removePointer = false;
                var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
                var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
                var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
                var isTouch = (pointerType == INPUT_TYPE_TOUCH);
                // get index of the event in the store
                var storeIndex = inArray(store, ev.pointerId, 'pointerId');
                // start and mouse must be down
                if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
                    if (storeIndex < 0) {
                        store.push(ev);
                        storeIndex = store.length - 1;
                    }
                }
                else if (eventType & (INPUT_END | INPUT_CANCEL)) {
                    removePointer = true;
                }
                // it not found, so the pointer hasn't been down (so it's probably a hover)
                if (storeIndex < 0) {
                    return;
                }
                // update the event in the store
                store[storeIndex] = ev;
                this.callback(this.manager, eventType, {
                    pointers: store,
                    changedPointers: [ev],
                    pointerType: pointerType,
                    srcEvent: ev
                });
                if (removePointer) {
                    // remove from the store
                    store.splice(storeIndex, 1);
                }
            }
        });
        var SINGLE_TOUCH_INPUT_MAP = {
            touchstart: INPUT_START,
            touchmove: INPUT_MOVE,
            touchend: INPUT_END,
            touchcancel: INPUT_CANCEL
        };
        var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
        var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
        /**
         * Touch events input
         * @constructor
         * @extends Input
         */
        function SingleTouchInput() {
            this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
            this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
            this.started = false;
            Input.apply(this, arguments);
        }
        inherit(SingleTouchInput, Input, {
            handler: function TEhandler(ev) {
                var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
                // should we handle the touch events?
                if (type === INPUT_START) {
                    this.started = true;
                }
                if (!this.started) {
                    return;
                }
                var touches = normalizeSingleTouches.call(this, ev, type);
                // when done, reset the started state
                if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
                    this.started = false;
                }
                this.callback(this.manager, type, {
                    pointers: touches[0],
                    changedPointers: touches[1],
                    pointerType: INPUT_TYPE_TOUCH,
                    srcEvent: ev
                });
            }
        });
        /**
         * @this {TouchInput}
         * @param {Object} ev
         * @param {Number} type flag
         * @returns {undefined|Array} [all, changed]
         */
        function normalizeSingleTouches(ev, type) {
            var all = toArray(ev.touches);
            var changed = toArray(ev.changedTouches);
            if (type & (INPUT_END | INPUT_CANCEL)) {
                all = uniqueArray(all.concat(changed), 'identifier', true);
            }
            return [all, changed];
        }
        var TOUCH_INPUT_MAP = {
            touchstart: INPUT_START,
            touchmove: INPUT_MOVE,
            touchend: INPUT_END,
            touchcancel: INPUT_CANCEL
        };
        var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
        /**
         * Multi-user touch events input
         * @constructor
         * @extends Input
         */
        function TouchInput() {
            this.evTarget = TOUCH_TARGET_EVENTS;
            this.targetIds = {};
            Input.apply(this, arguments);
        }
        inherit(TouchInput, Input, {
            handler: function MTEhandler(ev) {
                var type = TOUCH_INPUT_MAP[ev.type];
                var touches = getTouches.call(this, ev, type);
                if (!touches) {
                    return;
                }
                this.callback(this.manager, type, {
                    pointers: touches[0],
                    changedPointers: touches[1],
                    pointerType: INPUT_TYPE_TOUCH,
                    srcEvent: ev
                });
            }
        });
        /**
         * @this {TouchInput}
         * @param {Object} ev
         * @param {Number} type flag
         * @returns {undefined|Array} [all, changed]
         */
        function getTouches(ev, type) {
            var allTouches = toArray(ev.touches);
            var targetIds = this.targetIds;
            // when there is only one touch, the process can be simplified
            if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
                targetIds[allTouches[0].identifier] = true;
                return [allTouches, allTouches];
            }
            var i, targetTouches, changedTouches = toArray(ev.changedTouches), changedTargetTouches = [], target = this.target;
            // get target touches from touches
            targetTouches = allTouches.filter(function (touch) {
                return hasParent(touch.target, target);
            });
            // collect touches
            if (type === INPUT_START) {
                i = 0;
                while (i < targetTouches.length) {
                    targetIds[targetTouches[i].identifier] = true;
                    i++;
                }
            }
            // filter changed touches to only contain touches that exist in the collected target ids
            i = 0;
            while (i < changedTouches.length) {
                if (targetIds[changedTouches[i].identifier]) {
                    changedTargetTouches.push(changedTouches[i]);
                }
                // cleanup removed touches
                if (type & (INPUT_END | INPUT_CANCEL)) {
                    delete targetIds[changedTouches[i].identifier];
                }
                i++;
            }
            if (!changedTargetTouches.length) {
                return;
            }
            return [
                // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
                uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
                changedTargetTouches
            ];
        }
        /**
         * Combined touch and mouse input
         *
         * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
         * This because touch devices also emit mouse events while doing a touch.
         *
         * @constructor
         * @extends Input
         */
        var DEDUP_TIMEOUT = 2500;
        var DEDUP_DISTANCE = 25;
        function TouchMouseInput() {
            Input.apply(this, arguments);
            var handler = bindFn(this.handler, this);
            this.touch = new TouchInput(this.manager, handler);
            this.mouse = new MouseInput(this.manager, handler);
            this.primaryTouch = null;
            this.lastTouches = [];
        }
        inherit(TouchMouseInput, Input, {
            /**
             * handle mouse and touch events
             * @param {Hammer} manager
             * @param {String} inputEvent
             * @param {Object} inputData
             */
            handler: function TMEhandler(manager, inputEvent, inputData) {
                var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
                if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
                    return;
                }
                // when we're in a touch event, record touches to  de-dupe synthetic mouse event
                if (isTouch) {
                    recordTouches.call(this, inputEvent, inputData);
                }
                else if (isMouse && isSyntheticEvent.call(this, inputData)) {
                    return;
                }
                this.callback(manager, inputEvent, inputData);
            },
            /**
             * remove the event listeners
             */
            destroy: function destroy() {
                this.touch.destroy();
                this.mouse.destroy();
            }
        });
        function recordTouches(eventType, eventData) {
            if (eventType & INPUT_START) {
                this.primaryTouch = eventData.changedPointers[0].identifier;
                setLastTouch.call(this, eventData);
            }
            else if (eventType & (INPUT_END | INPUT_CANCEL)) {
                setLastTouch.call(this, eventData);
            }
        }
        function setLastTouch(eventData) {
            var touch = eventData.changedPointers[0];
            if (touch.identifier === this.primaryTouch) {
                var lastTouch = { x: touch.clientX, y: touch.clientY };
                this.lastTouches.push(lastTouch);
                var lts = this.lastTouches;
                var removeLastTouch = function () {
                    var i = lts.indexOf(lastTouch);
                    if (i > -1) {
                        lts.splice(i, 1);
                    }
                };
                setTimeout(removeLastTouch, DEDUP_TIMEOUT);
            }
        }
        function isSyntheticEvent(eventData) {
            var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;
            for (var i = 0; i < this.lastTouches.length; i++) {
                var t = this.lastTouches[i];
                var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
                if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
                    return true;
                }
            }
            return false;
        }
        var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
        var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
        // magical touchAction value
        var TOUCH_ACTION_COMPUTE = 'compute';
        var TOUCH_ACTION_AUTO = 'auto';
        var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
        var TOUCH_ACTION_NONE = 'none';
        var TOUCH_ACTION_PAN_X = 'pan-x';
        var TOUCH_ACTION_PAN_Y = 'pan-y';
        var TOUCH_ACTION_MAP = getTouchActionProps();
        /**
         * Touch Action
         * sets the touchAction property or uses the js alternative
         * @param {Manager} manager
         * @param {String} value
         * @constructor
         */
        function TouchAction(manager, value) {
            this.manager = manager;
            this.set(value);
        }
        TouchAction.prototype = {
            /**
             * set the touchAction value on the element or enable the polyfill
             * @param {String} value
             */
            set: function (value) {
                // find out the touch-action by the event handlers
                if (value == TOUCH_ACTION_COMPUTE) {
                    value = this.compute();
                }
                if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
                    this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
                }
                this.actions = value.toLowerCase().trim();
            },
            /**
             * just re-set the touchAction value
             */
            update: function () {
                this.set(this.manager.options.touchAction);
            },
            /**
             * compute the value for the touchAction property based on the recognizer's settings
             * @returns {String} value
             */
            compute: function () {
                var actions = [];
                each(this.manager.recognizers, function (recognizer) {
                    if (boolOrFn(recognizer.options.enable, [recognizer])) {
                        actions = actions.concat(recognizer.getTouchAction());
                    }
                });
                return cleanTouchActions(actions.join(' '));
            },
            /**
             * this method is called on each input cycle and provides the preventing of the browser behavior
             * @param {Object} input
             */
            preventDefaults: function (input) {
                var srcEvent = input.srcEvent;
                var direction = input.offsetDirection;
                // if the touch action did prevented once this session
                if (this.manager.session.prevented) {
                    srcEvent.preventDefault();
                    return;
                }
                var actions = this.actions;
                var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
                var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
                var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
                if (hasNone) {
                    //do not prevent defaults if this is a tap gesture
                    var isTapPointer = input.pointers.length === 1;
                    var isTapMovement = input.distance < 2;
                    var isTapTouchTime = input.deltaTime < 250;
                    if (isTapPointer && isTapMovement && isTapTouchTime) {
                        return;
                    }
                }
                if (hasPanX && hasPanY) {
                    // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
                    return;
                }
                if (hasNone ||
                    (hasPanY && direction & DIRECTION_HORIZONTAL) ||
                    (hasPanX && direction & DIRECTION_VERTICAL)) {
                    return this.preventSrc(srcEvent);
                }
            },
            /**
             * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
             * @param {Object} srcEvent
             */
            preventSrc: function (srcEvent) {
                this.manager.session.prevented = true;
                srcEvent.preventDefault();
            }
        };
        /**
         * when the touchActions are collected they are not a valid value, so we need to clean things up. *
         * @param {String} actions
         * @returns {*}
         */
        function cleanTouchActions(actions) {
            // none
            if (inStr(actions, TOUCH_ACTION_NONE)) {
                return TOUCH_ACTION_NONE;
            }
            var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
            var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
            // if both pan-x and pan-y are set (different recognizers
            // for different directions, e.g. horizontal pan but vertical swipe?)
            // we need none (as otherwise with pan-x pan-y combined none of these
            // recognizers will work, since the browser would handle all panning
            if (hasPanX && hasPanY) {
                return TOUCH_ACTION_NONE;
            }
            // pan-x OR pan-y
            if (hasPanX || hasPanY) {
                return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
            }
            // manipulation
            if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
                return TOUCH_ACTION_MANIPULATION;
            }
            return TOUCH_ACTION_AUTO;
        }
        function getTouchActionProps() {
            if (!NATIVE_TOUCH_ACTION) {
                return false;
            }
            var touchMap = {};
            var cssSupports = window.CSS && window.CSS.supports;
            ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function (val) {
                // If css.supports is not supported but there is native touch-action assume it supports
                // all values. This is the case for IE 10 and 11.
                touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
            });
            return touchMap;
        }
        /**
         * Recognizer flow explained; *
         * All recognizers have the initial state of POSSIBLE when a input session starts.
         * The definition of a input session is from the first input until the last input, with all it's movement in it. *
         * Example session for mouse-input: mousedown -> mousemove -> mouseup
         *
         * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
         * which determines with state it should be.
         *
         * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
         * POSSIBLE to give it another change on the next cycle.
         *
         *               Possible
         *                  |
         *            +-----+---------------+
         *            |                     |
         *      +-----+-----+               |
         *      |           |               |
         *   Failed      Cancelled          |
         *                          +-------+------+
         *                          |              |
         *                      Recognized       Began
         *                                         |
         *                                      Changed
         *                                         |
         *                                  Ended/Recognized
         */
        var STATE_POSSIBLE = 1;
        var STATE_BEGAN = 2;
        var STATE_CHANGED = 4;
        var STATE_ENDED = 8;
        var STATE_RECOGNIZED = STATE_ENDED;
        var STATE_CANCELLED = 16;
        var STATE_FAILED = 32;
        /**
         * Recognizer
         * Every recognizer needs to extend from this class.
         * @constructor
         * @param {Object} options
         */
        function Recognizer(options) {
            this.options = assign({}, this.defaults, options || {});
            this.id = uniqueId();
            this.manager = null;
            // default is enable true
            this.options.enable = ifUndefined(this.options.enable, true);
            this.state = STATE_POSSIBLE;
            this.simultaneous = {};
            this.requireFail = [];
        }
        Recognizer.prototype = {
            /**
             * @virtual
             * @type {Object}
             */
            defaults: {},
            /**
             * set options
             * @param {Object} options
             * @return {Recognizer}
             */
            set: function (options) {
                assign(this.options, options);
                // also update the touchAction, in case something changed about the directions/enabled state
                this.manager && this.manager.touchAction.update();
                return this;
            },
            /**
             * recognize simultaneous with an other recognizer.
             * @param {Recognizer} otherRecognizer
             * @returns {Recognizer} this
             */
            recognizeWith: function (otherRecognizer) {
                if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
                    return this;
                }
                var simultaneous = this.simultaneous;
                otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
                if (!simultaneous[otherRecognizer.id]) {
                    simultaneous[otherRecognizer.id] = otherRecognizer;
                    otherRecognizer.recognizeWith(this);
                }
                return this;
            },
            /**
             * drop the simultaneous link. it doesnt remove the link on the other recognizer.
             * @param {Recognizer} otherRecognizer
             * @returns {Recognizer} this
             */
            dropRecognizeWith: function (otherRecognizer) {
                if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
                    return this;
                }
                otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
                delete this.simultaneous[otherRecognizer.id];
                return this;
            },
            /**
             * recognizer can only run when an other is failing
             * @param {Recognizer} otherRecognizer
             * @returns {Recognizer} this
             */
            requireFailure: function (otherRecognizer) {
                if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
                    return this;
                }
                var requireFail = this.requireFail;
                otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
                if (inArray(requireFail, otherRecognizer) === -1) {
                    requireFail.push(otherRecognizer);
                    otherRecognizer.requireFailure(this);
                }
                return this;
            },
            /**
             * drop the requireFailure link. it does not remove the link on the other recognizer.
             * @param {Recognizer} otherRecognizer
             * @returns {Recognizer} this
             */
            dropRequireFailure: function (otherRecognizer) {
                if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
                    return this;
                }
                otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
                var index = inArray(this.requireFail, otherRecognizer);
                if (index > -1) {
                    this.requireFail.splice(index, 1);
                }
                return this;
            },
            /**
             * has require failures boolean
             * @returns {boolean}
             */
            hasRequireFailures: function () {
                return this.requireFail.length > 0;
            },
            /**
             * if the recognizer can recognize simultaneous with an other recognizer
             * @param {Recognizer} otherRecognizer
             * @returns {Boolean}
             */
            canRecognizeWith: function (otherRecognizer) {
                return !!this.simultaneous[otherRecognizer.id];
            },
            /**
             * You should use `tryEmit` instead of `emit` directly to check
             * that all the needed recognizers has failed before emitting.
             * @param {Object} input
             */
            emit: function (input) {
                var self = this;
                var state = this.state;
                function emit(event) {
                    self.manager.emit(event, input);
                }
                // 'panstart' and 'panmove'
                if (state < STATE_ENDED) {
                    emit(self.options.event + stateStr(state));
                }
                emit(self.options.event); // simple 'eventName' events
                if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
                    emit(input.additionalEvent);
                }
                // panend and pancancel
                if (state >= STATE_ENDED) {
                    emit(self.options.event + stateStr(state));
                }
            },
            /**
             * Check that all the require failure recognizers has failed,
             * if true, it emits a gesture event,
             * otherwise, setup the state to FAILED.
             * @param {Object} input
             */
            tryEmit: function (input) {
                if (this.canEmit()) {
                    return this.emit(input);
                }
                // it's failing anyway
                this.state = STATE_FAILED;
            },
            /**
             * can we emit?
             * @returns {boolean}
             */
            canEmit: function () {
                var i = 0;
                while (i < this.requireFail.length) {
                    if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
                        return false;
                    }
                    i++;
                }
                return true;
            },
            /**
             * update the recognizer
             * @param {Object} inputData
             */
            recognize: function (inputData) {
                // make a new copy of the inputData
                // so we can change the inputData without messing up the other recognizers
                var inputDataClone = assign({}, inputData);
                // is is enabled and allow recognizing?
                if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
                    this.reset();
                    this.state = STATE_FAILED;
                    return;
                }
                // reset when we've reached the end
                if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
                    this.state = STATE_POSSIBLE;
                }
                this.state = this.process(inputDataClone);
                // the recognizer has recognized a gesture
                // so trigger an event
                if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
                    this.tryEmit(inputDataClone);
                }
            },
            /**
             * return the state of the recognizer
             * the actual recognizing happens in this method
             * @virtual
             * @param {Object} inputData
             * @returns {Const} STATE
             */
            process: function (inputData) { },
            /**
             * return the preferred touch-action
             * @virtual
             * @returns {Array}
             */
            getTouchAction: function () { },
            /**
             * called when the gesture isn't allowed to recognize
             * like when another is being recognized or it is disabled
             * @virtual
             */
            reset: function () { }
        };
        /**
         * get a usable string, used as event postfix
         * @param {Const} state
         * @returns {String} state
         */
        function stateStr(state) {
            if (state & STATE_CANCELLED) {
                return 'cancel';
            }
            else if (state & STATE_ENDED) {
                return 'end';
            }
            else if (state & STATE_CHANGED) {
                return 'move';
            }
            else if (state & STATE_BEGAN) {
                return 'start';
            }
            return '';
        }
        /**
         * direction cons to string
         * @param {Const} direction
         * @returns {String}
         */
        function directionStr(direction) {
            if (direction == DIRECTION_DOWN) {
                return 'down';
            }
            else if (direction == DIRECTION_UP) {
                return 'up';
            }
            else if (direction == DIRECTION_LEFT) {
                return 'left';
            }
            else if (direction == DIRECTION_RIGHT) {
                return 'right';
            }
            return '';
        }
        /**
         * get a recognizer by name if it is bound to a manager
         * @param {Recognizer|String} otherRecognizer
         * @param {Recognizer} recognizer
         * @returns {Recognizer}
         */
        function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
            var manager = recognizer.manager;
            if (manager) {
                return manager.get(otherRecognizer);
            }
            return otherRecognizer;
        }
        /**
         * This recognizer is just used as a base for the simple attribute recognizers.
         * @constructor
         * @extends Recognizer
         */
        function AttrRecognizer() {
            Recognizer.apply(this, arguments);
        }
        inherit(AttrRecognizer, Recognizer, {
            /**
             * @namespace
             * @memberof AttrRecognizer
             */
            defaults: {
                /**
                 * @type {Number}
                 * @default 1
                 */
                pointers: 1
            },
            /**
             * Used to check if it the recognizer receives valid input, like input.distance > 10.
             * @memberof AttrRecognizer
             * @param {Object} input
             * @returns {Boolean} recognized
             */
            attrTest: function (input) {
                var optionPointers = this.options.pointers;
                return optionPointers === 0 || input.pointers.length === optionPointers;
            },
            /**
             * Process the input and return the state for the recognizer
             * @memberof AttrRecognizer
             * @param {Object} input
             * @returns {*} State
             */
            process: function (input) {
                var state = this.state;
                var eventType = input.eventType;
                var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
                var isValid = this.attrTest(input);
                // on cancel input and we've recognized before, return STATE_CANCELLED
                if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
                    return state | STATE_CANCELLED;
                }
                else if (isRecognized || isValid) {
                    if (eventType & INPUT_END) {
                        return state | STATE_ENDED;
                    }
                    else if (!(state & STATE_BEGAN)) {
                        return STATE_BEGAN;
                    }
                    return state | STATE_CHANGED;
                }
                return STATE_FAILED;
            }
        });
        /**
         * Pan
         * Recognized when the pointer is down and moved in the allowed direction.
         * @constructor
         * @extends AttrRecognizer
         */
        function PanRecognizer() {
            AttrRecognizer.apply(this, arguments);
            this.pX = null;
            this.pY = null;
        }
        inherit(PanRecognizer, AttrRecognizer, {
            /**
             * @namespace
             * @memberof PanRecognizer
             */
            defaults: {
                event: 'pan',
                threshold: 10,
                pointers: 1,
                direction: DIRECTION_ALL
            },
            getTouchAction: function () {
                var direction = this.options.direction;
                var actions = [];
                if (direction & DIRECTION_HORIZONTAL) {
                    actions.push(TOUCH_ACTION_PAN_Y);
                }
                if (direction & DIRECTION_VERTICAL) {
                    actions.push(TOUCH_ACTION_PAN_X);
                }
                return actions;
            },
            directionTest: function (input) {
                var options = this.options;
                var hasMoved = true;
                var distance = input.distance;
                var direction = input.direction;
                var x = input.deltaX;
                var y = input.deltaY;
                // lock to axis?
                if (!(direction & options.direction)) {
                    if (options.direction & DIRECTION_HORIZONTAL) {
                        direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
                        hasMoved = x != this.pX;
                        distance = Math.abs(input.deltaX);
                    }
                    else {
                        direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
                        hasMoved = y != this.pY;
                        distance = Math.abs(input.deltaY);
                    }
                }
                input.direction = direction;
                return hasMoved && distance > options.threshold && direction & options.direction;
            },
            attrTest: function (input) {
                return AttrRecognizer.prototype.attrTest.call(this, input) &&
                    (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
            },
            emit: function (input) {
                this.pX = input.deltaX;
                this.pY = input.deltaY;
                var direction = directionStr(input.direction);
                if (direction) {
                    input.additionalEvent = this.options.event + direction;
                }
                this._super.emit.call(this, input);
            }
        });
        /**
         * Pinch
         * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
         * @constructor
         * @extends AttrRecognizer
         */
        function PinchRecognizer() {
            AttrRecognizer.apply(this, arguments);
        }
        inherit(PinchRecognizer, AttrRecognizer, {
            /**
             * @namespace
             * @memberof PinchRecognizer
             */
            defaults: {
                event: 'pinch',
                threshold: 0,
                pointers: 2
            },
            getTouchAction: function () {
                return [TOUCH_ACTION_NONE];
            },
            attrTest: function (input) {
                return this._super.attrTest.call(this, input) &&
                    (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
            },
            emit: function (input) {
                if (input.scale !== 1) {
                    var inOut = input.scale < 1 ? 'in' : 'out';
                    input.additionalEvent = this.options.event + inOut;
                }
                this._super.emit.call(this, input);
            }
        });
        /**
         * Press
         * Recognized when the pointer is down for x ms without any movement.
         * @constructor
         * @extends Recognizer
         */
        function PressRecognizer() {
            Recognizer.apply(this, arguments);
            this._timer = null;
            this._input = null;
        }
        inherit(PressRecognizer, Recognizer, {
            /**
             * @namespace
             * @memberof PressRecognizer
             */
            defaults: {
                event: 'press',
                pointers: 1,
                time: 251,
                threshold: 9 // a minimal movement is ok, but keep it low
            },
            getTouchAction: function () {
                return [TOUCH_ACTION_AUTO];
            },
            process: function (input) {
                var options = this.options;
                var validPointers = input.pointers.length === options.pointers;
                var validMovement = input.distance < options.threshold;
                var validTime = input.deltaTime > options.time;
                this._input = input;
                // we only allow little movement
                // and we've reached an end event, so a tap is possible
                if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
                    this.reset();
                }
                else if (input.eventType & INPUT_START) {
                    this.reset();
                    this._timer = setTimeoutContext(function () {
                        this.state = STATE_RECOGNIZED;
                        this.tryEmit();
                    }, options.time, this);
                }
                else if (input.eventType & INPUT_END) {
                    return STATE_RECOGNIZED;
                }
                return STATE_FAILED;
            },
            reset: function () {
                clearTimeout(this._timer);
            },
            emit: function (input) {
                if (this.state !== STATE_RECOGNIZED) {
                    return;
                }
                if (input && (input.eventType & INPUT_END)) {
                    this.manager.emit(this.options.event + 'up', input);
                }
                else {
                    this._input.timeStamp = now();
                    this.manager.emit(this.options.event, this._input);
                }
            }
        });
        /**
         * Rotate
         * Recognized when two or more pointer are moving in a circular motion.
         * @constructor
         * @extends AttrRecognizer
         */
        function RotateRecognizer() {
            AttrRecognizer.apply(this, arguments);
        }
        inherit(RotateRecognizer, AttrRecognizer, {
            /**
             * @namespace
             * @memberof RotateRecognizer
             */
            defaults: {
                event: 'rotate',
                threshold: 0,
                pointers: 2
            },
            getTouchAction: function () {
                return [TOUCH_ACTION_NONE];
            },
            attrTest: function (input) {
                return this._super.attrTest.call(this, input) &&
                    (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
            }
        });
        /**
         * Swipe
         * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
         * @constructor
         * @extends AttrRecognizer
         */
        function SwipeRecognizer() {
            AttrRecognizer.apply(this, arguments);
        }
        inherit(SwipeRecognizer, AttrRecognizer, {
            /**
             * @namespace
             * @memberof SwipeRecognizer
             */
            defaults: {
                event: 'swipe',
                threshold: 10,
                velocity: 0.3,
                direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
                pointers: 1
            },
            getTouchAction: function () {
                return PanRecognizer.prototype.getTouchAction.call(this);
            },
            attrTest: function (input) {
                var direction = this.options.direction;
                var velocity;
                if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
                    velocity = input.overallVelocity;
                }
                else if (direction & DIRECTION_HORIZONTAL) {
                    velocity = input.overallVelocityX;
                }
                else if (direction & DIRECTION_VERTICAL) {
                    velocity = input.overallVelocityY;
                }
                return this._super.attrTest.call(this, input) &&
                    direction & input.offsetDirection &&
                    input.distance > this.options.threshold &&
                    input.maxPointers == this.options.pointers &&
                    abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
            },
            emit: function (input) {
                var direction = directionStr(input.offsetDirection);
                if (direction) {
                    this.manager.emit(this.options.event + direction, input);
                }
                this.manager.emit(this.options.event, input);
            }
        });
        /**
         * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
         * between the given interval and position. The delay option can be used to recognize multi-taps without firing
         * a single tap.
         *
         * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
         * multi-taps being recognized.
         * @constructor
         * @extends Recognizer
         */
        function TapRecognizer() {
            Recognizer.apply(this, arguments);
            // previous time and center,
            // used for tap counting
            this.pTime = false;
            this.pCenter = false;
            this._timer = null;
            this._input = null;
            this.count = 0;
        }
        inherit(TapRecognizer, Recognizer, {
            /**
             * @namespace
             * @memberof PinchRecognizer
             */
            defaults: {
                event: 'tap',
                pointers: 1,
                taps: 1,
                interval: 300,
                time: 250,
                threshold: 9,
                posThreshold: 10 // a multi-tap can be a bit off the initial position
            },
            getTouchAction: function () {
                return [TOUCH_ACTION_MANIPULATION];
            },
            process: function (input) {
                var options = this.options;
                var validPointers = input.pointers.length === options.pointers;
                var validMovement = input.distance < options.threshold;
                var validTouchTime = input.deltaTime < options.time;
                this.reset();
                if ((input.eventType & INPUT_START) && (this.count === 0)) {
                    return this.failTimeout();
                }
                // we only allow little movement
                // and we've reached an end event, so a tap is possible
                if (validMovement && validTouchTime && validPointers) {
                    if (input.eventType != INPUT_END) {
                        return this.failTimeout();
                    }
                    var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
                    var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
                    this.pTime = input.timeStamp;
                    this.pCenter = input.center;
                    if (!validMultiTap || !validInterval) {
                        this.count = 1;
                    }
                    else {
                        this.count += 1;
                    }
                    this._input = input;
                    // if tap count matches we have recognized it,
                    // else it has began recognizing...
                    var tapCount = this.count % options.taps;
                    if (tapCount === 0) {
                        // no failing requirements, immediately trigger the tap event
                        // or wait as long as the multitap interval to trigger
                        if (!this.hasRequireFailures()) {
                            return STATE_RECOGNIZED;
                        }
                        else {
                            this._timer = setTimeoutContext(function () {
                                this.state = STATE_RECOGNIZED;
                                this.tryEmit();
                            }, options.interval, this);
                            return STATE_BEGAN;
                        }
                    }
                }
                return STATE_FAILED;
            },
            failTimeout: function () {
                this._timer = setTimeoutContext(function () {
                    this.state = STATE_FAILED;
                }, this.options.interval, this);
                return STATE_FAILED;
            },
            reset: function () {
                clearTimeout(this._timer);
            },
            emit: function () {
                if (this.state == STATE_RECOGNIZED) {
                    this._input.tapCount = this.count;
                    this.manager.emit(this.options.event, this._input);
                }
            }
        });
        /**
         * Simple way to create a manager with a default set of recognizers.
         * @param {HTMLElement} element
         * @param {Object} [options]
         * @constructor
         */
        function Hammer(element, options) {
            options = options || {};
            options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
            return new Manager(element, options);
        }
        /**
         * @const {string}
         */
        Hammer.VERSION = '2.0.7';
        /**
         * default settings
         * @namespace
         */
        Hammer.defaults = {
            /**
             * set if DOM events are being triggered.
             * But this is slower and unused by simple implementations, so disabled by default.
             * @type {Boolean}
             * @default false
             */
            domEvents: false,
            /**
             * The value for the touchAction property/fallback.
             * When set to `compute` it will magically set the correct value based on the added recognizers.
             * @type {String}
             * @default compute
             */
            touchAction: TOUCH_ACTION_COMPUTE,
            /**
             * @type {Boolean}
             * @default true
             */
            enable: true,
            /**
             * EXPERIMENTAL FEATURE -- can be removed/changed
             * Change the parent input target element.
             * If Null, then it is being set the to main element.
             * @type {Null|EventTarget}
             * @default null
             */
            inputTarget: null,
            /**
             * force an input class
             * @type {Null|Function}
             * @default null
             */
            inputClass: null,
            /**
             * Default recognizer setup when calling `Hammer()`
             * When creating a new Manager these will be skipped.
             * @type {Array}
             */
            preset: [
                // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
                [RotateRecognizer, { enable: false }],
                [PinchRecognizer, { enable: false }, ['rotate']],
                [SwipeRecognizer, { direction: DIRECTION_HORIZONTAL }],
                [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']],
                [TapRecognizer],
                [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']],
                [PressRecognizer]
            ],
            /**
             * Some CSS properties can be used to improve the working of Hammer.
             * Add them to this method and they will be set when creating a new Manager.
             * @namespace
             */
            cssProps: {
                /**
                 * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
                 * @type {String}
                 * @default 'none'
                 */
                userSelect: 'none',
                /**
                 * Disable the Windows Phone grippers when pressing an element.
                 * @type {String}
                 * @default 'none'
                 */
                touchSelect: 'none',
                /**
                 * Disables the default callout shown when you touch and hold a touch target.
                 * On iOS, when you touch and hold a touch target such as a link, Safari displays
                 * a callout containing information about the link. This property allows you to disable that callout.
                 * @type {String}
                 * @default 'none'
                 */
                touchCallout: 'none',
                /**
                 * Specifies whether zooming is enabled. Used by IE10>
                 * @type {String}
                 * @default 'none'
                 */
                contentZooming: 'none',
                /**
                 * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
                 * @type {String}
                 * @default 'none'
                 */
                userDrag: 'none',
                /**
                 * Overrides the highlight color shown when the user taps a link or a JavaScript
                 * clickable element in iOS. This property obeys the alpha value, if specified.
                 * @type {String}
                 * @default 'rgba(0,0,0,0)'
                 */
                tapHighlightColor: 'rgba(0,0,0,0)'
            }
        };
        var STOP = 1;
        var FORCED_STOP = 2;
        /**
         * Manager
         * @param {HTMLElement} element
         * @param {Object} [options]
         * @constructor
         */
        function Manager(element, options) {
            this.options = assign({}, Hammer.defaults, options || {});
            this.options.inputTarget = this.options.inputTarget || element;
            this.handlers = {};
            this.session = {};
            this.recognizers = [];
            this.oldCssProps = {};
            this.element = element;
            this.input = createInputInstance(this);
            this.touchAction = new TouchAction(this, this.options.touchAction);
            toggleCssProps(this, true);
            each(this.options.recognizers, function (item) {
                var recognizer = this.add(new (item[0])(item[1]));
                item[2] && recognizer.recognizeWith(item[2]);
                item[3] && recognizer.requireFailure(item[3]);
            }, this);
        }
        Manager.prototype = {
            /**
             * set options
             * @param {Object} options
             * @returns {Manager}
             */
            set: function (options) {
                assign(this.options, options);
                // Options that need a little more setup
                if (options.touchAction) {
                    this.touchAction.update();
                }
                if (options.inputTarget) {
                    // Clean up existing event listeners and reinitialize
                    this.input.destroy();
                    this.input.target = options.inputTarget;
                    this.input.init();
                }
                return this;
            },
            /**
             * stop recognizing for this session.
             * This session will be discarded, when a new [input]start event is fired.
             * When forced, the recognizer cycle is stopped immediately.
             * @param {Boolean} [force]
             */
            stop: function (force) {
                this.session.stopped = force ? FORCED_STOP : STOP;
            },
            /**
             * run the recognizers!
             * called by the inputHandler function on every movement of the pointers (touches)
             * it walks through all the recognizers and tries to detect the gesture that is being made
             * @param {Object} inputData
             */
            recognize: function (inputData) {
                var session = this.session;
                if (session.stopped) {
                    return;
                }
                // run the touch-action polyfill
                this.touchAction.preventDefaults(inputData);
                var recognizer;
                var recognizers = this.recognizers;
                // this holds the recognizer that is being recognized.
                // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
                // if no recognizer is detecting a thing, it is set to `null`
                var curRecognizer = session.curRecognizer;
                // reset when the last recognizer is recognized
                // or when we're in a new session
                if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
                    curRecognizer = session.curRecognizer = null;
                }
                var i = 0;
                while (i < recognizers.length) {
                    recognizer = recognizers[i];
                    // find out if we are allowed try to recognize the input for this one.
                    // 1.   allow if the session is NOT forced stopped (see the .stop() method)
                    // 2.   allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
                    //      that is being recognized.
                    // 3.   allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
                    //      this can be setup with the `recognizeWith()` method on the recognizer.
                    if (session.stopped !== FORCED_STOP && ( // 1
                    !curRecognizer || recognizer == curRecognizer || // 2
                        recognizer.canRecognizeWith(curRecognizer))) { // 3
                        recognizer.recognize(inputData);
                    }
                    else {
                        recognizer.reset();
                    }
                    // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
                    // current active recognizer. but only if we don't already have an active recognizer
                    if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
                        curRecognizer = session.curRecognizer = recognizer;
                    }
                    i++;
                }
            },
            /**
             * get a recognizer by its event name.
             * @param {Recognizer|String} recognizer
             * @returns {Recognizer|Null}
             */
            get: function (recognizer) {
                if (recognizer instanceof Recognizer) {
                    return recognizer;
                }
                var recognizers = this.recognizers;
                for (var i = 0; i < recognizers.length; i++) {
                    if (recognizers[i].options.event == recognizer) {
                        return recognizers[i];
                    }
                }
                return null;
            },
            /**
             * add a recognizer to the manager
             * existing recognizers with the same event name will be removed
             * @param {Recognizer} recognizer
             * @returns {Recognizer|Manager}
             */
            add: function (recognizer) {
                if (invokeArrayArg(recognizer, 'add', this)) {
                    return this;
                }
                // remove existing
                var existing = this.get(recognizer.options.event);
                if (existing) {
                    this.remove(existing);
                }
                this.recognizers.push(recognizer);
                recognizer.manager = this;
                this.touchAction.update();
                return recognizer;
            },
            /**
             * remove a recognizer by name or instance
             * @param {Recognizer|String} recognizer
             * @returns {Manager}
             */
            remove: function (recognizer) {
                if (invokeArrayArg(recognizer, 'remove', this)) {
                    return this;
                }
                recognizer = this.get(recognizer);
                // let's make sure this recognizer exists
                if (recognizer) {
                    var recognizers = this.recognizers;
                    var index = inArray(recognizers, recognizer);
                    if (index !== -1) {
                        recognizers.splice(index, 1);
                        this.touchAction.update();
                    }
                }
                return this;
            },
            /**
             * bind event
             * @param {String} events
             * @param {Function} handler
             * @returns {EventEmitter} this
             */
            on: function (events, handler) {
                if (events === undefined) {
                    return;
                }
                if (handler === undefined) {
                    return;
                }
                var handlers = this.handlers;
                each(splitStr(events), function (event) {
                    handlers[event] = handlers[event] || [];
                    handlers[event].push(handler);
                });
                return this;
            },
            /**
             * unbind event, leave emit blank to remove all handlers
             * @param {String} events
             * @param {Function} [handler]
             * @returns {EventEmitter} this
             */
            off: function (events, handler) {
                if (events === undefined) {
                    return;
                }
                var handlers = this.handlers;
                each(splitStr(events), function (event) {
                    if (!handler) {
                        delete handlers[event];
                    }
                    else {
                        handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
                    }
                });
                return this;
            },
            /**
             * emit event to the listeners
             * @param {String} event
             * @param {Object} data
             */
            emit: function (event, data) {
                // we also want to trigger dom events
                if (this.options.domEvents) {
                    triggerDomEvent(event, data);
                }
                // no handlers, so skip it all
                var handlers = this.handlers[event] && this.handlers[event].slice();
                if (!handlers || !handlers.length) {
                    return;
                }
                data.type = event;
                data.preventDefault = function () {
                    data.srcEvent.preventDefault();
                };
                var i = 0;
                while (i < handlers.length) {
                    handlers[i](data);
                    i++;
                }
            },
            /**
             * destroy the manager and unbinds all events
             * it doesn't unbind dom events, that is the user own responsibility
             */
            destroy: function () {
                this.element && toggleCssProps(this, false);
                this.handlers = {};
                this.session = {};
                this.input.destroy();
                this.element = null;
            }
        };
        /**
         * add/remove the css properties as defined in manager.options.cssProps
         * @param {Manager} manager
         * @param {Boolean} add
         */
        function toggleCssProps(manager, add) {
            var element = manager.element;
            if (!element.style) {
                return;
            }
            var prop;
            each(manager.options.cssProps, function (value, name) {
                prop = prefixed(element.style, name);
                if (add) {
                    manager.oldCssProps[prop] = element.style[prop];
                    element.style[prop] = value;
                }
                else {
                    element.style[prop] = manager.oldCssProps[prop] || '';
                }
            });
            if (!add) {
                manager.oldCssProps = {};
            }
        }
        /**
         * trigger dom event
         * @param {String} event
         * @param {Object} data
         */
        function triggerDomEvent(event, data) {
            var gestureEvent = document.createEvent('Event');
            gestureEvent.initEvent(event, true, true);
            gestureEvent.gesture = data;
            data.target.dispatchEvent(gestureEvent);
        }
        assign(Hammer, {
            INPUT_START: INPUT_START,
            INPUT_MOVE: INPUT_MOVE,
            INPUT_END: INPUT_END,
            INPUT_CANCEL: INPUT_CANCEL,
            STATE_POSSIBLE: STATE_POSSIBLE,
            STATE_BEGAN: STATE_BEGAN,
            STATE_CHANGED: STATE_CHANGED,
            STATE_ENDED: STATE_ENDED,
            STATE_RECOGNIZED: STATE_RECOGNIZED,
            STATE_CANCELLED: STATE_CANCELLED,
            STATE_FAILED: STATE_FAILED,
            DIRECTION_NONE: DIRECTION_NONE,
            DIRECTION_LEFT: DIRECTION_LEFT,
            DIRECTION_RIGHT: DIRECTION_RIGHT,
            DIRECTION_UP: DIRECTION_UP,
            DIRECTION_DOWN: DIRECTION_DOWN,
            DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
            DIRECTION_VERTICAL: DIRECTION_VERTICAL,
            DIRECTION_ALL: DIRECTION_ALL,
            Manager: Manager,
            Input: Input,
            TouchAction: TouchAction,
            TouchInput: TouchInput,
            MouseInput: MouseInput,
            PointerEventInput: PointerEventInput,
            TouchMouseInput: TouchMouseInput,
            SingleTouchInput: SingleTouchInput,
            Recognizer: Recognizer,
            AttrRecognizer: AttrRecognizer,
            Tap: TapRecognizer,
            Pan: PanRecognizer,
            Swipe: SwipeRecognizer,
            Pinch: PinchRecognizer,
            Rotate: RotateRecognizer,
            Press: PressRecognizer,
            on: addEventListeners,
            off: removeEventListeners,
            each: each,
            merge: merge,
            extend: extend,
            assign: assign,
            inherit: inherit,
            bindFn: bindFn,
            prefixed: prefixed
        });
        // this prevents errors when Hammer is loaded in the presence of an AMD
        //  style loader but by script tag, not by the loader.
        var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
        freeGlobal.Hammer = Hammer;
        if (typeof define === 'function' && define.amd) {
            define(function () {
                return Hammer;
            });
        }
        else if (typeof module != 'undefined' && module.exports) {
            module.exports = Hammer;
        }
        else {
            window[exportName] = Hammer;
        }
    })(window, document, 'Hammer');
},
/* core/dom_view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const view_1 = require(42) /* ./view */;
    const dom_1 = require(43) /* ./dom */;
    class DOMView extends view_1.View {
        initialize() {
            super.initialize();
            this.el = this._createElement();
        }
        remove() {
            dom_1.remove(this.el);
            super.remove();
        }
        css_classes() {
            return [];
        }
        render() { }
        renderTo(element) {
            element.appendChild(this.el);
            this.render();
        }
        _createElement() {
            return dom_1.createElement(this.tagName, { class: this.css_classes() });
        }
    }
    exports.DOMView = DOMView;
    DOMView.__name__ = "DOMView";
    DOMView.prototype.tagName = "div";
},
/* styles/toolbar.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.toolbar_hidden = "bk-toolbar-hidden";
    exports.toolbar = "bk-toolbar";
    exports.button_bar = "bk-button-bar";
    exports.logo = "bk-logo";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.toolbar_button = "bk-toolbar-button";
    exports.active = "bk-active";
    exports.default = `.bk-root .bk-toolbar-hidden{visibility:hidden;opacity:0;transition:visibility 0.3s linear, opacity 0.3s linear;}.bk-root .bk-toolbar,.bk-root .bk-button-bar{display:flex;display:-webkit-flex;flex-wrap:nowrap;-webkit-flex-wrap:nowrap;align-items:center;-webkit-align-items:center;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;}.bk-root .bk-toolbar .bk-logo{flex-shrink:0;-webkit-flex-shrink:0;}.bk-root .bk-toolbar.bk-above,.bk-root .bk-toolbar.bk-below{flex-direction:row;-webkit-flex-direction:row;justify-content:flex-end;-webkit-justify-content:flex-end;}.bk-root .bk-toolbar.bk-above .bk-button-bar,.bk-root .bk-toolbar.bk-below .bk-button-bar{display:flex;display:-webkit-flex;flex-direction:row;-webkit-flex-direction:row;}.bk-root .bk-toolbar.bk-above .bk-logo,.bk-root .bk-toolbar.bk-below .bk-logo{order:1;-webkit-order:1;margin-left:5px;margin-right:0px;}.bk-root .bk-toolbar.bk-left,.bk-root .bk-toolbar.bk-right{flex-direction:column;-webkit-flex-direction:column;justify-content:flex-start;-webkit-justify-content:flex-start;}.bk-root .bk-toolbar.bk-left .bk-button-bar,.bk-root .bk-toolbar.bk-right .bk-button-bar{display:flex;display:-webkit-flex;flex-direction:column;-webkit-flex-direction:column;}.bk-root .bk-toolbar.bk-left .bk-logo,.bk-root .bk-toolbar.bk-right .bk-logo{order:0;-webkit-order:0;margin-bottom:5px;margin-top:0px;}.bk-root .bk-toolbar-button{width:30px;height:30px;cursor:pointer;background-size:60% 60%;background-origin:border-box;background-color:transparent;background-repeat:no-repeat;background-position:center center;}.bk-root .bk-toolbar-button:hover{background-color:rgba(192, 192, 192, 0.15);}.bk-root .bk-toolbar-button:focus{outline:none;}.bk-root .bk-toolbar-button::-moz-focus-inner{border:0;}.bk-root .bk-toolbar.bk-above .bk-toolbar-button{border-bottom:2px solid transparent;}.bk-root .bk-toolbar.bk-above .bk-toolbar-button.bk-active{border-bottom-color:#26aae1;}.bk-root .bk-toolbar.bk-below .bk-toolbar-button{border-top:2px solid transparent;}.bk-root .bk-toolbar.bk-below .bk-toolbar-button.bk-active{border-top-color:#26aae1;}.bk-root .bk-toolbar.bk-right .bk-toolbar-button{border-left:2px solid transparent;}.bk-root .bk-toolbar.bk-right .bk-toolbar-button.bk-active{border-left-color:#26aae1;}.bk-root .bk-toolbar.bk-left .bk-toolbar-button{border-right:2px solid transparent;}.bk-root .bk-toolbar.bk-left .bk-toolbar-button.bk-active{border-right-color:#26aae1;}.bk-root .bk-button-bar + .bk-button-bar:before{content:" ";display:inline-block;background-color:lightgray;}.bk-root .bk-toolbar.bk-above .bk-button-bar + .bk-button-bar:before,.bk-root .bk-toolbar.bk-below .bk-button-bar + .bk-button-bar:before{height:10px;width:1px;}.bk-root .bk-toolbar.bk-left .bk-button-bar + .bk-button-bar:before,.bk-root .bk-toolbar.bk-right .bk-button-bar + .bk-button-bar:before{height:1px;width:10px;}`;
},
/* styles/icons.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tool_icon_copy_to_clipboard = "bk-tool-icon-copy-to-clipboard";
    exports.tool_icon_replace_mode = "bk-tool-icon-replace-mode";
    exports.tool_icon_append_mode = "bk-tool-icon-append-mode";
    exports.tool_icon_intersect_mode = "bk-tool-icon-intersect-mode";
    exports.tool_icon_subtract_mode = "bk-tool-icon-subtract-mode";
    exports.tool_icon_clear_selection = "bk-tool-icon-clear-selection";
    exports.tool_icon_box_select = "bk-tool-icon-box-select";
    exports.tool_icon_box_zoom = "bk-tool-icon-box-zoom";
    exports.tool_icon_zoom_in = "bk-tool-icon-zoom-in";
    exports.tool_icon_zoom_out = "bk-tool-icon-zoom-out";
    exports.tool_icon_help = "bk-tool-icon-help";
    exports.tool_icon_hover = "bk-tool-icon-hover";
    exports.tool_icon_crosshair = "bk-tool-icon-crosshair";
    exports.tool_icon_lasso_select = "bk-tool-icon-lasso-select";
    exports.tool_icon_pan = "bk-tool-icon-pan";
    exports.tool_icon_xpan = "bk-tool-icon-xpan";
    exports.tool_icon_ypan = "bk-tool-icon-ypan";
    exports.tool_icon_range = "bk-tool-icon-range";
    exports.tool_icon_polygon_select = "bk-tool-icon-polygon-select";
    exports.tool_icon_redo = "bk-tool-icon-redo";
    exports.tool_icon_reset = "bk-tool-icon-reset";
    exports.tool_icon_save = "bk-tool-icon-save";
    exports.tool_icon_tap_select = "bk-tool-icon-tap-select";
    exports.tool_icon_undo = "bk-tool-icon-undo";
    exports.tool_icon_wheel_pan = "bk-tool-icon-wheel-pan";
    exports.tool_icon_wheel_zoom = "bk-tool-icon-wheel-zoom";
    exports.tool_icon_box_edit = "bk-tool-icon-box-edit";
    exports.tool_icon_freehand_draw = "bk-tool-icon-freehand-draw";
    exports.tool_icon_poly_draw = "bk-tool-icon-poly-draw";
    exports.tool_icon_point_draw = "bk-tool-icon-point-draw";
    exports.tool_icon_poly_edit = "bk-tool-icon-poly-edit";
    exports.tool_icon_line_edit = "bk-tool-icon-line-edit";
    exports.default = `.bk-root .bk-tool-icon-copy-to-clipboard{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUSDBoBvcHQeQAAAG9JREFUWMNjXLhsJcNAAiaGAQYwB/xHwh/Q+ITEkfHQCwEWND4jmeb8H/JpgBwfI6cNBhLSEkqaGXRpgFRAcZoZsmlg1AGjDhh1wKgDRh0w6gCaVcf/R2wIkNqw+D9s0wADvUNiyIYA47BJAwPuAAAj/Cjd0TCN6wAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-replace-mode{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxokK3gniQAAAHpJREFUWMNjXLhsJcNAAiaGAQajDhhwB7DgEP+PxmeksvjgDwFcLmYkUh2hkBj8IcBIZXsYh1w2/I8v3sgAOM0bLYhGc8GgrwuICgldfQO88pcvXvg/aOuCUQeM5oLRuoCFCJcTbOMh5XOiW0JDNhdQS3y0IBp1ABwAAF8KGrhC1Eg6AAAAAElFTkSuQmCC");}.bk-root .bk-tool-icon-append-mode{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxkZWD04WwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAoUlEQVRYw+1WQQ6AIAwrhO8Y/bIXEz9jIMSDr8ETCUEPQzA4pMeFLKNbu4l5WR0CDOMEALBGIzMuQIBEZQjPgP9JLjwTfBjY9sO9lZsFA9IafZng3BlIyVefgd8XQFZBAWe8jfNxwsDhir6rzoCiPiy1K+J8/FRQemv2XfAdFcQ9znU4Viqg9ta1qYJ+D1BnAIBrkgGVOrXNqUA9rbyZm/AEzFh4jEeY/soAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-intersect-mode{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxkrkOpp2wAAAPhJREFUWMPtV1EKwjAMTUavI3oawR/vtn5srJdREfzwMvHHQlcT2mpdMzFfWxiP5r2+JMN+mAiCOB72CABgR1cln4oOGocJnuMTSxWk8jMm7OggYkYXA9gPE3uyd8NXHONJ+eYMdE/NqCJmEZ5ZqlJJ4sUksKN7cYSaPoCZFWR1QI+Xm1fBACU63Cw22x0AAJxudwrffVwvZ+JmQdAHZkw0d4EpAMCw8k87pMdbnwtizQumJYv3nwV6XOA1qbUT/oQLUJgFRbsiNwFVucBIlyR3p0tdMp+XmFjfLKi1LatyAXtCRjPWBdL3Ke3VuACJKFfDr/xFN2fgAR/Go0qaLlmEAAAAAElFTkSuQmCC");}.bk-root .bk-tool-icon-subtract-mode{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxgsF5XNOQAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAABFUlEQVRYw9VWUQqDMAxNpWfxQxD1MoP97G7zQ5mH2RTZYLtM9lWoMbXtxLXNX4OG9r28l4hrd0PQoqxqAACYpxH25C/nkwCHyCBwSPoS09k1T5Fo+4EiExcC4v584xGFmyIXHBLRISAVZyZufUPVa4rcrwmPDgr93ylo+2GliLRUYHK6th/o/6r7nfLpqaCsagEA8Hh9FmcNKeRmgeYDC+SCq0B6FFi8/BcV6BdR9cL3gCv3ijPKOacsn3rBEcjmaVxpfGcg4wHxzgJJnc6241Hn23DERFRAu1bNcWa3Q0uXi62XR6sCaWoSejbtdLYmU3kTEunNgj0bUbQqYG/IcMaqwPS9jftoVCAQ0ZVDJwf0zQdH4AsyW6fpQu4YegAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-clear-selection{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUGEhcuan3d3wAAAoRJREFUWMPtlzFP3EAQhd+b3TNSzg0N5TWXLkJQUUaKhIQ4fgP/g5ArrriE/I3opEgRrZtIVJR0FJQ010SioUmEZHtnUpwN9gWHGA5BJCy58MraffvmfZ41v3z9hqe8BE98vQh4cgG+Ydzmnrng8efvQJNi/uN7dznx/B3ggtfhf4ehNdUttRzBDIm/2VTiiWCG1HK0nc+3UWtq8BQIiEEakEQOADBIA4QCQmBqoHBhFNR27ikQSmGdYCdTqCpEHMDZmEKRWUBEv1gBDg5SzRJnpopILWICgWuRYflLamuzxB2BmtYqSRIka5VWU8QduXO+1hRc5YZu5GAwmP2ZJzND0IBu5HCV2+NQcAhAVRsnC2IbPzPdSjzd6to6VtfWkXi6YLaVWr7xoAwkfpb8MnC3SH7rKSMBe4M0jA/OTicFIbtCGRIyNbURhcf3ErCd6YwA1m0HgAxhw1NGQnlXBHG4kylVlSJuH0RfIP2CkL2I/qS1gIAAQiBl1QwFggIHtyxgrxK5PgyfC0JWKoT0HLh8LwoietB4TYKaIl7yeNURxB05UtMxDOcVQlZIrlRKdK6m47gjR/fuBRQihyLArtNeJD50Izcx2Eczu7iFkIug4VM3cpOr3MKDekFED0fWUHv9Zq0kpLnridjhY3XDg7NTN0jDrhO3X7O9Wg7wwyANu4mnayNg3gmbu0tCNoUyBNGv2l4rB9EXynA7082FOxAQLhU6rQVO9T2AvWowFToNCJcPORGxIRcnpjZSKATSU9NxvOQnAPArDSaQoUKnNI4iufkGtD4P3EHIcWZhz4HLceSOyrR3Izf5memPAL2cX3yhAkonysZVaWLBkd9dw1Ivv2a/AYPkK+ty1U1DAAAAAElFTkSuQmCC");}.bk-root .bk-tool-icon-box-select{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg0kduFrowAAAIdJREFUWMPtVtEKwCAI9KL//4e9DPZ3+wP3KgOjNZouFYI4C8q7s7DtB1lGIeMoRMRinCLXg/ML3EcFqpjjloOyZxRntxpwQ8HsgHYARKFAtSFrCg3TCdMFCE1BuuALEXJLjC4qENsFVXCESZw38/kWLOkC/K4PcOc/Hj03WkoDT3EaWW9egQul6CUbq90JTwAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-box-zoom{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg82t254aQAAAkBJREFUWMPN11+E1FEUB/DPTFn2qaeIpcSwr5NlUyJiKWVXWUqvlUh/iE3RY9mUekkPPURtLKNRrFJEeuphGfUUaVliiX1aVjGs6aG7+XX9ZnZ+d2fTl2vmnHvPPfeee/79Sk+may2/UQq/q7Qu+bAJoxjHIKqB/wlfUMcMVqI9bLZ+DGIKwzlzQ2GcxCx2xwvKOUKlaHTiX8bHNspjDONHkOmJBW5jIof/FvPh/06MZOb6cRc7cGn1AKUE5cdzlM/gAr5F/O24H3xkFRfxAbVygvK+cIsspjGWo1zgjeFpxL+BvnLw7laBA4xjIFJwrgu52DoVjKdY4HBEX8dSF3JLYe1fe6UcYCii3xWQjdfuSTnAtoheKCC7GNED5Zx4L4qt61jbTLHA94geKSC7P7ZeShQ0Inoi1IJuEOeORooFXkV0FZNdZs5qvFfKAeqYy7nZ6yg//HG0MBfffh71lFrQDCW2EvEP4mt4okZUDftz9rmGZkotmMxJRtlisy+MTniAWrty3AlXw0hFM2TD89l+oNsoOJXjbIs4EpqNtTCLXbiZ0g+M4mFObj8U3vsNjoZCVcmk60ZwthpepLZkB/AsivWfOJZxtpUQHfWib7KWDwzjeegBZJSdKFiE2qJTFFTwElsi/unQ/awXrU4WGMD7nOJxBY/1EO2iYConq93CHT1GOwucjdqnRyFz+VcHmMNefMY9nNkA3SWUOoXhQviSWQ4huLIRFlirFixnQq/XaKXUgg2xQNGv4V7x/RcW+AXPB3h7H1PaiQAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-zoom-in{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgsUBmL8iQAAA2JJREFUWMO9l12IlFUYx3//MzPrLpSjkm5oN4FFIWVEl66IQlFYwtLOzozsjHdGRSCRF0sfBEXRVV0FQuQiLm5CZNBFgRRaRLVFhbJ2EdiN5gbK7toObTPn6eYdPTvNzPvOBz5Xh/ec5/n/n89zXtEHmZqeSXSuXBz/3zfdKvBWJHQrwZuRcP0El+QkbQXeBX6WZEgm6TtJk5lM5o4Lc+cV6qpf4Ga20Tm338zeATItVK9Ker6yvPzp4NDQ3+XieGsCU9MzTYumGbhz7m4ze9/MHgvBgItACrgfGAj2jgAvAYs3wlEujjc13kii8YyZrXXOfWhmo9GnFUlvOOemarVapVqtkslksmb2KjARqL62ecuWN9NxbRInzrldAXhV0uFSIfdew7G/gNLU9MwS8CwSmE3Oz88fcXG5blfpqVRq0Ix8VIAAX0XgrVL7HDCHGcCaWrV60LUBN8Dae58aQIxEqcA592I9M610JL0cpG/U9TIHJNKY3RV5z0R+7Nd4HZ0P1g/2RMBuegLAsRMnb4vT8d5vqKfMzOgtAlADrkmqGywmiMBTwfr3dC9j1Xv/r6Tvg/5/5ejxE6cO7M9faVbQZrYNOFSPmqQvVo9FKexvi5uWX58943aM7DwAfBDY+FbSCxP5sdkGx55GeguzrUEXPaSo2pFkAbiSZQCAzZJOmdkjwd6SpB/M7KykQTPbA2wDhoIzRzcNDx9MJwGNIXdJ0mEzmwbujL7dbma7gd03A7lKfnTOvf74nl0r6bonTUbujRSUCrm2d4L3/kvn3JPe+8+BDW2i9o+kT7z3kxP5sYsA6W47oE64TsR7P9tQL4vA2mh9WdIscKxUyJ0M7aR7acOGzikD65EQLEjaa2ZXzMwDFeB6qZBbbLTRE4EGeSaozNOZgYFf8qP7lmIvs354n0qlHpB0T7B9Ogl4IgJJrmjv/SiQjbrkD+BMUkfSbYATPdckrTOzkciWAXOlQu5cYgLdPEIapud9wMOR9zVJH3ViKx333mtHMJvNuoWFhZ3A+ojMcja77njXBEKwJJfTcqUyCIQ34Mf7nnh0paMnXacFuGoC1mr3AtuDfLzd8Zuyl+rfuGn4HLAD+Az4qZQf+61TAj0Noj8vX6oC35SL43u7teG6rf5+iXppwW7/JUL5D03qaFRvvUe+AAAAAElFTkSuQmCC");}.bk-root .bk-tool-icon-zoom-out{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgsHgty9VwAAA0FJREFUWMO9l09oXFUUxn/fmXlpItppi22k7UJBRSlVkCytSAuKUloIdjKT0El3FXVXdVFKRVAQV7qQohsNwdA0UFvBhYtqUVyIVlRaogtFQVq7qSTVjA3z3nHzBq/jvPmTN/Ss7rv3nvN99/y794kByMzcfE/7picn/jenmwWeRUI3E7wdCRskuCSTdDfwBvCtJEdySV9KOhpF0e0/LF5SqKtBgbv7ZjObcvfXgShD9Zqk5+orKx8Oj4z8NT05kU1gZm6+bdK0Azezu9z9hLs/HoIBvwAF4H5gKFh7B3gBWFY3460kWve4+3oze9fdx9OpVUmvmNlMHMf1RqNBFEUldz8OHAxUX9q6bduryut+Sfvc/Wz62ZD0fK1afjND9y3gGSRwv1GMojstTxUUCoVhdyopEYDzKXjWwZ4FFnEHWBc3Goet00m7lZlZYQixKw0FZnakGZksHUnHgvCN5/KARBH37enpOVg58H13HV0Kxg/kIuD/ngSA2ZMLt3bTSZJkUzNk7k4+D0AM/CGpaXCyBw/sC8Y/qZd2GpZiuL9YLN4Sx/HpoP5/c/exQ1OVq+1yyt13SLoArEsJnMjlgfOffvK3u58Kprab2QezJxfG2iTzUzI70wRPG9jbmpmb95SNB9mpzp7/j2yVdNbdx4K565K+cvfPJQ27+x5gBzAS7Hlvy+jo4WIvoC3kWpcvS3rR3eeAO9K529x9N7C7zX6AC2b28hN7Hl1Vt44niVq13LUjmtlYkiQfA5s6eO+GpDNJkhw9NFX5ueNt2ARodyF1IHIN2JiOl4H16fiKpK+B2Vq1vBAqFAf4IJkGNiIhWJK0192vunsC1IE/a9XycquNXARa5OnApeeioaHvKuP7r3dTGsiLqFAo7JR0T7B8rhfwXARa2us4UEqr5Ffgs151i/08oTNKdIO770ptObBYq5Yv5ibQq/sl3Qc8lJ4+lnSqH1vFfp9koZRKJVtaWnqkWXqSVkqlDe+vmUDWpZMlK/X6MBDegKf3P/nYaj8ErN9fqZBYEsf3Ag8G8Xit33BaniTcvGX0IvAw8BHwTa1y4Md+CeRqRL9fudwAvpienNi7Vhu21uwflOT+L+i1X2TJP57iUvUFtHWsAAAAAElFTkSuQmCC");}.bk-root .bk-tool-icon-help{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABltpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIgogICAgICAgICAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgICAgICAgICAgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiCiAgICAgICAgICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgICAgICAgICAgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIj4KICAgICAgICAgPHRpZmY6UmVzb2x1dGlvblVuaXQ+MjwvdGlmZjpSZXNvbHV0aW9uVW5pdD4KICAgICAgICAgPHRpZmY6Q29tcHJlc3Npb24+NTwvdGlmZjpDb21wcmVzc2lvbj4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+NzI8L3RpZmY6WFJlc29sdXRpb24+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgICAgIDx0aWZmOllSZXNvbHV0aW9uPjcyPC90aWZmOllSZXNvbHV0aW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MzI8L2V4aWY6UGl4ZWxZRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFhEaW1lbnNpb24+MzI8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjE8L2V4aWY6Q29sb3JTcGFjZT4KICAgICAgICAgPHhtcE1NOkluc3RhbmNlSUQ+eG1wLmlpZDpBODVDNDBDMzIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRTwveG1wTU06SW5zdGFuY2VJRD4KICAgICAgICAgPHhtcE1NOkRvY3VtZW50SUQ+eG1wLmRpZDpBODVDNDBDNDIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRTwveG1wTU06RG9jdW1lbnRJRD4KICAgICAgICAgPHhtcE1NOkRlcml2ZWRGcm9tIHJkZjpwYXJzZVR5cGU9IlJlc291cmNlIj4KICAgICAgICAgICAgPHN0UmVmOmluc3RhbmNlSUQ+eG1wLmlpZDpBODVDNDBDMTIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRTwvc3RSZWY6aW5zdGFuY2VJRD4KICAgICAgICAgICAgPHN0UmVmOmRvY3VtZW50SUQ+eG1wLmRpZDpBODVDNDBDMjIwQjMxMUU0ODREQUYzNzM5QTM2MjBCRTwvc3RSZWY6ZG9jdW1lbnRJRD4KICAgICAgICAgPC94bXBNTTpEZXJpdmVkRnJvbT4KICAgICAgICAgPGRjOnN1YmplY3Q+CiAgICAgICAgICAgIDxyZGY6U2VxLz4KICAgICAgICAgPC9kYzpzdWJqZWN0PgogICAgICAgICA8eG1wOk1vZGlmeURhdGU+MjAxNjoxMToyOCAxMToxMTo4MjwveG1wOk1vZGlmeURhdGU+CiAgICAgICAgIDx4bXA6Q3JlYXRvclRvb2w+UGl4ZWxtYXRvciAzLjY8L3htcDpDcmVhdG9yVG9vbD4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cphjt2AAAAT7SURBVFgJxRdbaFxFdGb2bhui227BWrsVKYgf2kJUbP9EUPuzEB803WTXJjH61Q/7Ya1+CMYKEVTsh4J/EpvY7BoabUiNiA8s1p+4KIhpoUUEselHqyS76TbZ3HuP58ydc3d2u4+IkQxczpz3mZkzZ86VYpXjvenpjZsLhUcliE4AuUuASAgptmt1EFdwPiclzIIUUwubNn17OJlcXo1p2UpodHRiux9xB1Eug1+slbzhFxGOKc851tu7/0oznYYBDA8Pt0U2tL8KQryIq2tvZqQhD0QJHRz3yqWhgYGBpXpydQMwqz6NCnurleCSADkJEfgKfOePqL80R/wV1ZaQyr1LenKfkPCkEPKeaj0xg7vxVL3duCmA0Vyuw/fl52hgBxsBED+h4Cv9z3R/zbRm8MTJTx7HQN7GQB6w5C4L4SX7M5lfLBpurjXMyvNIShiyi0l1pL8n9b7EDGPR8fHxzSsQ6XDB3618/xqo6Pk25V5MpVJllgHM1BO58RdQ612kOYZ+GXdij70TYQB05mpj+1kU5G2fB+l3PZtOf8NGx6ambnMXb3yAxg8wjSEG6OKKR9oicBQD+ZvpH2Wzj0lQpxCPG9qMv1x6hHNCsSAlHM7ZOa682vlI9tRDbvHGbD3nZAPpDoD/3JIrLpAs26UFkC3EMUA99hpfGtEBfJjNJnS2Gwnadnvl+Xw+iuc3DAJuNyIaSCHpilVldyDjjUxj3WDZIAhxhHHyRcdNuA7AAfUaXzVKODpzFiZ4/uLvh5G+m2no+C/pyIf7MqlEJB7bpqR6nXkEUfbeawuLaZsW2ISfNQ2vtaktQlGFQyIVGT0o2+2EC4iQNGwjBIN9qdQ5Qg4mk4X4rW3vCClLtowE2FOFUxKDfNmiZci3ovKKRFPh4FK9q4Zbdr+lKKJiA13TcHR2dmLBgdmQ0GAS2MZaEowY+XbAk09IvgtYZGp16SyvFhaHcIUh645t8T9DBCcnz5zZ4hZLu3DzK2QlL1QQa0Y+pHiJKPSuOGj3PmZTheM5w2TwqBxnvBZOTk7G5gvXJ5Aelms8wnJURL+olSWcfEhf6gDoUXPMq6ZlqbzWU2pE+3hi4s6F68tfIj9cBMlikr7Z0/P0b/X0yIcUXsDCF1WhtL4OROHaXk+xlkbV0Cu732Nmhc4peaWSg73pA8dq5RkvO37ldUTfXCKZv2q45MkhvG87WQEzpCCUSvV1d9GONBy3lMvgKSwrZig8gjAietWY0QriylO2jIo4yVbOSb7KB/qmI9BPKjHpSSXYauRyn92Nq9/Kcrj13x3s3v8D481glQ/0raiNYgX9njPSBOImbrHZePl+tfFmc9sH+Xaoh8NjOKSVdDMhjjYzQLy+dFceH5+IJQf9VYXX4tROg4ZFU8m31M3mfPEqUoJqCGJfvWpo2xnNfdrhC28n06SCeSzNZxlvBINGRXCtKS7EY1uV6V7HWAm38y1cXaXsMcOCvr9ySPj+af7A1U2HJXHzVNvUXVLIGyPf+jV0pf8GHoN+TLAyPkidTCi2RpPApmnR0Bd1zGRaB/B8Oj2HSw7LLbVR1MmskW8RdEWVXSJf3JbpAMgRtc4IZoxTh9qotQjCasm46M0YX9pV1VmbpvRH5OwwgdRtSg2vKaAz/1dNKVtb17Y8DCL4HVufHxMOYl1/zTgIgiYvBnFKfaNp3YjTdPz3n9Na8//X7/k/O1tdwopcZlcAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-hover{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4oVHp0SwAAAQJJREFUWMPtlsENgzAMRb8RQ5VJItFDOgaZAMaAA0iZpN3KPZSoEEHSQBCViI/G8pfNt/KAFFcPshPdoAGgZkYVVYjQAFCyFLN8tlAbXRwAxp61nc9XCkGERpZCxRDvBl0zoxp7K98GAACxxH29srNNmPsK2l7zHoHHXZDr+/9vwDfB3kgeSB5IHkgeOH0DmesJjSXi6pUvkYt5u9teVy6aWREDM0D0BRvmGRV5N6DsQkMzI64FidtI5t3AOKWaFhuioY8dlYf9TO1PREUh/9HVeAqzIThHgWZ6MuNmC1jiL1mK4pAzlKUojEmNsxcmL0J60tazWjLZFpClPbd9BMJfL95145YajN5RHQAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-crosshair{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADEUlEQVRYR81XXVIaQRCeHqug8CXmBNETaE4gniDwIgpVspxAbxC9ATkBkCpQ8gKeQDiB5AQxNyAvUlrldr7eHxyGXZi1rMJ5opbp7m++7un+htSGF204vsoMoNXrlzSpfWa1oxQfhAegCZGaEtPorHo8znIoJwCt6+td8uk7ApUQCIHTF4BNAWzImq8ap6cP68CsBdDp9i9ZqXM7ML79g/EnCWD+jgMKENKqWT+tXK0CkQqgNRjs0OxpQIqKhoMxaG6/6JeRnK7T6yO2UvVqhYSlLX+ryORfgKn9ORDFIy7ky41yGcwsr0QAQfDH5zucOswx819fs4egI9OFCcD8DjBF7VNbEX0JzdWEt3NHSSASAcCxBDqMgt/623kvyTgNgNjJIfTjk4D4FqaJR1715MjmYAmA5Bx3AwUXQL+t105KaTlcBSC26XRvhjEIoLiq1yqXpr8FAGG16/ug4IT27fxBWu7EiQuAiImJpEMKE6nYM30uAIDDttSUOPfJP7JzbjPhAiBIh9QE67vIvoOi9WJfCwDavf40ulpjbCqmUf+W753ezURuh7Dg1SqflwAEHU6pgfyBq9Y4qx0LG++2fnZ/eUzcstmdM2AWH+jfc+liWdBJfSENf8Lifi3GVwC9mybOfi5dzatWVrbbLIHNva8p5h/16gkaFiLGGxbufkoE6XguwePiXLF3XmMfCUCUAqtKXU7sumd1CowOuJEi3Pg1FBpjitIGhyvVSfvmjci6ZR+rFQfDiPVE2jFYeICQ+PoewwjC5h7CZld6DBdyu6nDSKgzOyIMhmhK5TTqXYbRorZYM46TmpKAAOrGWwSJJekSB1yqJNOzp1Gs7YJ0EDeySDIMtJbQHh6Kf/uFfNFZkolJICRmz0P8DKWZuIG2g1hpok+Mk0Qphs0h9lzMtWRoNvYLuVImUWrmPJDlBKeRBDfATGOpHkhw670QSHWGLLckmF1PTsMlYqMJpyUbiO0weiMMceqLVTcotnMCYAYJJbcuQrVgZFP0NOOJYpr62pf3AmrHfWUG4O7abefGAfwH7EXSMJafOlYAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-lasso-select{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgwlGP1qdAAABMBJREFUWMO9V1uIVVUY/r61z57ZMx4DnbzgkbQXL5iCJphlWdpIGY4jpFBkEiU9ZNaDRRcITcIwMwgxoQtU2IMXdAZfMjFvpERXYiSbysyBEXFmyuHMnLP32uvrwT2xnY5nxvHQ93Jg7fWv71/r//7L4a59TRgqJk+Z6v3a+sv0OI5nk5wu6VaSVZImAThHsgjgrKTvM5nMUWvtmf5n8HodCIKgOgzDhc65pSTrJQWDsSNpJX1ljHnDOfdT37oZLLHv+8OMMasKhcIJ59xHAJYMlhwAJGUAzJfUTHLFuFzOG5QDU6dNMyQfs9Yedc5tBpAD4IYYNQGoBrDtQnt7/b0LFrJsCHzfn2itfQfAnZLiazytA3AaQAuAiwDaEgeNpGkkswAWSBqRONB38b88z5uTKePt6iiKXkk8jq+iJC5LOmiMaTLGHLPWhmWeHr7vV0dRtATAapAzIVmSo51zyzIlbm2stesFPA6pKk0r6Ryg93y/ek8YFvPOOTg3cDSiKCoC2OP7/rEoirYm4rUkF12lAWNM1lr7lqQn0+QA8gI2jBg5cj6Aj8OwmB+KAKIoukhyp6SRJAUgl0ndPLDWPi9pJQCbuviXvu+/GIZhW1dnJ24UJFuTjCCA2ADA8sYGWmsXS3qmL94kDYAtkh4Nw7ANlQJ5U6INT1KrAYC9zQdykl7nFSj5fXp5Y8NWVBhy7mUAjqShMYdMXV2dJ2klyRwAJ8lIeuGWCRMP7N7frEqSG2OmAFhKshNAp5wrmO7u7jEAngPQm1S2z2pqapr+OPt7XEly0oxwzq2RdFmSD2AMgKKJouhhAL4kA+Cs53l7e3t7uytJHgRBreTWkXwkKVJnJD0B4GAGwIJE9R6AFufc6UqSZ7PZbD6ff5dkA4CQZEHSqwAOISmXtwGIE+F1SeqqIP8d+Xz+C0mLJYWSAODteXffczjdDQNJ0BWMCoLg5gqIbRTJNwHsljQhUb0luWPM2LE7Thw/9m/5NCT/TByxAOYWi8X6/gdWV1dnfN8fNRBxJpMZTXKdc+6IpFVJWAEgkvSJpA0X2tvtVTaSjgOYBCAEEADYSHK87/sfhmEYA9gShuEDkgzJHyWtB/B1irQ2juP7ADxkrX0wOUOpzmdpzEY590HJ7Ni1r2kSyZOSiv2+hSRjSTXp/QAukzySNJOJkmalyNIl10hqMcasdc61XDNcQRD8BnITgNp+36r6kfcNFMMlLQGwTNLMEuQGQBfJl2bdPru+HDkAZAqFQux53jZHEsC6aw0eg2gylNRBcqcx5v04ji999+03AwsWAOI4Lsy9a94WkisAnE5a5WCJYwCfA1g7LJudI2lTHMeXBm1faiQzxkyRtF3S5CTupeAB+KG2tnZFT0/P30NO2VKLzrmfAbwGMipjG5Oc0dPTc0Md05SZ5U4Q2FxChErtEYD7jTGNQ3UgM8Asv90Yc9I5LSKRlXSI5CxJa0jWSALJjKRnAewfkniT+vwf7N7fXHK9rq7O7+jo+BTA/NRrdBpjnnLOnUrvXd7YMPQXSBunneno6IhIHgYwW1JtkgmBpBkATlVMAwOk3nFJ+VSoqgCMr6gIy2FcLtdKspAedyQN/98caDt/3kpyabUmf8WvG/8A1vODTBVE/0MAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-pan{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4lKssI9gAAAOtJREFUWMPVll0KwyAMgNPgoc0JzDX2Mtgp3csKErSamGabIEUo/T6bHz0ezxdsjPJ5kvUDaROem7VJAp3gufkbtwtI+JYEOsHNEugIN0mgM1wtsVoF1MnyKtZHZBW4DVxoMh6jaAW0MTfnBAbALyUwCD6UwEB4VyJN4FXx4aqUAACgFLjzrsRP9AECAP4Cm88QtJeJrGivdeNdPpko+j1H7XzUB+6WYHmo4eDk4wj41XFMEfBZGXpK0F/eB+QhVcXslVo7i6eANjF5NYSojCN7wi05MJNgbfKiMaPZA75TBVKCrWWbnGrb3DPePZ9Bcbe/QecAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-xpan{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4X4hxZdgAAAMpJREFUWMPtlsEKwjAMhr/pwOOedINJe/PobWXCfAIvgo/nA4heOiilZQqN2yE5lpD/I38SWt3uD9aMHSuHAiiAAmwaYCqoM/0KMABtQYDW11wEaHyiEei28bWb8LGOkk5C4iEEgE11YBQWDyHGuAMD0CeS30IQPfACbC3o+Vd2bOIOWMCtoO1mC+ap3CfmoCokFs/SZd6E0ILjnzrhvFbyEJ2FIZzXyB6iZ3AkjITn8WOdSbbAoaD4NSW+tIZdQYBOPyQKoAAKkIsPv0se4A/1UC0AAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-ypan{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4anK0lywAAAMVJREFUWMPtlzEKwzAMRX/S7rlpIMXeOnaLaME36FLo8XqCdNFghGljyc4kgQi2Q/SUj0F/eL7eMMTKz6j9wNlYPGRrFcSoLH4XxQPvdQeYuPOlcLbw2dRTgqvoXEaolWM0aP4LYm0NkHYWzyFSSwlmzjw2sR6OvAXNwgEcwAEcwAEcwAEcoGYk20SiMCHlmVoCzACoojEqjHBmCeJOCOo1lgPA7Q8E8TvdjMmHuzsV3NFD4w+1t+Ai/gTx3qHuOFqdMQB8ASMwJX0IEHOeAAAAAElFTkSuQmCC");}.bk-root .bk-tool-icon-range{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABCJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIgogICAgICAgICAgICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgICAgICAgICAgIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyI+CiAgICAgICAgIDx0aWZmOlJlc29sdXRpb25Vbml0PjI8L3RpZmY6UmVzb2x1dGlvblVuaXQ+CiAgICAgICAgIDx0aWZmOkNvbXByZXNzaW9uPjU8L3RpZmY6Q29tcHJlc3Npb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjcyPC90aWZmOlhSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICAgICA8dGlmZjpZUmVzb2x1dGlvbj43MjwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxYRGltZW5zaW9uPjMyPC9leGlmOlBpeGVsWERpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6Q29sb3JTcGFjZT4xPC9leGlmOkNvbG9yU3BhY2U+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4zMjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxkYzpzdWJqZWN0PgogICAgICAgICAgICA8cmRmOkJhZy8+CiAgICAgICAgIDwvZGM6c3ViamVjdD4KICAgICAgICAgPHhtcDpNb2RpZnlEYXRlPjIwMTgtMDQtMjhUMTQ6MDQ6NDk8L3htcDpNb2RpZnlEYXRlPgogICAgICAgICA8eG1wOkNyZWF0b3JUb29sPlBpeGVsbWF0b3IgMy43PC94bXA6Q3JlYXRvclRvb2w+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgrsrWBhAAAD60lEQVRYCcVWv2scRxSemZ097SHbSeWkcYwwclDhzr1Q5T6QE1LghP6BGNIYJGRWNlaZItiFK1mr+JAu4HQu0kjpU8sgF3ITAsaFg0hOvt2Zyfvmdsa7a610Unx44Zgf773vvfneezPHNzrbhn3CT3xC3wPXYOC8LDzqdi8YY/gwh4BeknS/2th6dr2kf94AOp3OFyWgMyziOPbMDxV9FTtJnl1ut795Xd0/YQ0/vtYQwMT1KXWCfr2IjOWwtNehwN4xL9ykTrm6Pzl58yLn3J+mKh9mXbT3uRjGEDph+O8/TjfP5dBp7Ha7AX7O3o5nZeD/0E/OGyXntDgzA0X6qmCnrVutVlrUWV9f/3xo+pwhGDhvEPHOjoxnZjJggXmMHzBQ7NGNp9vxk61fr0HR7e/u7pZzCGHlc7qwBYYTT7tJYSx1AQzppyFPft5apta9w7SKcn0b7P7+/jCsDQ5mbc0dCmIJGDN0ehdcjsmkm6A6KUeKFOTE11PLxrC7Ukqh3ylL2fT0NAP9q6ur6rRCJJYsbKB0JsbCKMuy+xREePDyxQPCz+Crlw062QcA5wBOOt1l6vIl2WiI9F1fN6Q+BBqit6hEC4Hk08GQJMn4myjSP7RavVxgdaVUh/3U6HCMsPr9pYnJKRziHtWQ+un58+hGs6nsjQSjpuTyKGN3CX+FBwHXSiEVgjP+O8X6N12kIePES+GzTKAkGbNp8yJsGUMVzz8jPKReiyAQRimy5/cjye5RpF8utFp/+nwmT7d/NMzcFkS7yjJNGDaPURQxIQThEQy0SyF4l5WJYYhBa816vZ6dU7A6CAhbZVow/pDe0O9hVOoCi13r4BgBAvJHqMSQL2vE/iH6IAXEwgrRVUmBoRRwnwJQT98xEeVeSUyB4dJ5nwJBKdCFFGRmUCcu7rwIYypCTblaChuNBhWODrman5ub+4v0rMNBt8z6Ezh7GksJQpCbm79cMQE7QBFm/X6f0rjWnv8WRYg/QdbUpwDAEBy8vPyA8rNGzg3a8MiElwiM7dAtRqNoNptjGPM1laVxP9umWEMGLOKhKUOJDtBwDmzsw9fC/CzHr9SGuCTi2LbbKvVtmqXpCjMihBFa79Wrt5fGx9PDzc3fmu32Lf8qFliwU9emKhBSp+kRKn/hu9k1COEDbFdt/BoKWOAkuEbdVYyoIXv8+I/QK9dMHEb1Knb7MHOv8LFFOsjzCVHWOD7Ltn+MXCRF4729vWMDK+p8rLkvwjLg4N4v741m5YuwCI9CvHp1Ha8gFdBoPnQAkGsYYGxxcfEI7QQlFCTGUXwjAz4tWF+EpymOWu7fglE7qsOvrYE6g4+9/x/vhRbMdLOCFgAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-polygon-select{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEjc1OfiVKAAAAe1JREFUWMPt1r9rU1EUB/DPK0XbqphFHETo4OCiFhwF0V1KHbRSROLqon+AUMVRRFBwEbRFMBiV+mMW/wIxi5OD1kERRVKRJHUwLvfBTZrU5OWBGXLgQu7Jfe98z/ec7z0vKa88b2q1BDtRHdAPBaylm1NzsxsOjPnPNt6WSWprbft+/c3I3zOAjhT1Y4+fvcjEQJIXnVECSa+AhqIHqlHH5lWCZoe+Gk4GRgDG86j9SAUdlDBSQaZhlOkuHyoVdJmsw98D1S5fM4NYM1LCpqM+Lwa240oLgmZzpVZvzKT75VLZcqksSZKWlQeAy/iORVwIvh31xvotvK7VG3Px4aWHj3Jl4C2uYSvq+Bn8v6LLbaVWb9zsBiKLCvbiNG7gLm7jAYqbPHMJMziZ9lsKoh8GtqCEVVzHftwJn+TFHp4/hg8BSCYVfMOZoPEv2NZGdy9WCGUr9toDR3E2/H4V6nwRe/BmgN65H1ZhvMuB3XiKIyFoGefwO6ysVkUlrNUNsyAK/jli533Q+Y8cJFvAeXyMS1CI/jiMr/gUtD2LQwMGr4R3p7bY3oQHQ5b38CT4D2AXXg6YcQXHpyYnlqKsi5iOAVSwL9zd7zJ09r+Cpwq72omFMazjT9Dnibym0dTkRDUKrrgwH7MwXVyYB38BstaGDfLUTsgAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-redo{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4itK+dVQAAAaFJREFUWMPt1L1rFFEUBfDfJDaBBSslIFjbaSFp1FJQFMVCHkzhKIqdUYOCoBgErVz8rCwiTDMwBCIKipDWyip/gxAIWAmBgBC0eYFh2Gx2l9lFcA5M8e59782Zc84dWrT435Hs1siLchqn43MS0zgW22vYxjesYjVLw3YjBPKinMUTBOwf8J5fKLGYpWFjJAJ5Uc7gIW6jM6Kim3iNZ1katgYmEL/6I+YasvY7Lg6iRpIX5VF8wuEe/XV8wGf8jN6LWTiAc7iEQ7ucPZ+lYW0vAtfwvlbfwCKW9gpXDOv1mJvZHiSO91MiyYsyiQSuxtpXXM7SsDmM5nlRdrCMMz3sOJWl4Xevc/vwBzdwAl+yNNwZxfRI+GxelK9ikHcwh8d4NNR/YFRES1ZwoTYdR7I0rNf3TzVNIGbmSvR/Bx08mIgCFSVu4l2ltIWD9WxNGR+W8KOynqnZ0rwCeVG+wa0hjrxtWoF5dAfc28V8Mib/n+Nev5dnabg/zgw87aNEN/bHOwVRiRe4Wym9zNKwMKkpgIWKEt24njxiJlq0aPFv4i9ZWXMSPPhE/QAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-reset{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4gWqH8eQAABLdJREFUWMPtlktsVGUUx3/nfvfOlLQaY2IiRRMQIRpI0PjamJhoVASDvNpCpYw1vJQYSVwZwIVQF6wwRHmkAUof9ElrI6VqDAXcID4TF0IiYQMkSlTokNCZ+b7jove2t+NMH7rQBWd3v+989/zP+Z8X3Jb/WGQySvUNTQBJESkNguAVYIWqzhaRhwBU9WcR+QXoymazn6jqzUQiMQSQzWZRVdal1vwzAI2tHQBPOuc2AbWTdOyQ53n7nHNfRwee51GzqoIQMCLDpr3x/tLQ0oZzrk5Vj0/BOEBt+KYuOlBVGlrahr0Wob27t3gEjnZ2AyQzmUwHsDgP6J/AYRE553neDwDOuUdU9QngNeCumK4TkRMhZUORcYC1qysLA6iuSQHIwkWLD6lqapQsuSmwTVV3h99I7EcAR462A2xR2Ilq6ehTaejvO1774kuLNALR33eclsaGsQDe3fYegHl43vyNwEeqGl1963mm2jl7YZRTQ82qlWP4HM6ZToC5ztkW4LHQoALru7s6Di5dvlIj/e6ujrEAWoZDn8hmMjXATMACGaAVuBjXTVVXFc/AxhaA+4zvn1DV+eHxVWPMAmvtb5GeMWZyZVhI2rt7qVy2pOh9U1snwIPW2vMi4oWJuBPYHkVAVScPoKmtkzVVK6cEMsyJraHhiCqJqJUwj/JRz7TW1iSSyR2rVyylqa0Ta+24Ic8vXaAEmDFc/l5Z2A/80OibuVyuz/f9ElUdHCmvw82t5HK5h6y1PYhsz2YyGw43t2KtBZHIGwB6+j4rCkBVUdV7gXrggnPuu8h4eP+xMeZS2D0rJYZ6AdAMzAt1b4nI26p6IFZOY8pugijcKSIHVLUK0LyST4vnrVfnWr3mjmP4QTATaERkXkypRFX3isjmuHdRJEK6Ckqquopp06bdKCkp2Sgi7XnGLcg7gzeutwNIiPYc8HixqIrIOlU9ONVIhHPEd851icgSVXUiskVV94gIqoonIt0i8gfQCfwae38e6BWRXuBZz5jZ8VbaOE4EIqlZVUEQBLlkMplS1QER2RwkEnsSyaREDUzyeNsvIhvCMqkH1kdIJ2o+k8iJB1LVVRfjZ6nqqlEAIbdVQGto8Lrv+/dbawcjAL7vc+6bs+zetetfLSHxniIFGofGGsU2oC7eOCbDfZ7nQawBOSAX74SF9oEPImOq+r7nmVmxb5raukZa8UReGmNmhbMkAwwBH467EYVZe49z7kdgenj8k7V2oTHm8kgdWcvrNdVFjR8cHkYzjDH9wLjDaEwEzpwa4MypgWvAjtjxfGNMj4jMiT+M+kFsZI/Q6Pv+HGNMT8w4wI7TAyevxXVPD5z8+zD64tRXAMHVK1eaVLUyVvuDqroV2BOnJF4ZIedviUidqt4Re9s+vbx8zZXLl7PR2+nl5Tz/zNOFp2FzxzGAklw22wUsLLaSKXwf8vhosZUM6PeDYEUum70VHfpBwKsVyyfeikOP6oBNwN1TrLbfgX3A1kKLzKeff8nLLzw38T5wZDgxn1LnNk5lLRfP26/OnR2hwfNYW2Atn9RCsrf+EECyrKysDFimqhXhyjY3VLkAXBKRDqA7nU6nS0tLhyIj6XSaN9bVclv+l/IXAmkwvZc+jNUAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-save{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4UexUIzAAAAIRJREFUWMNjXLhs5X+GAQRMDAMMWJDYjGhyf7CoIQf8x2H+f0KGM9M7BBio5FNcITo408CoA0YdQM1cwEhtB/ylgqMkCJmFLwrOQguj/xTg50hmkeyARAYGhlNUCIXjDAwM0eREwTUGBgbz0Ww46oBRB4w6YNQBow4YdcCIahP+H5EhAAAH2R8hH3Rg0QAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-tap-select{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo3NzIwRUFGMDYyMjE2ODExOTdBNUNBNjVEQTY5OTRDRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpCOTJBQzE0RDQ0RDUxMUU0QTE0ODk2NTE1M0M0MkZENCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpCOTJBQzE0QzQ0RDUxMUU0QTE0ODk2NTE1M0M0MkZENCIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1LjEgTWFjaW50b3NoIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6OTQ0QzIwMUM1RjIxNjgxMUE3QkFFMzhGRjc2NTI3MjgiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NzcyMEVBRjA2MjIxNjgxMTk3QTVDQTY1REE2OTk0Q0UiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6eYZ88AAADLklEQVR42rSXf2TUYRzHv7tuGcfE6Vwb5zLSSjEj7Y9KWqfEmFZJP+yPMdKKmUrrn0iUfjhWlLFi6YfNrF+StBoTo39iYkTGco4xxxG59P7k/T2PT8/37nu3bx9ezvPj+zyf5/PreS78bGLS8SmrwE6yje3NHJsDBTALpknBz6JhH3NiYAB0gHqPOVv52wJ6QQ48BzdAttTioRJjdeA8mAHHS2xuk3p+M8M16ipVQE49Ds6CiFO9RLjGONf05QLx6wPQaBlbBlPgJVgkP0ETiIJ2sB/E1XfimjfgBOOlKDUqCGOcqBcQnw6BYW5YTo4wbvQhMmCfGRemC2rBiGXzWUb+kM/NRZ6CHWBM9ce5R61NgX6ayhSJ5EPlItlDRNkz4JbFHf06BkSzHjXxM+gDv1S/mPUo2AXWgt9UUHL/IVhS8yUV1/EbV3o4N+NaoE9Fu/i827K5pNYHnqAVJECShWmAaddpscYFFXwR7vnXBRGlnUN/L6kqKJlxnRUuDbaDBiL+vst5d4gpcpBrqk/2jIgCKVUolhntplzivHmwh4stGOPfwBWwl/2dpp8p7xjQZqFLiQJtauKkivYm+kzccpK57yXfOUe+P23JqAnVbhMFmlXntCWnxbT31am9ZJ4BJifsUmNTqt0cYhA5ypympPg7VkEKunPbVb8cIG+0kyHLJZNR7fUMooUKFHAPkfQo58VLK+RzwRDd4FdWG9mjpaAXzqkJa1R7kQttqEABWXMjOOxxVRfnhRm5URX1prk/0pQHwNcKlchZ+jdpC+hFdVqO0my9Hj5dkYgCn1Rfh/KdlNDHrJhPqlDih+IfBd6qwpOgEqYMsorJ2HtWxtagLJDn/W3KRfPOZhoeBJfZPgVeGKeKrkQBh5dLXl25Ny3pc4/1fkTdbvFqFQgbxWeYD0hXulhQ0pYiM1jG547fcbMQpVnHTZEn9W3ljsCzwHxCdVteNHIZvQa7/7cC7nV6zHIfyFP9EXjFa7YxKAVqPP4bxhhoLWW+z9JyCb6M/MREg59/RlmmXbmneIybB+YC/ay+yrffqEddDzwGvKxxDmzhc0tc80XVgblqFfgjwAAPubcGjAOl1wAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-undo{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4em8Dh0gAAAatJREFUWMPt1rFrFFEQBvDfGhACASshkL/ALpWVrSAKEQV5sIULWlgZNSgIFkGIVQ412gkBt1lYLERREFJqJRaW1oHAoZUQsDqwecWy7N3tbe6C4H2wxc682Zn3zTfvLXPM8b8j6RqYF+UCzsfnHBawGt3fMcAX7GEvS8NgKgXkRbmMxwg41TLsN0psZmnodyogL8pFPMIdLHUk7hA7eJKl4U/rAuKu3+HslFr/FZezNPSTFslX8QErDe4DvMVH/Iq9F7VwGpdwZUjsPtaSFjv/1vCBPjaxO0xcNbHejLpZrrlvJCMCT+JzA+2fcC1Lw+GE4l3CG1yIptfjCtiKoqtiJ0vD3aM0Py/K57iIMxgkQxat4EdN7e9xdRzlk+LEEPvDWvIDXJ928sYxjL36icWK+VaWhlezOIqbGFirJd/H7szugrwoX+D2BDEvszSsT5OBdfRaru/F9dPXQF6U27g/KnmWhgctxqyzBrZGMNGL/rHI0nDkKXiKexXTsywNGx0OnFbFNk3BRoWJXnw//j+ivCi32/S8CxPVNiWOAdUiJtXITIqYY45/Cn8B2D97FYW2H+IAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-wheel-pan{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgswOmEYWAAABddJREFUWMO9l09oXNcVxn/n3vc0fzRjj2RHyIZ6ERuy6CarxJtS0pQSCsXNpqGFWK5tTHAwyqIGN7VdEts1LV04BEoxdlJnUbfNogtDCYWQRZOSxtAUCoFiJY0pWJVUjeTKM9LMe+9+Xcyb8ZMychuofeHCffeee7/vnXvOuefYlV/+mv932//tb91z/Y2rvxmMHQ+4FcEfOIGN4A+UwDDwoQScc7vM7AIwB8yZ2QXn3K77Ab6OgJnVgeOSbkqaBiaACUnTkm4Cx3OZzwf+qzcRQup1zNZ9RwDe+0YI4YKZTUn6zCGSMLOfAF/03r+QZdnyfwO+ePEiI6N1nPMgMDMkETLRbd2mXG8gCbd9YiIKIUxLKoLfBN7I+80+CUlTIYTp7RMT0b3Af37p8kh5y9gZcy4Fzt+5szqSaxkzUR7dwtrKMmaGW242d0t6vrD/He/90865o865o977p4F3Ctp4frnZ3L0Z+OryUrVSrZ0z8ZxhHjhcq1XPrS43q/0flDlK9XpPA2ma7gMeyvfPx3H8TJZlH4YQWiGEVpZlH8Zx/Awwn8s8lKbpvmq1ahvB641SXNk6dhLskNA2MIBtwKHK1vGTW8bKMRbAMgyPqWeETxUM8VSSJAv52JmZA0iSZMHMThWwnipXKp8hsLLcSaIR92oU8xjSayCQXotiHotG3Ku3m+0EOQwPQCDggMf7BzQajSs5eAk4B5zLx4O1vD2eJMmAQKliscgASJMw21pansFs1swQ/DNLmUmTMNuXX+taXHTDaj5OW612R1JZ0nFJJ/J+XFJ5aWmpA6S5bHV8fHsPHFU6q3pJCjtFxtrKMuXRLUUXXxdrRLazFOtUolZlsGhmACsgnHPTwJnCnjP5HMBKLotzxsTE9rgDL0t6LoriKsDIaB31ZEK+JxQJRHFUBR2NqLw8OTkZR0OC0ntm9k1JWU7OA4vD/mZ+YfElsANmNEKi75vztzB5M8uAr+bx48me88g757PQ1U5zNg52YH7hX8l6f+4Fi3c3BqHNmkI4YQOV2MGCNu9qHPYCewfzbrC+XSGcWEcgTRKA3wFfyzdDz5d+D3x9CIcfA4eBbQS9LscskgfLnHNPAnslvS/pbZDHLLPADpx9N9fqpSIBH8cxWZY9m6bpb4Ev5fN/iKLo2TRNgdx/eo8Wk5O7Ts/N/SOSdMjHdj4kmgkIEJLJzPZKetvMTkIvFLsR25Ml2gfuF5M7vnA66sdooJYkCSGERe/9VAjhzRxoKk3Tvg3U8nulVqvx8cyNpER2umM+SdOkbc5B8JhpqBdIgTRR24h+lpKen731aRIN7thscH9Zlv0d2F8YD2TIX7F2uw3A7ZWV1a0TYz9ca8cJZHRbuRuaDfUCw9/qJHamPOKToAwHtHN6lMvlSkH2o7wDMDo6WuGuQbbn5+YAKNcb3J5fSvrhtTY+vsOPuD1IOyRhMOkj9kSx29HfXB5RUnS964NT2+3vbGbxG9auO2cDNuV6A8NTb5TitBuOpQkfYD2vwOxgmvBB2g3Hto5X42EJyVsFlztbKpXGNgqVSqUxSWcLU2+tdToa9hasLjfPYlwGa+bTi8Dl1dvNsyvNtQQL9MO2w+HM7BqwlAtPdrvdq9773WAVsIr3fne3270KTOYyS2Z2bbXdHhogKmPj7YWF+VOSXs/v/9KdO+0fVBrjbRkgB/KIDBnYu9f/7D+ZmfmRxPd6qwB8YmZXcq1MAQ/nJhTM+OnDe/a8+PGNG9lm19V/D1Qw7HXZlcRa69+U6w38l5/4ipxzf5X0CPBILjcGPJH34pVcc8692FxcXLlXRnTwwH7+9P4f8aWe3fY59LIqo1NMyQBCCHNmdgx4BegUWefjDvCKmR0LIcz9L8nokSNH+PRvH4HC3YQ098pSbevg24qlmZmNmtmjkg4D3+j/tZldkvQXSa3PW5ptlpL3ZaIN99OS9F7+IgKUgSyEkNyv2nHT7DZX0dr9rpjua2l2r4rogRAYVqZvnPsPqVnpEXjEaB4AAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-wheel-zoom{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgskILvMJQAABTtJREFUWMPdl1+MXVUVxn/fPvf2zrSFmUKnoBCUdjRoVaIxEpO2JhilMYBCtBQS2hejpg1Uo2NUrIFAoyGmtiE+GHwQGtvQJhqDmKYRBv+URFsFDNCSptH60DJTO3dKnX/33rM/H7rvsDu9M20fDMaVnGTvtb69z7fWXmvtc/TEzqd4OyXwNsv/FwFJQVI/sA14SZKRLOlPkr5TrVYXHz70quYkEEK4TtI2YAgYkrQthHDdhV5uuw+43/ZrwCbgRttgY/tjtrc0m83X3/f+D6ydnJhYcB4BSZcBA7aP2d4ELAGW2N5k+xgwkDB0IH19CGGH7R8B1aQeAf4KvAw0ku4K2zu7uru3ApdPEyiKohd4TNKjtjt5h6RHgccSNrddbvuHtm9Jqoak7xVF8WFgdavV+pSk5cCObNmXgK++85prCj3z28HKqZMnH7D9YAY4BvwujT8BvCuL1INX9vVt+dfwcCvNb7f9q2RuSfrGvWu/sL2Nf3LX7pzvj4ENSGBPVarVd4fRkZFltjdmoMGiKO4IIWwIIWwoiuIOYDDzeOPoyMiyFLkum7WJCMDztrcrTTrIRuAQZ6NcK1utL4dWq/VZoC8BhqvV6l1lWb4YYxyLMY6VZflitVq9CxhOmL60hhCKeYiV7WMKIXw9jT1HpXw3c+bOAKzOjJubzebJrKQCQLPZPClpc7bP6rMYKtjXth2OMf7tIkr11Wz8oQDc1Fb09vY+kQw1YAuwJY2nbUluAnCWpKkaFl6IQIzxivaR2SYA89sJVK/Xp2x32R6w/a30DNjuqtfrU0ArYecDCEqgLqm94T0dEm9mBG7PxkdDlkBnkhebgIezNQ8nHcCZPL9ijE1Jf/bZZoPtzbavmqNZLbf9tSxq+yoduuJ+SZ+zXSZyBXCqU+d8fvC5yRUrV+0G2j3g2hDCLyXd/+Su3QdnvP/zCuH72LWsgf2k0oHlH2c2odlkxcpVEdgr6aDtjyb8x20/J+mA7T9I6rL9SWA5dne2/GdXLl58qNJh398An85yTMA+4DOz8Dgu6Zu2dwJXJ91ltm8Gbp7Fgb+EEB4aHhpq5CEtACqVyr3AC0AlPS8k3TSmQ2YPhhBuS/1/LpmS9JTtNTHGfwBU2uUALARotVqniqJYH2Pck85pfavVaufAwnQvnHc0McaDKVptebN94QAnJB0EdtjekydyZXqjs/0ZgLIs/w6sy8bnYGYJ63pgERKC05JutT1kOwITwL9tvzlzUQUYB+Zjs2DBgu6xsbGJZHstByZbezregcBXeCsEz1bnzXt5anLyzLq71zDLxTRdVgemdx0fv2e2w5thO5DbiqL4oKT3ZKpnpyYnz+SY2ZpTAPZmJfdIrVZbNBNUq9UW2X4kU+2dcf53Aj1pj2PA7y/6m1DS00A9za9uNBq7iqJYBuoGdRdFsazRaOzKSqye1rTbaa/tlbYrqXQP2X4FIA9/J1l39xrC0v7+w5IeB8XkwS1lWe6TGJAYKMty31tfO4qSHl/a3384I3CDpI+kzC4lnRfrue6GytEjR8oQwlY73gC0L4qlth/q0M1/LYWtR48cKQF6enrC6dOnVwGLEpnxnp7en4+O1i/tszzGOCTpPmB7ahb57QUwBWyXdF+McWg6MScmuoA8OX8xOlpvXGz422XYTsB/SnpA0h7bX5R0WzI9HUL4qe2XbI+dk3xl+V7gxoztD5jRI+YK/zkEEokx2/uB/RdzIfUtueqVN04cXwF8G3iHY3z9Urw/j8ClyhsnjrcS2Vv/J/8NLxT+/zqBTkcxU/cfEkyEAu3kmjAAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-box-edit{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4QfHjM1QAAAGRJREFUWMNjXLhsJcNAAiaGAQYsDAwM/+lsJ+OgCwGsLqMB+D8o08CoA0YdMOqAUQewDFQdMBoFIyoN/B/U7YFRB7DQIc7xyo9GwbBMA4xDqhxgISH1klXbDYk0QOseEeOgDgEAIS0JQleje6IAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-freehand-draw{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADTElEQVRYCeWWTWwMYRjH/88721X1lZJIGxJxcEE4OOiBgzjXWh8TJKR76kWacOBGxdEJIdk4VChZI/phidRBHMRRIr7DSUiaSCRFRM3u88gz+o7Z6bBTdjmYZPf9eJ55fv/5zzvvDPC/H9QsA66Olo9Ga+/MdR+Ljm2/KQIULsz9FqItGdOfJKLhApLgVkiSCGODjWit7QpKWy+TNrFeXvzKVUT8NiTVaIgDcbiCFJ7GiT8WkARXAdYBK0Lbhi/CenArRNskuM7/tgNp4ArQ42dwjf3WY5gWTqC7O/NbNn2Xkfw/YwdSw/We14HP2IEZwX+y9cZ9SH0LmgFP7UCz4KkENBNeV0Cz4b8U8DfgKiDxMWwUXETqLvJpCQpXZfawbzS7t9v5pL19cHBwfja7YA0y/lyCM0+E5hv5+piZXwKYcF23as+37bTXsQVqgkL0p/34fHR7DcBtbetFsBmGDwMOJCggYG55yw7dMlk6DuC1Bdu2RsCU9TYWQq2IoGbsreZ5NzvEqfSBsIsIy8OTbcdgiRHeh4o8AFAEwDakbY2AaCCpH7V9aGhoUUUy3UyVbkPYFuYLDlUZH8XBpwxkK0Dbgxg5HcVi0ent7a0RULMIozaHBSMfF9b2SzdutFcFB2FkwMIJOG6qfteXOa1nHZ48tyefuwyfT9s6wtzZ3t7eZse2DR2I228TtHXzuWCx9g8MtK5cuHCZTH4tiHEOa4xFngvTyS8f35d6enomiCi4/foEXBkZaQuukChL4FYA2Whd7YcC4gEdW3CpdL3LtGAVCVYJywEyTpAuJKeMOKXZs/Bw947C50KhUFOG4cwz35cjWNBlHGeD53n3xsfHP/T19U1qciggar8Fa4I3PHobIotBWBtc2hSiChyZxVzM53Pv7FVH6Tp3uVy+g0r1ImD2GjIrQGYIxjnfuXTZGICS5k/bBwJoubwEFX4TLah9EXomJGMA3za+f9913Yl4TnzsDQ+vE6YTZOjHh4ngibstt1pzQwd04F0bPStEBpXqRoBeQ/AKghfBnOEKgS+Q7z91Xfdz/HGKg8Ox7z8iYD9z6wqTkZFgnvhMGP9VZ2or1XVkPM9z0mytSfVsHa1RLBZbLoyNzUnK+ydz3wC6I9x+lwbngwAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-poly-draw{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEjglo9eZgwAAAc5JREFUWMPt1zFrU1EUB/DfS4OmVTGDIChCP4BgnQXRxVHqIJUupp9AB8VBQcRBQUXIB9DWQoMRiXZzcnQSA34A7aAuHSJKkgo2LvfBrU3aJnlYkBy4vHcP557zP/9z3r33JdXa647N0kHSZd5Nn0rSxc8G3cXp85sMcnZZ8vge3osZ+l3vB8CWFA0iL14t79h210swAjACMAIwAjACkB90D/8/GchI9ve4nPwTBh5E9ws7OepzGWb9EddSn51Op9ZstadSg4VK1UKlKkmSDSMLALewiuNh/hVJq71Wxttmqz0dG88vPc+MgWP4grvYG3SLOBrZFFFrttqPe4HIDxh4GSei+98iSlusuYopXEAjBtEPA3tQwUpwluAbDm4TPJUz+BTW9l2Ce6G7L0X/Bw8D3T/7SKKIDzHg7QCcxjvcQAEtXAnrrg/RP0/DKPbqgcN4iVOR7gcO4dcQgRuoh7HSqwlP4n20m63jJu5n8MkWMYfP3UowhzdR8FU8w9iQwevBdyq3/27CMRzAE5yLuvsRLg+ZcR1nJ8YL81HWJUzGAPaFZwe/Q5MdyYDyNHgjzO90YyGHtVDncuiJchaHw8R4oREFV5qdiVmYLM3OgD9k5209/atmIAAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-point-draw{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEiERGWPELgAAA4RJREFUWMO1lr1uG1cQhb9ztdRSP7AF1QxgwKlcuZSqRC9gWUUUINWqTh5AnaFOnVPEteQmRuhCURqWsSqqc9IolREXdEvQBElxtdw7KURSFEVKu4w8wAKLxdw9Z+bMnRmZGXfZ29//II8th4WwGVNyIoQLYB5vxA9Caq04iUd9A+7ZlsNC2I7TdSd2hZXMJKlnTqp9jtl/GBaqoyQ0noFKpUIzBicYYc+DEFpxkglc4oVJa5gvDn8v1xV2irG3FM4NSVwjUKlUaMcpJhCGmSEJQ6QGD8M5WnHCd8+f3QCXpPLx8WNwv0j6Bm9FMK7FJ3WBE+R/2t7c/GBmFvSBrzRTCsyTDjXrxUgEMtpxynJYmJoBJ4VAybwVARgvL7Oik0okCodnKpVKX7P0leiVMb0VvbJT+upznK4vh0GIeQwwQStJkHQD3MwsCALTJRG7Qrdrj5m/djgYaIa0hlkRdJk26XEgC9txurccBtVW3IudBImmZuACUP+ZlIDBt9FKcubYNTcAH/X0RYM1E7utJPlqe+uZzPxUcEkiSS4sTT95n15Mud0xWC0o2PAWOCdK3KYZlFxfM+tHOcnMzNr1es18ug+cgsVjP4yBU/Ppfrter1m/+l0+zYygML1xRVHU7TSb1cSzBzoBzszsH+AMdJJ49jrNZjWKou6wBnwOzcyndBpNbuueURR1Dw8Pq35p9cc5p/Dy9Dypt7jXrtdGwQECS9NPhr6Gq6txUzNigE6zydLK6lTw12/KT4FGFEUfJX2YJNONq5tVs4ODA7sD/DnwJ/BoADZuE3tHFs12dna6d4C/BI6AlbyzI8ii2TTw12/KK33gb2cdXsNZoAntbZC2SeO4c9592k/5eNQbiwvFd1kJuFGwLJr1wSPg/SwpvyFBHufOeXcFeAlE97U/uCxOY+P3b+Bn4B3Q+L8EdJfD4a+/AbC4UBzPxiPg3wlHZquB28Cn2IuR9x3gr3uV4DbwfvSDOvi4uFA8BDZmIRHkjHpS9Ht9iRqd8+5G3g05mAGcQbsdiX5QJ428G7Kygo8XYdb1/K4NWVmjzkNge2sz84bs+ELmpDDLtqWsNZBXgvmw8CTtpWVMT7x5YWBjLARnwZfKQNYN2U2LPvrh+5nBt7c2M2/It9bArCTKR8eZN+SJ13AScPnoODeRdqNenH+wul5w2gUr2WUjMFAt8bZ/0axX/wNnv4H8vTFb1QAAAABJRU5ErkJggg==");}.bk-root .bk-tool-icon-poly-edit{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gELFi46qJmxxAAABV9JREFUWMOdl19vFFUYxn9n9u9sCyylUIzWUoMQBAWCMdEEIt6xIRQSLIEKtvHe6AcA4yeQb7CAUNJy0daLeomJN8SEULAC2kBBapBKoLvbmdl/c14vdmY7u91tF95kknPOnHmf95znPc97Ro2OTeBbdjFDT3c32ZxVHUOE9kSMB0/m6ExuoJn1H+ur6Y+OTfD50SMN5168OgrAlyf7CfuD+z7+iDs3p8hkLUQ0iFQ/yFl5Nm/qonfHVva+s32Zw9GxCYILsZ08tpNfBhbs+1YN4OH9+7huGdECSBVfqUosbsllfmauBqiR+cCNwOr7AEo8pPHJnymXykhg5fUWjoQpl0vVvhZhbSzGoUOHqgBlt6B6uruj2Zy1E9jo0fhfeyL2x4Mnc8VErK0KUEOB64JSyptfG4RSytsJjUJVxw2lsFy3urL9nx1Qd25ObctkrVMi+jQivd7U2ZyV/3Hzpq7h3h1b/7p9Y0o8v8rwAbTWrGpSocN/FGDlbAI0Rl23PCBan0Ok158H9Ipwzi25A/Mzc9Gl/BYx/E4kYqC1NKRARNAaDCNUM27Z+Zr+ouXs0q4+LSLBHPYCFkTkC6uU39kwCdsS7WRKmaYUiAhdnZ3MPX2K4+QjQI+C94A93rMzm8ltMwyDeDzWjMZeEb2pYQDdW3vITU2jtUZ5QThOPgm8C7wP7J15OPsBsB3oWpGnVWisCeDS1VHj4vBI92+/3tgB7Ab2AruAXiDBK5oIOkhtkEYRNRuJhObrd8Dl9ewf4D5wG7hVLpen29vb5wzD+BrkbBMaL3d1dk5nsrnlFDTTFWAWmAZueWD3gCemGde2k2fw1Al1YXhEvjozoO49eczdqekrWmsc2zlrmvEKOGoW1GUjFLqSk2KpJrCLwyMCPAP+BO54QL8DM6YZX/ClsP9YnwKkXnIBP4jdIpJRpdJTCYdMwwi98KU0Hjc/dDILNyUcwTCWdOSMJ0TRmBktGRhLugu0xyLk7CIqVNm+0bGJptl1YXikD0grpY4Rjc4a8Fbgdab/6OGbAJeCUuyJnnHmZH9pbSyGuBXV8NUwlUpR1EWyixmSyTWEwqGlJ2Swbo2JXbAAfgDGgGQA9I1A9t1tlq0AxrXxn0ilUpw4fhQqYkH/sT41OTnJJwf2s6FjI5mshdYa7bqVR2uezr9MJmJt14FvGrh/O9D+e6UkM/xyCuCqEKCYnJyUTKFQrZDHjxzGshwWLQcRsOz8Hi85P23id0ug/XilAMLBmm4tPGdoaKjSH5+oAGrhwvBI9SjZTn4QSK9yenoD7dlrExPoJlXW8G8ytpNHxRKk02lGxsdRKFwXLNvx5yY94HQLGhGk4LFCYQSqaE0AwWM1eOoEbR0dKBSW7bC4mKuffxs4D/wCLKwQQPAUzIkslfp6cVomROWSolh0GjldAM4nzDi2k9/i5UAzC9aKfwNJ3zgJg9YEvN6+C7SHgKm69+sD7RfNnKTTaZRPQfAut4oFV//IS7gkcB34VlVo8kGzphlfB+DU+TfNGBpZtRastvrvARJmfMF28ge9sc2B9/PNnCilMIDwK6y8/ow/Ai4kvILTljAXvDvEvrqKSUs60KolzPjBxspavQD2tKqCAGF/Ba+xE/Wbilu54wZV8NEKF5fXzQHl/bh4hUsE0WAXSlDMYcQSrQXgCmsTseXHsJkNnjqBFGwKJaHsKlxtUHYVhbLCzr1kaOA4bcn1y1Swmb+iLpJKpVrfgdpfsiVVCYcgluwgnU7jEgJ4s5UkLFtWYyHyEg0/N1q1tmQH+YXnAMFr97Nmv3p+0QsHQRsF8qpBOE5+rb9Nkaj50tVQKjqh4OU3GNL/1/So3vuUgbAAAAAASUVORK5CYII=");}.bk-root .bk-tool-icon-line-edit{background-image:url("data:image/png;base64, ");}`;
},
/* styles/menus.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.menu_icon = "bk-menu-icon";
    exports.context_menu = "bk-context-menu";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.divider = "bk-divider";
    exports.active = "bk-active";
    exports.menu = "bk-menu";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.caret = "bk-caret";
    exports.down = "bk-down";
    exports.up = "bk-up";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.default = `.bk-root .bk-menu-icon{width:28px;height:28px;background-size:60%;background-color:transparent;background-repeat:no-repeat;background-position:center center;}.bk-root .bk-context-menu{position:absolute;display:inline-flex;display:-webkit-inline-flex;flex-wrap:nowrap;-webkit-flex-wrap:nowrap;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;width:auto;height:auto;z-index:100;cursor:pointer;font-size:12px;background-color:#fff;border:1px solid #ccc;border-radius:4px;box-shadow:0 6px 12px rgba(0, 0, 0, 0.175);}.bk-root .bk-context-menu.bk-horizontal{flex-direction:row;-webkit-flex-direction:row;}.bk-root .bk-context-menu.bk-vertical{flex-direction:column;-webkit-flex-direction:column;}.bk-root .bk-context-menu > .bk-divider{cursor:default;overflow:hidden;background-color:#e5e5e5;}.bk-root .bk-context-menu.bk-horizontal > .bk-divider{width:1px;margin:5px 0;}.bk-root .bk-context-menu.bk-vertical > .bk-divider{height:1px;margin:0 5px;}.bk-root .bk-context-menu > :not(.bk-divider){border:1px solid transparent;}.bk-root .bk-context-menu > :not(.bk-divider).bk-active{border-color:#26aae1;}.bk-root .bk-context-menu > :not(.bk-divider):hover{background-color:#f9f9f9;}.bk-root .bk-context-menu.bk-horizontal > :not(.bk-divider):first-child{border-top-left-radius:4px;border-bottom-left-radius:4px;}.bk-root .bk-context-menu.bk-horizontal > :not(.bk-divider):last-child{border-top-right-radius:4px;border-bottom-right-radius:4px;}.bk-root .bk-context-menu.bk-vertical > :not(.bk-divider):first-child{border-top-left-radius:4px;border-top-right-radius:4px;}.bk-root .bk-context-menu.bk-vertical > :not(.bk-divider):last-child{border-bottom-left-radius:4px;border-bottom-right-radius:4px;}.bk-root .bk-menu{position:absolute;left:0;width:100%;z-index:100;cursor:pointer;font-size:12px;background-color:#fff;border:1px solid #ccc;border-radius:4px;box-shadow:0 6px 12px rgba(0, 0, 0, 0.175);}.bk-root .bk-menu.bk-above{bottom:100%;}.bk-root .bk-menu.bk-below{top:100%;}.bk-root .bk-menu > .bk-divider{height:1px;margin:7.5px 0;overflow:hidden;background-color:#e5e5e5;}.bk-root .bk-menu > :not(.bk-divider){padding:6px 12px;}.bk-root .bk-menu > :not(.bk-divider):hover,.bk-root .bk-menu > :not(.bk-divider).bk-active{background-color:#e6e6e6;}.bk-root .bk-caret{display:inline-block;vertical-align:middle;width:0;height:0;margin:0 5px;}.bk-root .bk-caret.bk-down{border-top:4px solid;}.bk-root .bk-caret.bk-up{border-bottom:4px solid;}.bk-root .bk-caret.bk-down,.bk-root .bk-caret.bk-up{border-right:4px solid transparent;border-left:4px solid transparent;}.bk-root .bk-caret.bk-left{border-right:4px solid;}.bk-root .bk-caret.bk-right{border-left:4px solid;}.bk-root .bk-caret.bk-left,.bk-root .bk-caret.bk-right{border-top:4px solid transparent;border-bottom:4px solid transparent;}`;
},
/* core/util/menus.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const dom_1 = require(43) /* ../dom */;
    const iterator_1 = require(245) /* ./iterator */;
    const menus = tslib_1.__importStar(require(243) /* ../../styles/menus.css */);
    class ContextMenu {
        constructor(items, options = {}) {
            this.items = items;
            this.options = options;
            this.el = dom_1.div();
            this._open = false;
            this._item_click = (i) => {
                var _a;
                (_a = this.items[i]) === null || _a === void 0 ? void 0 : _a.handler();
                this.hide();
            };
            this._on_mousedown = (event) => {
                var _a, _b;
                const { target } = event;
                if (target instanceof Node && this.el.contains(target))
                    return;
                if ((_b = (_a = this.options).prevent_hide) === null || _b === void 0 ? void 0 : _b.call(_a, event))
                    return;
                this.hide();
            };
            this._on_keydown = (event) => {
                if (event.keyCode == dom_1.Keys.Esc)
                    this.hide();
            };
            this._on_blur = () => {
                this.hide();
            };
            dom_1.undisplay(this.el);
        }
        get is_open() {
            return this._open;
        }
        get can_open() {
            return this.items.length != 0;
        }
        remove() {
            dom_1.remove(this.el);
            this._unlisten();
        }
        _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) {
            const parent_el = this.el.parentElement;
            if (parent_el != null) {
                const parent = parent_el.getBoundingClientRect();
                this.el.style.left = at.left != null ? `${at.left - parent.left}px` : "";
                this.el.style.top = at.top != null ? `${at.top - parent.top}px` : "";
                this.el.style.right = at.right != null ? `${parent.right - at.right}px` : "";
                this.el.style.bottom = at.bottom != null ? `${parent.bottom - at.bottom}px` : "";
            }
        }
        /*
        styles(): string[] {
          return [...super.styles(), menus_css]
        }
        */
        render() {
            var _a, _b;
            dom_1.empty(this.el, true);
            const orientation = (_a = this.options.orientation) !== null && _a !== void 0 ? _a : "vertical";
            dom_1.classes(this.el).add("bk-context-menu", `bk-${orientation}`);
            for (const [item, i] of iterator_1.enumerate(this.items)) {
                let el;
                if (item == null) {
                    el = dom_1.div({ class: menus.divider });
                }
                else if (item.if != null && !item.if()) {
                    continue;
                }
                else {
                    const icon = item.icon != null ? dom_1.div({ class: ["bk-menu-icon", item.icon] }) : null;
                    el = dom_1.div({ class: ((_b = item.active) === null || _b === void 0 ? void 0 : _b.call(item)) ? "bk-active" : null, title: item.tooltip }, icon, item.label);
                }
                el.addEventListener("click", () => this._item_click(i));
                this.el.appendChild(el);
            }
        }
        show(at) {
            if (this.items.length == 0)
                return;
            if (!this._open) {
                this.render();
                if (this.el.children.length == 0)
                    return;
                this._position(at !== null && at !== void 0 ? at : { left: 0, top: 0 });
                dom_1.display(this.el);
                this._listen();
                this._open = true;
            }
        }
        hide() {
            if (this._open) {
                this._open = false;
                this._unlisten();
                dom_1.undisplay(this.el);
            }
        }
        toggle(at) {
            this._open ? this.hide() : this.show(at);
        }
    }
    exports.ContextMenu = ContextMenu;
    ContextMenu.__name__ = "ContextMenu";
},
/* core/util/iterator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(9) /* ./array */;
    function* enumerate(seq) {
        let i = 0;
        for (const item of seq) {
            yield [item, i++];
        }
    }
    exports.enumerate = enumerate;
    // 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 = array_1.range(r);
        yield indices.map((i) => seq[i]);
        while (true) {
            let k;
            for (const i of array_1.reversed(array_1.range(r))) {
                if (indices[i] != i + n - r) {
                    k = i;
                    break;
                }
            }
            if (k == null)
                return;
            indices[k] += 1;
            for (const j of 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 array_1.range(seq.length + 1)) {
            yield* combinations(seq, k);
        }
    }
    exports.subsets = subsets;
},
/* models/tools/on_off_button.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const button_tool_1 = require(238) /* ./button_tool */;
    const toolbars = tslib_1.__importStar(require(241) /* ../../styles/toolbar.css */);
    const dom_1 = require(43) /* ../../core/dom */;
    class OnOffButtonView extends button_tool_1.ButtonToolButtonView {
        render() {
            super.render();
            dom_1.classes(this.el).toggle(toolbars.active, this.model.active);
        }
        _clicked() {
            const { active } = this.model;
            this.model.active = !active;
        }
    }
    exports.OnOffButtonView = OnOffButtonView;
    OnOffButtonView.__name__ = "OnOffButtonView";
},
/* models/tools/inspectors/inspect_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const button_tool_1 = require(238) /* ../button_tool */;
    const on_off_button_1 = require(246) /* ../on_off_button */;
    class InspectToolView extends button_tool_1.ButtonToolView {
    }
    exports.InspectToolView = InspectToolView;
    InspectToolView.__name__ = "InspectToolView";
    class InspectTool extends button_tool_1.ButtonTool {
        constructor(attrs) {
            super(attrs);
            this.event_type = "move";
        }
        static init_InspectTool() {
            this.prototype.button_view = on_off_button_1.OnOffButtonView;
            this.define(({ Boolean }) => ({
                toggleable: [Boolean, true],
            }));
            this.override({
                active: true,
            });
        }
    }
    exports.InspectTool = InspectTool;
    InspectTool.__name__ = "InspectTool";
    InspectTool.init_InspectTool();
},
/* models/tools/toolbar_base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const logging_1 = require(19) /* ../../core/logging */;
    const dom_1 = require(43) /* ../../core/dom */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const dom_view_1 = require(240) /* ../../core/dom_view */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const canvas_1 = require(249) /* ../../core/util/canvas */;
    const bbox_1 = require(99) /* ../../core/util/bbox */;
    const model_1 = require(53) /* ../../model */;
    const tool_1 = require(236) /* ./tool */;
    const gesture_tool_1 = require(237) /* ./gestures/gesture_tool */;
    const action_tool_1 = require(251) /* ./actions/action_tool */;
    const help_tool_1 = require(252) /* ./actions/help_tool */;
    const inspect_tool_1 = require(247) /* ./inspectors/inspect_tool */;
    const toolbar_css_1 = tslib_1.__importStar(require(241) /* ../../styles/toolbar.css */), toolbars = toolbar_css_1;
    const logo_css_1 = tslib_1.__importStar(require(253) /* ../../styles/logo.css */), logos = logo_css_1;
    class ToolbarViewModel extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_ToolbarViewModel() {
            this.define(({ Boolean, Nullable }) => ({
                _visible: [Nullable(Boolean), null],
                autohide: [Boolean, false],
            }));
        }
        get visible() {
            return (!this.autohide) ? true : (this._visible == null) ? false : this._visible;
        }
    }
    exports.ToolbarViewModel = ToolbarViewModel;
    ToolbarViewModel.__name__ = "ToolbarViewModel";
    ToolbarViewModel.init_ToolbarViewModel();
    class ToolbarBaseView extends dom_view_1.DOMView {
        constructor() {
            super(...arguments);
            this.layout = { bbox: new bbox_1.BBox() };
        }
        initialize() {
            super.initialize();
            this._tool_button_views = new Map();
            this._toolbar_view_model = new ToolbarViewModel({ autohide: this.model.autohide });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_tool_button_views();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.tools.change, async () => {
                await this._build_tool_button_views();
                this.render();
            });
            this.connect(this.model.properties.autohide.change, () => {
                this._toolbar_view_model.autohide = this.model.autohide;
                this._on_visible_change();
            });
            this.connect(this._toolbar_view_model.properties._visible.change, () => this._on_visible_change());
        }
        styles() {
            return [...super.styles(), toolbar_css_1.default, logo_css_1.default];
        }
        remove() {
            build_views_1.remove_views(this._tool_button_views);
            super.remove();
        }
        async _build_tool_button_views() {
            const tools = (this.model._proxied_tools != null ? this.model._proxied_tools : this.model.tools); // XXX
            await build_views_1.build_views(this._tool_button_views, tools, { parent: this }, (tool) => tool.button_view); // XXX: no ButtonToolButton model
        }
        set_visibility(visible) {
            if (visible != this._toolbar_view_model._visible) {
                this._toolbar_view_model._visible = visible;
            }
        }
        _on_visible_change() {
            const visible = this._toolbar_view_model.visible;
            const hidden_class = toolbars.toolbar_hidden;
            if (this.el.classList.contains(hidden_class) && visible) {
                this.el.classList.remove(hidden_class);
            }
            else if (!visible) {
                this.el.classList.add(hidden_class);
            }
        }
        render() {
            dom_1.empty(this.el);
            this.el.classList.add(toolbars.toolbar);
            this.el.classList.add(toolbars[this.model.toolbar_location]);
            this._toolbar_view_model.autohide = this.model.autohide;
            this._on_visible_change();
            if (this.model.logo != null) {
                const gray = this.model.logo === "grey" ? logos.grey : null;
                const logo_el = dom_1.a({ href: "https://bokeh.org/", target: "_blank", class: [logos.logo, logos.logo_small, gray] });
                this.el.appendChild(logo_el);
            }
            for (const [, button_view] of this._tool_button_views) {
                button_view.render();
            }
            const bars = [];
            const el = (tool) => {
                return this._tool_button_views.get(tool).el;
            };
            const { gestures } = this.model;
            for (const gesture of object_1.values(gestures)) {
                bars.push(gesture.tools.map(el));
            }
            bars.push(this.model.actions.map(el));
            bars.push(this.model.inspectors.filter((tool) => tool.toggleable).map(el));
            for (const bar of bars) {
                if (bar.length !== 0) {
                    const el = dom_1.div({ class: toolbars.button_bar }, bar);
                    this.el.appendChild(el);
                }
            }
        }
        update_layout() { }
        update_position() { }
        after_layout() {
            this._has_finished = true;
        }
        export(type, hidpi = true) {
            const output_backend = type == "png" ? "canvas" : "svg";
            const canvas = new canvas_1.CanvasLayer(output_backend, hidpi);
            canvas.resize(0, 0);
            return canvas;
        }
    }
    exports.ToolbarBaseView = ToolbarBaseView;
    ToolbarBaseView.__name__ = "ToolbarBaseView";
    function create_gesture_map() {
        return {
            pan: { tools: [], active: null },
            scroll: { tools: [], active: null },
            pinch: { tools: [], active: null },
            tap: { tools: [], active: null },
            doubletap: { tools: [], active: null },
            press: { tools: [], active: null },
            pressup: { tools: [], active: null },
            rotate: { tools: [], active: null },
            move: { tools: [], active: null },
            multi: { tools: [], active: null },
        };
    }
    class ToolbarBase extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_ToolbarBase() {
            this.prototype.default_view = ToolbarBaseView;
            this.define(({ Boolean, Array, Ref, Nullable }) => ({
                tools: [Array(Ref(tool_1.Tool)), []],
                logo: [Nullable(enums_1.Logo), "normal"],
                autohide: [Boolean, false],
            }));
            this.internal(({ Array, Struct, Ref, Nullable }) => {
                const GestureEntry = Struct({
                    tools: Array(Ref(gesture_tool_1.GestureTool)),
                    active: Nullable(Ref(tool_1.Tool)),
                });
                const GestureMap = Struct({
                    pan: GestureEntry,
                    scroll: GestureEntry,
                    pinch: GestureEntry,
                    tap: GestureEntry,
                    doubletap: GestureEntry,
                    press: GestureEntry,
                    pressup: GestureEntry,
                    rotate: GestureEntry,
                    move: GestureEntry,
                    multi: GestureEntry,
                });
                return {
                    gestures: [GestureMap, create_gesture_map],
                    actions: [Array(Ref(action_tool_1.ActionTool)), []],
                    inspectors: [Array(Ref(inspect_tool_1.InspectTool)), []],
                    help: [Array(Ref(help_tool_1.HelpTool)), []],
                    toolbar_location: [enums_1.Location, "right"],
                };
            });
        }
        initialize() {
            super.initialize();
            this._init_tools();
        }
        _init_tools() {
            // The only purpose of this function is to avoid unnecessary property churning.
            const tools_changed = function (old_tools, new_tools) {
                if (old_tools.length != new_tools.length) {
                    return true;
                }
                const new_ids = new Set(new_tools.map(t => t.id));
                return array_1.some(old_tools, t => !new_ids.has(t.id));
            };
            const new_inspectors = this.tools.filter(t => t instanceof inspect_tool_1.InspectTool);
            if (tools_changed(this.inspectors, new_inspectors)) {
                this.inspectors = new_inspectors;
            }
            const new_help = this.tools.filter(t => t instanceof help_tool_1.HelpTool);
            if (tools_changed(this.help, new_help)) {
                this.help = new_help;
            }
            const new_actions = this.tools.filter(t => t instanceof action_tool_1.ActionTool);
            if (tools_changed(this.actions, new_actions)) {
                this.actions = new_actions;
            }
            const check_event_type = (et, tool) => {
                if (!(et in this.gestures)) {
                    logging_1.logger.warn(`Toolbar: unknown event type '${et}' for tool: ${tool}`);
                }
            };
            const new_gestures = create_gesture_map();
            for (const tool of this.tools) {
                if (tool instanceof gesture_tool_1.GestureTool && tool.event_type) {
                    if (types_1.isString(tool.event_type)) {
                        new_gestures[tool.event_type].tools.push(tool);
                        check_event_type(tool.event_type, tool);
                    }
                    else {
                        new_gestures.multi.tools.push(tool);
                        for (const et of tool.event_type) {
                            check_event_type(et, tool);
                        }
                    }
                }
            }
            for (const et of Object.keys(new_gestures)) {
                const gm = this.gestures[et];
                if (tools_changed(gm.tools, new_gestures[et].tools)) {
                    gm.tools = new_gestures[et].tools;
                }
                if (gm.active && array_1.every(gm.tools, t => t.id != gm.active.id)) {
                    gm.active = null;
                }
            }
        }
        get horizontal() {
            return this.toolbar_location === "above" || this.toolbar_location === "below";
        }
        get vertical() {
            return this.toolbar_location === "left" || this.toolbar_location === "right";
        }
        _active_change(tool) {
            const { event_type } = tool;
            if (event_type == null)
                return;
            const event_types = types_1.isString(event_type) ? [event_type] : event_type;
            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.ToolbarBase = ToolbarBase;
    ToolbarBase.__name__ = "ToolbarBase";
    ToolbarBase.init_ToolbarBase();
},
/* core/util/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const svg_1 = require(250) /* ./svg */;
    const bbox_1 = require(99) /* ./bbox */;
    const dom_1 = require(43) /* ../dom */;
    function fixup_line_dash(ctx) {
        if (typeof ctx.lineDash === "undefined") {
            Object.defineProperty(ctx, "lineDash", {
                get: () => ctx.getLineDash(),
                set: (segments) => ctx.setLineDash(segments),
            });
        }
    }
    function fixup_image_smoothing(ctx) {
        ctx.setImageSmoothingEnabled = (value) => {
            ctx.imageSmoothingEnabled = value;
            ctx.mozImageSmoothingEnabled = value;
            ctx.oImageSmoothingEnabled = value;
            ctx.webkitImageSmoothingEnabled = value;
            ctx.msImageSmoothingEnabled = value;
        };
        ctx.getImageSmoothingEnabled = () => {
            const val = ctx.imageSmoothingEnabled;
            return val != null ? val : true;
        };
    }
    function fixup_ellipse(ctx) {
        // implementing the ctx.ellipse function with bezier curves
        // we don't implement the startAngle, endAngle and anticlockwise arguments.
        function ellipse_bezier(x, y, radiusX, radiusY, rotation, _startAngle, _endAngle, anticlockwise = false) {
            const c = 0.551784; // see http://www.tinaja.com/glib/ellipse4.pdf
            ctx.translate(x, y);
            ctx.rotate(rotation);
            let rx = radiusX;
            let ry = radiusY;
            if (anticlockwise) {
                rx = -radiusX;
                ry = -radiusY;
            }
            ctx.moveTo(-rx, 0); // start point of first curve
            ctx.bezierCurveTo(-rx, ry * c, -rx * c, ry, 0, ry);
            ctx.bezierCurveTo(rx * c, ry, rx, ry * c, rx, 0);
            ctx.bezierCurveTo(rx, -ry * c, rx * c, -ry, 0, -ry);
            ctx.bezierCurveTo(-rx * c, -ry, -rx, -ry * c, -rx, 0);
            ctx.rotate(-rotation);
            ctx.translate(-x, -y);
        }
        if (!ctx.ellipse)
            ctx.ellipse = ellipse_bezier;
    }
    function fixup_ctx(ctx) {
        fixup_line_dash(ctx);
        fixup_image_smoothing(ctx);
        fixup_ellipse(ctx);
    }
    const style = {
        position: "absolute",
        top: "0",
        left: "0",
        width: "100%",
        height: "100%",
    };
    class CanvasLayer {
        constructor(backend, hidpi) {
            this.backend = backend;
            this.hidpi = hidpi;
            this.pixel_ratio = 1;
            this.bbox = new bbox_1.BBox();
            switch (backend) {
                case "webgl":
                case "canvas": {
                    this._el = this._canvas = dom_1.canvas({ style });
                    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 = dom_1.div({ style }, this._canvas);
                    break;
                }
            }
            fixup_ctx(this._ctx);
        }
        get canvas() {
            return this._canvas;
        }
        get ctx() {
            return this._ctx;
        }
        get el() {
            return this._el;
        }
        resize(width, height) {
            this.bbox = new bbox_1.BBox({ left: 0, top: 0, width, height });
            const target = this._ctx instanceof svg_1.SVGRenderingContext2D ? this._ctx : this.canvas;
            target.width = width * this.pixel_ratio;
            target.height = height * this.pixel_ratio;
        }
        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) {
                if (_canvas.msToBlob != null) {
                    return Promise.resolve(_canvas.msToBlob());
                }
                else {
                    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(168) /* ./affine */;
    const types_1 = require(8) /* ./types */;
    const dom_1 = require(43) /* ../dom */;
    // helper function that generates a random string
    function randomString(holder) {
        if (!holder) {
            throw new Error("cannot create a random attribute name for an undefined object");
        }
        const chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        let randomstring = "";
        do {
            randomstring = "";
            for (let i = 0; i < 12; i++) {
                randomstring += chars[Math.floor(Math.random() * chars.length)];
            }
        } while (holder[randomstring]);
        return randomstring;
    }
    // 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) {
        var _a;
        // TODO: support rtl languages
        const mapping = { left: "start", right: "end", center: "middle", start: "start", end: "end" };
        return (_a = mapping[textAlign]) !== null && _a !== void 0 ? _a : mapping.start;
    }
    // helper function to map canvas-textBaseline to svg-dominantBaseline
    function getDominantBaseline(textBaseline) {
        var _a;
        // INFO: not supported in all browsers
        const mapping = { alphabetic: "alphabetic", hanging: "hanging", top: "text-before-edge", bottom: "text-after-edge", middle: "central" };
        return (_a = mapping[textBaseline]) !== null && _a !== void 0 ? _a : mapping.alphabetic;
    }
    // Unpack entities lookup where the numbers are in radix 32 to reduce the size
    // entity mapping courtesy of tinymce
    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",
        },
        fillStyle: {
            svgAttr: "fill",
            canvas: "#000000",
            svg: null,
            apply: "fill",
        },
        lineCap: {
            svgAttr: "stroke-linecap",
            canvas: "butt",
            svg: "butt",
            apply: "stroke",
        },
        lineJoin: {
            svgAttr: "stroke-linejoin",
            canvas: "miter",
            svg: "miter",
            apply: "stroke",
        },
        miterLimit: {
            svgAttr: "stroke-miterlimit",
            canvas: 10,
            svg: 4,
            apply: "stroke",
        },
        lineWidth: {
            svgAttr: "stroke-width",
            canvas: 1,
            svg: 1,
            apply: "stroke",
        },
        globalAlpha: {
            svgAttr: "opacity",
            canvas: 1,
            svg: 1,
            apply: "fill stroke",
        },
        font: {
            // font converts to multiple svg attributes, there is custom logic for this
            canvas: "10px sans-serif",
        },
        shadowColor: {
            canvas: "#000000",
        },
        shadowOffsetX: {
            canvas: 0,
        },
        shadowOffsetY: {
            canvas: 0,
        },
        shadowBlur: {
            canvas: 0,
        },
        textAlign: {
            canvas: "start",
        },
        textBaseline: {
            canvas: "alphabetic",
        },
        lineDash: {
            svgAttr: "stroke-dasharray",
            canvas: [],
            svg: null,
            apply: "stroke",
        },
    };
    class CanvasGradient {
        constructor(gradientNode, ctx) {
            this.__root = gradientNode;
            this.__ctx = ctx;
        }
        /**
         * Adds a color stop to the gradient root
         */
        addColorStop(offset, color) {
            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;
        }
    }
    CanvasPattern.__name__ = "CanvasPattern";
    /**
     * The mock canvas context
     * @param o - options include:
     * ctx - existing Context2D to wrap around
     * width - width of your canvas (defaults to 500)
     * height - height of your canvas (defaults to 500)
     * document - the document object (defaults to the current document)
     */
    class SVGRenderingContext2D /*implements CanvasRenderingContext2D*/ {
        constructor(options) {
            var _a, _b, _c;
            this.__currentPosition = null;
            this._transform = new affine_1.AffineTransform();
            this._clip_path = null;
            this.__document = (_a = options === null || options === void 0 ? void 0 : options.document) !== null && _a !== void 0 ? _a : document;
            // allow passing in an existing context to wrap around
            // if a context is passed in, we know a canvas already exist
            if (options === null || options === void 0 ? void 0 : options.ctx) {
                this.__ctx = options.ctx;
            }
            else {
                this.__canvas = this.__document.createElement("canvas");
                this.__ctx = this.__canvas.getContext("2d");
            }
            this.__setDefaultStyles();
            this.__stack = [];
            // the root svg element
            this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg");
            this.__root.setAttribute("version", "1.1");
            this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg");
            this.__root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
            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 = {};
            // defs tag
            this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs");
            this.__root.appendChild(this.__defs);
        }
        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}`);
        }
        /**
         * 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) {
            var _a;
            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 ((_a = style.apply) === null || _a === void 0 ? void 0 : _a.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[id] = 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") && 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})`);
                            // should take globalAlpha here
                            let opacity = parseFloat(a);
                            const globalAlpha = this.globalAlpha;
                            if (globalAlpha != null) {
                                opacity *= globalAlpha;
                            }
                            currentElement.setAttribute(style.svgAttr + "-opacity", `${opacity}`);
                        }
                        else {
                            let attr = style.svgAttr;
                            if (keys[i] === 'globalAlpha') {
                                attr = type + '-' + style.svgAttr;
                                if (currentElement.getAttribute(attr)) {
                                    // fill-opacity or stroke-opacity has already been set by stroke or fill.
                                    continue;
                                }
                            }
                            // otherwise only update attribute if right type, and not svg default
                            currentElement.setAttribute(attr, `${value}`);
                        }
                    }
                }
            }
        }
        /**
          * Returns the serialized value of the svg so far
          * @param fixNamedEntities - Standalone SVG doesn't support named entities, which document.createTextNode encodes.
          *                           If true, we attempt to find all named entities and encode it as a numeric entity.
          * @return serialized svg
          */
        get_serialized_svg(fixNamedEntities = false) {
            let serialized = new XMLSerializer().serializeToString(this.__root);
            // IE search for a duplicate xmnls because they didn't implement setAttributeNS correctly
            const xmlns = /xmlns="http:\/\/www\.w3\.org\/2000\/svg".+xmlns="http:\/\/www\.w3\.org\/2000\/svg/gi;
            if (xmlns.test(serialized)) {
                serialized = serialized.replace('xmlns="http://www.w3.org/2000/svg', 'xmlns:xlink="http://www.w3.org/1999/xlink');
            }
            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);
        }
        _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;
            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;
            if (this.__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;
            const x0 = this.__currentPosition.x;
            const y0 = this.__currentPosition.y;
            // Negative values for radius must cause the implementation to throw an IndexSizeError exception.
            if (radius < 0) {
                throw new Error("IndexSizeError: The radius provided (" + radius + ") is negative.");
            }
            // If the point (x0, y0) is equal to the point (x1, y1),
            // or if the point (x1, y1) is equal to the point (x2, y2),
            // or if the radius radius is zero,
            // then the method must add the point (x1, y1) to the subpath,
            // and connect that point to the previous point (x0, y0) by a straight line.
            if (((x0 === x1) && (y0 === y1)) || ((x1 === x2) && (y1 === y2)) || (radius === 0)) {
                this.lineTo(x1, y1);
                return;
            }
            function normalize([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);
            }
        }
        /**
          * Sets fill properties on the current element
          */
        fill(fill_rule) {
            if (this.__currentElement.nodeName === "path") {
                this.__currentElement.setAttribute("paint-order", "stroke");
            }
            // XXX: hack (?) to allow fill and hatch visuals on same canvas path
            if (this.__currentElement.getAttribute("fill") != "none") {
                const path = this.__currentElement.cloneNode(true);
                this.__root.appendChild(path);
                this.__currentElement = path;
            }
            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;
            if (this.__currentElement.nodeName !== "path") {
                this.beginPath();
            }
            this.moveTo(x, y);
            this.lineTo(x + width, y);
            this.lineTo(x + width, y + height);
            this.lineTo(x, y + height);
            this.lineTo(x, y);
        }
        /**
          * adds a rectangle element
          */
        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() {
            dom_1.empty(this.__defs);
            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);
        }
        /**
          * 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: randomString(this.__ids),
                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: randomString(this.__ids),
                cx: `${tx1}px`,
                cy: `${ty1}px`,
                r: `${r1}px`,
                fx: `${tx0}px`,
                fy: `${ty0}px`,
                gradientUnits: "userSpaceOnUse",
            }, false);
            this.__defs.appendChild(grad);
            return new CanvasGradient(grad, this);
        }
        /**
          * Parses the font string and returns svg mapping
          */
        __parseFont() {
            var _a, _b, _c, _d, _e;
            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 fontPart = regex.exec(this.font);
            const data = {
                style: (_a = fontPart[1]) !== null && _a !== void 0 ? _a : 'normal',
                size: (_b = fontPart[4]) !== null && _b !== void 0 ? _b : '10px',
                family: (_c = fontPart[6]) !== null && _c !== void 0 ? _c : 'sans-serif',
                weight: (_d = fontPart[3]) !== null && _d !== void 0 ? _d : 'normal',
                decoration: (_e = fontPart[2]) !== null && _e !== void 0 ? _e : 'normal',
            };
            // canvas doesn't support underline natively, but we can pass this attribute
            if (this.__fontUnderline === "underline") {
                data.decoration = "underline";
            }
            // canvas also doesn't support linking, but we can pass this as well
            if (this.__fontHref != null) {
                data.href = this.__fontHref;
            }
            return data;
        }
        /**
          * Helper to link text fragments
          */
        __wrapTextLink(font, element) {
            if (font.href) {
                const a = this.__createElement("a");
                a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href);
                a.appendChild(element);
                return a;
            }
            return element;
        }
        /**
          * Fills or strokes text
          */
        __applyText(text, x, y, action) {
            const font = this.__parseFont();
            const textElement = 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);
            textElement.appendChild(this.__document.createTextNode(text));
            this._apply_transform(textElement);
            this.__currentElement = textElement;
            this.__applyStyleToCurrentElement(action);
            this.__root.appendChild(this.__wrapTextLink(font, textElement));
        }
        /**
          * Creates a text element
          */
        fillText(text, x, y) {
            if (text == null || !isFinite(x + y))
                return;
            this.__applyText(text, x, y, "fill");
        }
        /**
          * Strokes text
          */
        strokeText(text, x, y) {
            if (text == null || !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, startAngle, endAngle, counterClockwise = false) {
            if (!isFinite(x + y + radius + startAngle + endAngle))
                return;
            // in canvas no circle is drawn if no angle is provided.
            if (startAngle === endAngle) {
                return;
            }
            startAngle = startAngle % (2 * Math.PI);
            endAngle = endAngle % (2 * Math.PI);
            if (startAngle === endAngle) {
                // circle time! subtract some of the angle so svg is happy (svg elliptical arc can't draw a full circle)
                endAngle = ((endAngle + (2 * Math.PI)) - 0.001 * (counterClockwise ? -1 : 1)) % (2 * Math.PI);
            }
            const endX = x + radius * Math.cos(endAngle);
            const endY = y + radius * Math.sin(endAngle);
            const startX = x + radius * Math.cos(startAngle);
            const startY = y + radius * Math.sin(startAngle);
            const sweepFlag = counterClockwise ? 0 : 1;
            let largeArcFlag = 0;
            let diff = endAngle - startAngle;
            // https://github.com/gliffy/canvas2svg/issues/4
            if (diff < 0) {
                diff += 2 * Math.PI;
            }
            if (counterClockwise) {
                largeArcFlag = diff > Math.PI ? 0 : 1;
            }
            else {
                largeArcFlag = diff > Math.PI ? 1 : 0;
            }
            this.lineTo(startX, startY);
            const rx = radius;
            const ry = radius;
            const xAxisRotation = 0;
            const [tendX, tendY] = this._transform.apply(endX, endY);
            this.__addPathCommand(tendX, tendY, `A ${rx} ${ry} ${xAxisRotation} ${largeArcFlag} ${sweepFlag} ${tendX} ${tendY}`);
        }
        /**
          * Generates a ClipPath from the clip command.
          */
        clip() {
            const clip_path = this.__createElement("clipPath");
            const id = randomString(this.__ids);
            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;
                sw = image.width;
                sh = image.height;
                dw = sw;
                dh = sh;
            }
            else if (args.length == 4) {
                [dx, dy, dw, dh] = args;
                if (!isFinite(dx + dy + dw + dh))
                    return;
                sx = 0;
                sy = 0;
                sw = image.width;
                sh = image.height;
            }
            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)
                    scope = parent;
                else {
                    scope = this.__createElement("g");
                    this._apply_transform(scope, transform);
                    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[id] = id;
                                this.__defs.appendChild(def);
                            }
                        }
                    }
                    else {
                        scope.appendChild(child);
                    }
                }
            }
            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 (sx || sy || 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.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", url);
                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");
                // 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.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", image.toDataURL());
                parent.appendChild(svgImage);
            }
        }
        /**
          * Generates a pattern tag
          */
        createPattern(image, _repetition) {
            const pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern");
            const id = randomString(this.__ids);
            pattern.setAttribute("id", id);
            pattern.setAttribute("width", `${this._to_number(image.width)}`);
            pattern.setAttribute("height", `${this._to_number(image.height)}`);
            pattern.setAttribute("patternUnits", "userSpaceOnUse");
            if (image instanceof HTMLCanvasElement || image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                const img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image");
                const url = image instanceof HTMLCanvasElement ? image.toDataURL() : image.getAttribute("src");
                img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink: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);
                    }
                }
                //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);
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else {
                throw new Error("unsupported");
            }
            return new CanvasPattern(pattern, this);
        }
        setLineDash(dashArray) {
            if (dashArray && dashArray.length > 0) {
                this.lineDash = dashArray.join(",");
            }
            else {
                this.lineDash = null;
            }
        }
        _to_number(val) {
            return types_1.isNumber(val) ? val : val.baseVal.value;
        }
    }
    exports.SVGRenderingContext2D = SVGRenderingContext2D;
    SVGRenderingContext2D.__name__ = "SVGRenderingContext2D";
},
/* models/tools/actions/action_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const button_tool_1 = require(238) /* ../button_tool */;
    const signaling_1 = require(15) /* ../../../core/signaling */;
    class ActionToolButtonView extends button_tool_1.ButtonToolButtonView {
        _clicked() {
            this.model.do.emit(undefined);
        }
    }
    exports.ActionToolButtonView = ActionToolButtonView;
    ActionToolButtonView.__name__ = "ActionToolButtonView";
    class ActionToolView extends button_tool_1.ButtonToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.do, (arg) => this.doit(arg));
        }
    }
    exports.ActionToolView = ActionToolView;
    ActionToolView.__name__ = "ActionToolView";
    class ActionTool extends button_tool_1.ButtonTool {
        constructor(attrs) {
            super(attrs);
            this.button_view = ActionToolButtonView;
            this.do = new signaling_1.Signal(this, "do");
        }
    }
    exports.ActionTool = ActionTool;
    ActionTool.__name__ = "ActionTool";
},
/* models/tools/actions/help_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(251) /* ./action_tool */;
    const icons_css_1 = require(242) /* ../../../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.icon = icons_css_1.tool_icon_help;
        }
        static init_HelpTool() {
            this.prototype.default_view = HelpToolView;
            this.define(({ String }) => ({
                redirect: [String, "https://docs.bokeh.org/en/latest/docs/user_guide/tools.html"],
            }));
            this.override({
                description: "Click the question mark to learn more about Bokeh plot tools.",
            });
            this.register_alias("help", () => new HelpTool());
        }
    }
    exports.HelpTool = HelpTool;
    HelpTool.__name__ = "HelpTool";
    HelpTool.init_HelpTool();
},
/* styles/logo.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.logo = "bk-logo";
    exports.grey = "bk-grey";
    exports.logo_small = "bk-logo-small";
    exports.logo_notebook = "bk-logo-notebook";
    exports.default = `.bk-root .bk-logo{margin:5px;position:relative;display:block;background-repeat:no-repeat;}.bk-root .bk-logo.bk-grey{filter:url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");filter:gray;-webkit-filter:grayscale(100%);}.bk-root .bk-logo-small{width:20px;height:20px;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAOkSURBVDiNjZRtaJVlGMd/1/08zzln5zjP1LWcU9N0NkN8m2CYjpgQYQXqSs0I84OLIC0hkEKoPtiH3gmKoiJDU7QpLgoLjLIQCpEsNJ1vqUOdO7ppbuec5+V+rj4ctwzd8IIbbi6u+8f1539dt3A78eXC7QizUF7gyV1fD1Yqg4JWz84yffhm0qkFqBogB9rM8tZdtwVsPUhWhGcFJngGeWrPzHm5oaMmkfEg1usvLFyc8jLRqDOMru7AyC8saQr7GG7f5fvDeH7Ej8CM66nIF+8yngt6HWaKh7k49Soy9nXurCi1o3qUbS3zWfrYeQDTB/Qj6kX6Ybhw4B+bOYoLKCC9H3Nu/leUTZ1JdRWkkn2ldcCamzrcf47KKXdAJllSlxAOkRgyHsGC/zRday5Qld9DyoM4/q/rUoy/CXh3jzOu3bHUVZeU+DEn8FInkPBFlu3+nW3Nw0mk6vCDiWg8CeJaxEwuHS3+z5RgY+YBR6V1Z1nxSOfoaPa4LASWxxdNp+VWTk7+4vzaou8v8PN+xo+KY2xsw6une2frhw05CTYOmQvsEhjhWjn0bmXPjpE1+kplmmkP3suftwTubK9Vq22qKmrBhpY4jvd5afdRA3wGjFAgcnTK2s4hY0/GPNIb0nErGMCRxWOOX64Z8RAC4oCXdklmEvcL8o0BfkNK4lUg9HTl+oPlQxdNo3Mg4Nv175e/1LDGzZen30MEjRUtmXSfiTVu1kK8W4txyV6BMKlbgk3lMwYCiusNy9fVfvvwMxv8Ynl6vxoByANLTWplvuj/nF9m2+PDtt1eiHPBr1oIfhCChQMBw6Aw0UulqTKZdfVvfG7VcfIqLG9bcldL/+pdWTLxLUy8Qq38heUIjh4XlzZxzQm19lLFlr8vdQ97rjZVOLf8nclzckbcD4wxXMidpX30sFd37Fv/GtwwhzhxGVAprjbg0gCAEeIgwCZyTV2Z1REEW8O4py0wsjeloKoMr6iCY6dP92H6Vw/oTyICIthibxjm/DfN9lVz8IqtqKYLUXfoKVMVQVVJOElGjrnnUt9T9wbgp8AyYKaGlqingHZU/uG2NTZSVqwHQTWkx9hxjkpWDaCg6Ckj5qebgBVbT3V3NNXMSiWSDdGV3hrtzla7J+duwPOToIg42ChPQOQjspnSlp1V+Gjdged7+8UN5CRAV7a5EdFNwCjEaBR27b3W890TE7g24NAP/mMDXRWrGoFPQI9ls/MWO2dWFAar/xcOIImbbpA3zgAAAABJRU5ErkJggg==);}.bk-root .bk-logo-notebook{display:inline-block;vertical-align:middle;margin-right:5px;}`;
},
/* models/annotations/tooltip.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(40) /* ./annotation */;
    const enums_1 = require(20) /* ../../core/enums */;
    const dom_1 = require(43) /* ../../core/dom */;
    const tooltips_css_1 = tslib_1.__importStar(require(255) /* ../../styles/tooltips.css */), tooltips = tooltips_css_1;
    const arrow_size = 10; // XXX: keep in sync with less
    class TooltipView extends annotation_1.AnnotationView {
        initialize() {
            super.initialize();
            this.el = dom_1.div({ class: tooltips.tooltip });
            dom_1.undisplay(this.el);
            this.plot_view.canvas_view.add_overlay(this.el);
        }
        remove() {
            dom_1.remove(this.el);
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.content.change, () => this.render());
            this.connect(this.model.properties.position.change, () => this._reposition());
        }
        styles() {
            return [...super.styles(), tooltips_css_1.default];
        }
        render() {
            if (!this.model.visible)
                dom_1.undisplay(this.el);
            super.render();
        }
        _render() {
            const { content } = this.model;
            if (content == null) {
                dom_1.undisplay(this.el);
                return;
            }
            dom_1.empty(this.el);
            dom_1.classes(this.el).toggle("bk-tooltip-custom", this.model.custom);
            this.el.appendChild(content);
            if (this.model.show_arrow)
                this.el.classList.add(tooltips.tooltip_arrow);
        }
        _reposition() {
            const { position } = this.model;
            if (position == null) {
                dom_1.undisplay(this.el);
                return;
            }
            const [sx, sy] = position;
            const side = (() => {
                const area = this.parent.layout.bbox.relative();
                const { attachment } = this.model;
                switch (attachment) {
                    case "horizontal":
                        return sx < area.hcenter ? "right" : "left";
                    case "vertical":
                        return sy < area.vcenter ? "below" : "above";
                    default:
                        return attachment;
                }
            })();
            this.el.classList.remove(tooltips.right);
            this.el.classList.remove(tooltips.left);
            this.el.classList.remove(tooltips.above);
            this.el.classList.remove(tooltips.below);
            dom_1.display(this.el); // XXX: {offset,client}Width() gives 0 when display="none"
            // slightly confusing: side "left" (for example) is relative to point that
            // is being annotated but CS class ".bk-left" is relative to the tooltip itself
            let top;
            let left = null;
            let right = null;
            switch (side) {
                case "right":
                    this.el.classList.add(tooltips.left);
                    left = sx + (this.el.offsetWidth - this.el.clientWidth) + arrow_size;
                    top = sy - this.el.offsetHeight / 2;
                    break;
                case "left":
                    this.el.classList.add(tooltips.right);
                    right = (this.plot_view.layout.bbox.width - sx) + arrow_size;
                    top = sy - this.el.offsetHeight / 2;
                    break;
                case "below":
                    this.el.classList.add(tooltips.above);
                    top = sy + (this.el.offsetHeight - this.el.clientHeight) + arrow_size;
                    left = Math.round(sx - this.el.offsetWidth / 2);
                    break;
                case "above":
                    this.el.classList.add(tooltips.below);
                    top = sy - this.el.offsetHeight - arrow_size;
                    left = Math.round(sx - this.el.offsetWidth / 2);
                    break;
            }
            this.el.style.top = `${top}px`;
            this.el.style.left = left != null ? `${left}px` : "auto";
            this.el.style.right = right != null ? `${right}px` : "auto";
        }
    }
    exports.TooltipView = TooltipView;
    TooltipView.__name__ = "TooltipView";
    class Tooltip extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        static init_Tooltip() {
            this.prototype.default_view = TooltipView;
            this.define(({ Boolean }) => ({
                attachment: [enums_1.TooltipAttachment, "horizontal"],
                inner_only: [Boolean, true],
                show_arrow: [Boolean, true],
            }));
            this.internal(({ Boolean, Number, Tuple, Ref, Nullable }) => ({
                position: [Nullable(Tuple(Number, Number)), null],
                content: [Ref(HTMLElement), () => dom_1.div()],
                custom: [Boolean],
            }));
            this.override({
                level: 'overlay',
            });
        }
        clear() {
            this.position = null;
        }
    }
    exports.Tooltip = Tooltip;
    Tooltip.__name__ = "Tooltip";
    Tooltip.init_Tooltip();
},
/* styles/tooltips.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tooltip = "bk-tooltip";
    exports.left = "bk-left";
    exports.tooltip_arrow = "bk-tooltip-arrow";
    exports.right = "bk-right";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.tooltip_row_label = "bk-tooltip-row-label";
    exports.tooltip_row_value = "bk-tooltip-row-value";
    exports.tooltip_color_block = "bk-tooltip-color-block";
    exports.default = `.bk-root{}.bk-root .bk-tooltip{font-weight:300;font-size:12px;position:absolute;padding:5px;border:1px solid #e5e5e5;color:#2f2f2f;background-color:white;pointer-events:none;opacity:0.95;z-index:100;}.bk-root .bk-tooltip > div:not(:first-child){margin-top:5px;border-top:#e5e5e5 1px dashed;}.bk-root .bk-tooltip.bk-left.bk-tooltip-arrow::before{position:absolute;margin:-7px 0 0 0;top:50%;width:0;height:0;border-style:solid;border-width:7px 0 7px 0;border-color:transparent;content:" ";display:block;left:-10px;border-right-width:10px;border-right-color:#909599;}.bk-root .bk-tooltip.bk-left::before{left:-10px;border-right-width:10px;border-right-color:#909599;}.bk-root .bk-tooltip.bk-right.bk-tooltip-arrow::after{position:absolute;margin:-7px 0 0 0;top:50%;width:0;height:0;border-style:solid;border-width:7px 0 7px 0;border-color:transparent;content:" ";display:block;right:-10px;border-left-width:10px;border-left-color:#909599;}.bk-root .bk-tooltip.bk-right::after{right:-10px;border-left-width:10px;border-left-color:#909599;}.bk-root .bk-tooltip.bk-above::before{position:absolute;margin:0 0 0 -7px;left:50%;width:0;height:0;border-style:solid;border-width:0 7px 0 7px;border-color:transparent;content:" ";display:block;top:-10px;border-bottom-width:10px;border-bottom-color:#909599;}.bk-root .bk-tooltip.bk-below::after{position:absolute;margin:0 0 0 -7px;left:50%;width:0;height:0;border-style:solid;border-width:0 7px 0 7px;border-color:transparent;content:" ";display:block;bottom:-10px;border-top-width:10px;border-top-color:#909599;}.bk-root .bk-tooltip-row-label{text-align:right;color:#26aae1;}.bk-root .bk-tooltip-row-value{color:default;}.bk-root .bk-tooltip-color-block{width:12px;height:12px;margin-left:5px;margin-right:5px;outline:#dddddd solid 1px;display:inline-block;}`;
},
/* models/annotations/whisker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const upper_lower_1 = require(135) /* ./upper_lower */;
    const arrow_head_1 = require(133) /* ./arrow_head */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    class WhiskerView extends upper_lower_1.UpperLowerView {
        async lazy_initialize() {
            await super.lazy_initialize();
            const { lower_head, upper_head } = this.model;
            if (lower_head != null)
                this.lower_head = await build_views_1.build_view(lower_head, { parent: this });
            if (upper_head != null)
                this.upper_head = await build_views_1.build_view(upper_head, { parent: this });
        }
        set_data(source) {
            var _a, _b;
            super.set_data(source);
            (_a = this.lower_head) === null || _a === void 0 ? void 0 : _a.set_data(source);
            (_b = this.upper_head) === null || _b === void 0 ? void 0 : _b.set_data(source);
        }
        paint(ctx) {
            if (this.visuals.line.doit) {
                for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.beginPath();
                    ctx.moveTo(this._lower_sx[i], this._lower_sy[i]);
                    ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
                    ctx.stroke();
                }
            }
            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);
        }
        static init_Whisker() {
            this.prototype.default_view = WhiskerView;
            this.mixins(property_mixins_1.LineVector);
            this.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 })],
            }));
            this.override({
                level: "underlay",
            });
        }
    }
    exports.Whisker = Whisker;
    Whisker.__name__ = "Whisker";
    Whisker.init_Whisker();
},
/* models/callbacks/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_1 = require(258) /* ./customjs */;
    __esExport("CustomJS", customjs_1.CustomJS);
    var open_url_1 = require(260) /* ./open_url */;
    __esExport("OpenURL", open_url_1.OpenURL);
},
/* models/callbacks/customjs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const callback_1 = require(259) /* ./callback */;
    const object_1 = require(13) /* ../../core/util/object */;
    const string_1 = require(34) /* ../../core/util/string */;
    class CustomJS extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        static init_CustomJS() {
            this.define(({ Unknown, String, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            }));
        }
        get names() {
            return object_1.keys(this.args);
        }
        get values() {
            return object_1.values(this.args);
        }
        get func() {
            const code = string_1.use_strict(this.code);
            return new Function(...this.names, "cb_obj", "cb_data", code);
        }
        execute(cb_obj, cb_data = {}) {
            return this.func.apply(cb_obj, this.values.concat(cb_obj, cb_data));
        }
    }
    exports.CustomJS = CustomJS;
    CustomJS.__name__ = "CustomJS";
    CustomJS.init_CustomJS();
},
/* models/callbacks/callback.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../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) {
    __esModule();
    const callback_1 = require(259) /* ./callback */;
    const templating_1 = require(182) /* ../../core/util/templating */;
    const types_1 = require(8) /* ../../core/util/types */;
    class OpenURL extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        static init_OpenURL() {
            this.define(({ Boolean, String }) => ({
                url: [String, "http://"],
                same_tab: [Boolean, false],
            }));
        }
        execute(_cb_obj, { source }) {
            const open_url = (i) => {
                const url = templating_1.replace_placeholders(this.url, source, i, undefined, undefined, encodeURIComponent);
                if (!types_1.isString(url))
                    throw new Error("HTML output is not supported in this context");
                if (this.same_tab)
                    window.location.href = url;
                else
                    window.open(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;
    OpenURL.__name__ = "OpenURL";
    OpenURL.init_OpenURL();
},
/* models/canvas/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var canvas_1 = require(262) /* ./canvas */;
    __esExport("Canvas", canvas_1.Canvas);
    var cartesian_frame_1 = require(144) /* ./cartesian_frame */;
    __esExport("CartesianFrame", cartesian_frame_1.CartesianFrame);
},
/* models/canvas/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const has_props_1 = require(14) /* ../../core/has_props */;
    const dom_view_1 = require(240) /* ../../core/dom_view */;
    const logging_1 = require(19) /* ../../core/logging */;
    const dom_1 = require(43) /* ../../core/dom */;
    const enums_1 = require(20) /* ../../core/enums */;
    const object_1 = require(13) /* ../../core/util/object */;
    const ui_events_1 = require(263) /* ../../core/ui_events */;
    const bbox_1 = require(99) /* ../../core/util/bbox */;
    const canvas_1 = require(249) /* ../../core/util/canvas */;
    const global_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", { premultipliedAlpha: true });
        // If WebGL is available, we store a reference to the gl canvas on
        // the ctx object, because that's what gets passed everywhere.
        if (gl != null)
            return { canvas, gl };
        else {
            logging_1.logger.trace("WebGL is not supported");
            return undefined;
        }
    })();
    const style = {
        position: "absolute",
        top: "0",
        left: "0",
        width: "100%",
        height: "100%",
    };
    class CanvasView extends dom_view_1.DOMView {
        constructor() {
            super(...arguments);
            this.bbox = new bbox_1.BBox();
        }
        initialize() {
            super.initialize();
            if (this.model.output_backend == "webgl") {
                this.webgl = global_webgl;
            }
            this.underlays_el = dom_1.div({ style });
            this.primary = this.create_layer();
            this.overlays = this.create_layer();
            this.overlays_el = dom_1.div({ style });
            this.events_el = dom_1.div({ class: "bk-canvas-events", style });
            const elements = [
                this.underlays_el,
                this.primary.el,
                this.overlays.el,
                this.overlays_el,
                this.events_el,
            ];
            object_1.extend(this.el.style, style);
            dom_1.append(this.el, ...elements);
            this.ui_event_bus = new ui_events_1.UIEventBus(this);
        }
        remove() {
            this.ui_event_bus.destroy();
            super.remove();
        }
        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
        }
        resize(width, height) {
            this.bbox = new bbox_1.BBox({ left: 0, top: 0, width, height });
            this.primary.resize(width, height);
            this.overlays.resize(width, height);
        }
        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 { gl } = webgl;
                // Clipping
                gl.enable(gl.SCISSOR_TEST);
                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;
                gl.scissor(ratio * vx, ratio * vy, ratio * w, ratio * h); // lower left corner, width, height
                // Setup blending
                gl.enable(gl.BLEND);
                gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE_MINUS_DST_ALPHA, gl.ONE); // premultipliedAlpha == true
                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) {
                // 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 { gl, canvas } = webgl;
                gl.viewport(0, 0, canvas.width, canvas.height);
                gl.clearColor(0, 0, 0, 0);
                gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
            }
        }
        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 has_props_1.HasProps {
        constructor(attrs) {
            super(attrs);
        }
        static init_Canvas() {
            this.prototype.default_view = CanvasView;
            this.internal(({ Boolean }) => ({
                hidpi: [Boolean, true],
                output_backend: [enums_1.OutputBackend, "canvas"],
            }));
        }
    }
    exports.Canvas = Canvas;
    Canvas.__name__ = "Canvas";
    Canvas.init_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(239) /* hammerjs */);
    const signaling_1 = require(15) /* ./signaling */;
    const logging_1 = require(19) /* ./logging */;
    const dom_1 = require(43) /* ./dom */;
    const events = tslib_1.__importStar(require(264) /* ./bokeh_events */);
    const wheel_1 = require(265) /* ./util/wheel */;
    const array_1 = require(9) /* ./util/array */;
    const types_1 = require(8) /* ./util/types */;
    const platform_1 = require(27) /* ./util/platform */;
    const menus_1 = require(244) /* ./util/menus */;
    function is_touch(event) {
        return typeof TouchEvent !== "undefined" && event instanceof TouchEvent;
    }
    class UIEventBus {
        constructor(canvas_view) {
            this.canvas_view = canvas_view;
            this.pan_start = new signaling_1.Signal(this, 'pan:start');
            this.pan = new signaling_1.Signal(this, 'pan');
            this.pan_end = new signaling_1.Signal(this, 'pan:end');
            this.pinch_start = new signaling_1.Signal(this, 'pinch:start');
            this.pinch = new signaling_1.Signal(this, 'pinch');
            this.pinch_end = new signaling_1.Signal(this, 'pinch:end');
            this.rotate_start = new signaling_1.Signal(this, 'rotate:start');
            this.rotate = new signaling_1.Signal(this, 'rotate');
            this.rotate_end = new signaling_1.Signal(this, 'rotate:end');
            this.tap = new signaling_1.Signal(this, 'tap');
            this.doubletap = new signaling_1.Signal(this, 'doubletap');
            this.press = new signaling_1.Signal(this, 'press');
            this.pressup = new signaling_1.Signal(this, 'pressup');
            this.move_enter = new signaling_1.Signal(this, 'move:enter');
            this.move = new signaling_1.Signal(this, 'move');
            this.move_exit = new signaling_1.Signal(this, 'move:exit');
            this.scroll = new signaling_1.Signal(this, 'scroll');
            this.keydown = new signaling_1.Signal(this, 'keydown');
            this.keyup = new signaling_1.Signal(this, 'keyup');
            this.hammer = new hammerjs_1.default(this.hit_area, {
                touchAction: 'auto',
                inputClass: hammerjs_1.default.TouchMouseInput,
            });
            this._prev_move = null;
            this._curr_pan = null;
            this._curr_pinch = null;
            this._curr_rotate = null;
            this._configure_hammerjs();
            // Mouse & keyboard events not handled through hammerjs
            // We can 'add and forget' these event listeners because this.hit_area is a DOM element
            // that will be thrown away when the view is removed
            this.hit_area.addEventListener("mousemove", (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);
            this.menu = new menus_1.ContextMenu([], {
                prevent_hide: (event) => event.button == 2 && event.target == this.hit_area,
            });
            this.hit_area.appendChild(this.menu.el);
        }
        get hit_area() {
            return this.canvas_view.events_el;
        }
        destroy() {
            this.menu.remove();
            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) {
            const et = tool_view.model.event_type;
            if (et != null) {
                if (types_1.isString(et))
                    this._register_tool(tool_view, et);
                else {
                    // Multi-tools should only registered shared events once
                    et.forEach((e, index) => this._register_tool(tool_view, e, index < 1));
                }
            }
        }
        _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)));
                    if (v._doubletap != null)
                        v.connect(this.doubletap, conditionally(v._doubletap.bind(v)));
                    break;
                }
                case "press": {
                    if (v._press != null)
                        v.connect(this.press, conditionally(v._press.bind(v)));
                    if (v._pressup != null)
                        v.connect(this.pressup, conditionally(v._pressup.bind(v)));
                    break;
                }
                case "scroll": {
                    if (v._scroll != null)
                        v.connect(this.scroll, conditionally(v._scroll.bind(v)));
                    break;
                }
                default:
                    throw new Error(`unsupported event_type: ${et}`);
            }
            // Skip shared events if registering multi-tool
            if (!shared)
                return;
            if (v._keydown != null)
                v.connect(this.keydown, unconditionally(v._keydown.bind(v)));
            if (v._keyup != null)
                v.connect(this.keyup, unconditionally(v._keyup.bind(v)));
            // Dual touch hack part 1/2
            // This is a hack for laptops with touch screen who may be pinching or scrolling
            // in order to use the wheel zoom tool. If it's a touch screen the WheelZoomTool event
            // will be linked to pinch. But we also want to trigger in the case of a scroll.
            if (platform_1.is_mobile && v._scroll != null && et == 'pinch') {
                logging_1.logger.debug("Registering scroll on touch screen");
                v.connect(this.scroll, conditionally(v._scroll.bind(v)));
            }
        }
        _hit_test_renderers(plot_view, sx, sy) {
            var _a;
            const views = plot_view.get_renderer_views();
            for (const view of array_1.reversed(views)) {
                if ((_a = view.interactive_hit) === null || _a === void 0 ? void 0 : _a.call(view, sx, sy))
                    return view;
            }
            return null;
        }
        set_cursor(cursor = "default") {
            this.hit_area.style.cursor = cursor;
        }
        _hit_test_frame(plot_view, sx, sy) {
            return plot_view.frame.bbox.contains(sx, sy);
        }
        _hit_test_canvas(plot_view, sx, sy) {
            return plot_view.layout.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.layout.bbox.relative() /*XXX*/.contains(sx, sy))
                    return plot_view;
            }
            return null;
        }
        _trigger(signal, e, srcEvent) {
            var _a;
            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, shiftKey: false, ctrlKey: 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, shiftKey: false, ctrlKey: 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;
            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);
            const on_canvas = this._hit_test_canvas(plot_view, e.sx, e.sy);
            switch (base_type) {
                case "move": {
                    const active_gesture = gestures[base_type].active;
                    if (active_gesture != null)
                        this.trigger(signal, e, active_gesture.id);
                    const active_inspectors = plot_view.model.toolbar.inspectors.filter(t => t.active);
                    let cursor = "default";
                    // the event happened on a renderer
                    if (view != null) {
                        cursor = (_a = view.cursor(e.sx, e.sy)) !== null && _a !== void 0 ? _a : cursor;
                        if (!array_1.is_empty(active_inspectors)) {
                            // override event_type to cause inspectors to clear overlays
                            signal = this.move_exit; // XXX
                        }
                        // the event happened on the plot frame but off a renderer
                    }
                    else if (this._hit_test_frame(plot_view, e.sx, e.sy)) {
                        if (!array_1.is_empty(active_inspectors)) {
                            cursor = "crosshair";
                        }
                    }
                    this.set_cursor(cursor);
                    plot_view.set_toolbar_visibility(on_canvas);
                    active_inspectors.map((inspector) => this.trigger(signal, e, inspector.id));
                    break;
                }
                case "tap": {
                    const { target } = srcEvent;
                    if (target != null && target != this.hit_area)
                        return; // don't trigger bokeh events
                    if (view != null && view.on_hit != null)
                        view.on_hit(e.sx, e.sy);
                    const active_gesture = gestures[base_type].active;
                    if (active_gesture != null)
                        this.trigger(signal, e, active_gesture.id);
                    break;
                }
                case "doubletap": {
                    const active_gesture = (_b = gestures.doubletap.active) !== null && _b !== void 0 ? _b : gestures.tap.active;
                    if (active_gesture != null)
                        this.trigger(signal, e, active_gesture.id);
                    break;
                }
                case "scroll": {
                    // Dual touch hack part 2/2
                    // This is a hack for laptops with touch screen who may be pinching or scrolling
                    // in order to use the wheel zoom tool. If it's a touch screen the WheelZoomTool event
                    // will be linked to pinch. But we also want to trigger in the case of a scroll.
                    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[base_type].active;
                    if (active_gesture != null) {
                        srcEvent.preventDefault();
                        this.trigger(signal, e, active_gesture.id);
                    }
                    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 } = 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);
                    case "mousemove":
                        return new events.MouseMove(sx, sy, x, y);
                    case "mouseenter":
                        return new events.MouseEnter(sx, sy, x, y);
                    case "mouseleave":
                        return new events.MouseLeave(sx, sy, x, y);
                    case "tap":
                        return new events.Tap(sx, sy, x, y);
                    case "doubletap":
                        return new events.DoubleTap(sx, sy, x, y);
                    case "press":
                        return new events.Press(sx, sy, x, y);
                    case "pressup":
                        return new events.PressUp(sx, sy, x, y);
                    case "pan":
                        return new events.Pan(sx, sy, x, y, e.deltaX, e.deltaY);
                    case "panstart":
                        return new events.PanStart(sx, sy, x, y);
                    case "panend":
                        return new events.PanEnd(sx, sy, x, y);
                    case "pinch":
                        return new events.Pinch(sx, sy, x, y, e.scale);
                    case "pinchstart":
                        return new events.PinchStart(sx, sy, x, y);
                    case "pinchend":
                        return new events.PinchEnd(sx, sy, x, y);
                    case "rotate":
                        return new events.Rotate(sx, sy, x, y, e.rotation);
                    case "rotatestart":
                        return new events.RotateStart(sx, sy, x, y);
                    case "rotateend":
                        return new events.RotateEnd(sx, sy, x, y);
                    default:
                        return undefined;
                }
            })();
            if (ev != null)
                plot_view.model.trigger_event(ev);
        }
        /*private*/ _get_sxy(event) {
            const { pageX, pageY } = is_touch(event) ? (event.touches.length != 0 ? event.touches : event.changedTouches)[0] : event;
            const { left, top } = dom_1.offset(this.hit_area);
            return {
                sx: pageX - left,
                sy: pageY - top,
            };
        }
        /*private*/ _pan_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e.srcEvent)), { deltaX: e.deltaX, deltaY: e.deltaY, shiftKey: e.srcEvent.shiftKey, ctrlKey: e.srcEvent.ctrlKey });
        }
        /*private*/ _pinch_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e.srcEvent)), { scale: e.scale, shiftKey: e.srcEvent.shiftKey, ctrlKey: e.srcEvent.ctrlKey });
        }
        /*private*/ _rotate_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e.srcEvent)), { rotation: e.rotation, shiftKey: e.srcEvent.shiftKey, ctrlKey: e.srcEvent.ctrlKey });
        }
        /*private*/ _tap_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e.srcEvent)), { shiftKey: e.srcEvent.shiftKey, ctrlKey: e.srcEvent.ctrlKey });
        }
        /*private*/ _move_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e)), { shiftKey: e.shiftKey, ctrlKey: e.ctrlKey });
        }
        /*private*/ _scroll_event(e) {
            return Object.assign(Object.assign({ type: e.type }, this._get_sxy(e)), { delta: wheel_1.getDeltaY(e), shiftKey: e.shiftKey, ctrlKey: e.ctrlKey });
        }
        /*private*/ _key_event(e) {
            return {
                type: e.type,
                keyCode: e.keyCode,
            };
        }
        /*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) {
            if (!this.menu.is_open && this.menu.can_open) {
                e.preventDefault();
            }
            const { sx, sy } = this._get_sxy(e);
            this.menu.toggle({ left: sx, top: sy });
        }
        /*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";
},
/* core/bokeh_events.js */ function _(require, module, exports, __esModule, __esExport) {
    __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;
    };
    function event(event_name) {
        return function (cls) {
            cls.prototype.event_name = event_name;
        };
    }
    class BokehEvent {
        to_json() {
            const { event_name } = this;
            return { event_name, event_values: this._to_json() };
        }
    }
    exports.BokehEvent = BokehEvent;
    BokehEvent.__name__ = "BokehEvent";
    class ModelEvent extends BokehEvent {
        constructor() {
            super(...arguments);
            this.origin = null;
        }
        _to_json() {
            return { model: this.origin };
        }
    }
    exports.ModelEvent = ModelEvent;
    ModelEvent.__name__ = "ModelEvent";
    let DocumentReady = class DocumentReady extends BokehEvent {
        _to_json() {
            return {};
        }
    };
    exports.DocumentReady = DocumentReady;
    DocumentReady.__name__ = "DocumentReady";
    exports.DocumentReady = DocumentReady = __decorate([
        event("document_ready")
    ], DocumentReady);
    let ButtonClick = class ButtonClick extends ModelEvent {
    };
    exports.ButtonClick = ButtonClick;
    ButtonClick.__name__ = "ButtonClick";
    exports.ButtonClick = ButtonClick = __decorate([
        event("button_click")
    ], ButtonClick);
    let MenuItemClick = class MenuItemClick extends ModelEvent {
        constructor(item) {
            super();
            this.item = item;
        }
        _to_json() {
            const { item } = this;
            return Object.assign(Object.assign({}, super._to_json()), { item });
        }
    };
    exports.MenuItemClick = MenuItemClick;
    MenuItemClick.__name__ = "MenuItemClick";
    exports.MenuItemClick = MenuItemClick = __decorate([
        event("menu_item_click")
    ], MenuItemClick);
    // A UIEvent is an event originating on a canvas this includes.
    // DOM events such as keystrokes as well as hammer events and LOD events.
    class UIEvent extends ModelEvent {
    }
    exports.UIEvent = UIEvent;
    UIEvent.__name__ = "UIEvent";
    let LODStart = class LODStart extends UIEvent {
    };
    exports.LODStart = LODStart;
    LODStart.__name__ = "LODStart";
    exports.LODStart = LODStart = __decorate([
        event("lodstart")
    ], LODStart);
    let LODEnd = class LODEnd extends UIEvent {
    };
    exports.LODEnd = LODEnd;
    LODEnd.__name__ = "LODEnd";
    exports.LODEnd = LODEnd = __decorate([
        event("lodend")
    ], LODEnd);
    let SelectionGeometry = class SelectionGeometry extends UIEvent {
        constructor(geometry, final) {
            super();
            this.geometry = geometry;
            this.final = final;
        }
        _to_json() {
            const { geometry, final } = this;
            return Object.assign(Object.assign({}, super._to_json()), { geometry, final });
        }
    };
    exports.SelectionGeometry = SelectionGeometry;
    SelectionGeometry.__name__ = "SelectionGeometry";
    exports.SelectionGeometry = SelectionGeometry = __decorate([
        event("selectiongeometry")
    ], SelectionGeometry);
    let Reset = class Reset extends UIEvent {
    };
    exports.Reset = Reset;
    Reset.__name__ = "Reset";
    exports.Reset = Reset = __decorate([
        event("reset")
    ], Reset);
    class PointEvent extends UIEvent {
        constructor(sx, sy, x, y) {
            super();
            this.sx = sx;
            this.sy = sy;
            this.x = x;
            this.y = y;
        }
        _to_json() {
            const { sx, sy, x, y } = this;
            return Object.assign(Object.assign({}, super._to_json()), { sx, sy, x, y });
        }
    }
    exports.PointEvent = PointEvent;
    PointEvent.__name__ = "PointEvent";
    let Pan = class Pan extends PointEvent {
        /* TODO: direction: -1 | 1 */
        constructor(sx, sy, x, y, delta_x, delta_y) {
            super(sx, sy, x, y);
            this.sx = sx;
            this.sy = sy;
            this.x = x;
            this.y = y;
            this.delta_x = delta_x;
            this.delta_y = delta_y;
        }
        _to_json() {
            const { delta_x, delta_y /*, direction*/ } = this;
            return Object.assign(Object.assign({}, super._to_json()), { delta_x, delta_y /*, direction*/ });
        }
    };
    exports.Pan = Pan;
    Pan.__name__ = "Pan";
    exports.Pan = Pan = __decorate([
        event("pan")
    ], Pan);
    let Pinch = class Pinch extends PointEvent {
        constructor(sx, sy, x, y, scale) {
            super(sx, sy, x, y);
            this.sx = sx;
            this.sy = sy;
            this.x = x;
            this.y = y;
            this.scale = scale;
        }
        _to_json() {
            const { scale } = this;
            return Object.assign(Object.assign({}, super._to_json()), { scale });
        }
    };
    exports.Pinch = Pinch;
    Pinch.__name__ = "Pinch";
    exports.Pinch = Pinch = __decorate([
        event("pinch")
    ], Pinch);
    let Rotate = class Rotate extends PointEvent {
        constructor(sx, sy, x, y, rotation) {
            super(sx, sy, x, y);
            this.sx = sx;
            this.sy = sy;
            this.x = x;
            this.y = y;
            this.rotation = rotation;
        }
        _to_json() {
            const { rotation } = this;
            return Object.assign(Object.assign({}, super._to_json()), { rotation });
        }
    };
    exports.Rotate = Rotate;
    Rotate.__name__ = "Rotate";
    exports.Rotate = Rotate = __decorate([
        event("rotate")
    ], Rotate);
    let MouseWheel = class MouseWheel extends PointEvent {
        constructor(sx, sy, x, y, delta) {
            super(sx, sy, x, y);
            this.sx = sx;
            this.sy = sy;
            this.x = x;
            this.y = y;
            this.delta = delta;
        }
        _to_json() {
            const { delta } = this;
            return Object.assign(Object.assign({}, super._to_json()), { delta });
        }
    };
    exports.MouseWheel = MouseWheel;
    MouseWheel.__name__ = "MouseWheel";
    exports.MouseWheel = MouseWheel = __decorate([
        event("wheel")
    ], MouseWheel);
    let MouseMove = class MouseMove extends PointEvent {
    };
    exports.MouseMove = MouseMove;
    MouseMove.__name__ = "MouseMove";
    exports.MouseMove = MouseMove = __decorate([
        event("mousemove")
    ], MouseMove);
    let MouseEnter = class MouseEnter extends PointEvent {
    };
    exports.MouseEnter = MouseEnter;
    MouseEnter.__name__ = "MouseEnter";
    exports.MouseEnter = MouseEnter = __decorate([
        event("mouseenter")
    ], MouseEnter);
    let MouseLeave = class MouseLeave extends PointEvent {
    };
    exports.MouseLeave = MouseLeave;
    MouseLeave.__name__ = "MouseLeave";
    exports.MouseLeave = MouseLeave = __decorate([
        event("mouseleave")
    ], MouseLeave);
    let Tap = class Tap extends PointEvent {
    };
    exports.Tap = Tap;
    Tap.__name__ = "Tap";
    exports.Tap = Tap = __decorate([
        event("tap")
    ], Tap);
    let DoubleTap = class DoubleTap extends PointEvent {
    };
    exports.DoubleTap = DoubleTap;
    DoubleTap.__name__ = "DoubleTap";
    exports.DoubleTap = DoubleTap = __decorate([
        event("doubletap")
    ], DoubleTap);
    let Press = class Press extends PointEvent {
    };
    exports.Press = Press;
    Press.__name__ = "Press";
    exports.Press = Press = __decorate([
        event("press")
    ], Press);
    let PressUp = class PressUp extends PointEvent {
    };
    exports.PressUp = PressUp;
    PressUp.__name__ = "PressUp";
    exports.PressUp = PressUp = __decorate([
        event("pressup")
    ], PressUp);
    let PanStart = class PanStart extends PointEvent {
    };
    exports.PanStart = PanStart;
    PanStart.__name__ = "PanStart";
    exports.PanStart = PanStart = __decorate([
        event("panstart")
    ], PanStart);
    let PanEnd = class PanEnd extends PointEvent {
    };
    exports.PanEnd = PanEnd;
    PanEnd.__name__ = "PanEnd";
    exports.PanEnd = PanEnd = __decorate([
        event("panend")
    ], PanEnd);
    let PinchStart = class PinchStart extends PointEvent {
    };
    exports.PinchStart = PinchStart;
    PinchStart.__name__ = "PinchStart";
    exports.PinchStart = PinchStart = __decorate([
        event("pinchstart")
    ], PinchStart);
    let PinchEnd = class PinchEnd extends PointEvent {
    };
    exports.PinchEnd = PinchEnd;
    PinchEnd.__name__ = "PinchEnd";
    exports.PinchEnd = PinchEnd = __decorate([
        event("pinchend")
    ], PinchEnd);
    let RotateStart = class RotateStart extends PointEvent {
    };
    exports.RotateStart = RotateStart;
    RotateStart.__name__ = "RotateStart";
    exports.RotateStart = RotateStart = __decorate([
        event("rotatestart")
    ], RotateStart);
    let RotateEnd = class RotateEnd extends PointEvent {
    };
    exports.RotateEnd = RotateEnd;
    RotateEnd.__name__ = "RotateEnd";
    exports.RotateEnd = RotateEnd = __decorate([
        event("rotateend")
    ], RotateEnd);
},
/* core/util/wheel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    /*!
     * jQuery Mousewheel 3.1.13
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license
     * http://jquery.org/license
     */
    function fontSize(element) {
        const value = getComputedStyle(element).fontSize;
        if (value != null)
            return parseInt(value, 10);
        return null;
    }
    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;
},
/* models/expressions/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var expression_1 = require(124) /* ./expression */;
    __esExport("Expression", expression_1.Expression);
    var customjs_expr_1 = require(267) /* ./customjs_expr */;
    __esExport("CustomJSExpr", customjs_expr_1.CustomJSExpr);
    var stack_1 = require(268) /* ./stack */;
    __esExport("Stack", stack_1.Stack);
    var cumsum_1 = require(269) /* ./cumsum */;
    __esExport("CumSum", cumsum_1.CumSum);
    var expression_2 = require(124) /* ./expression */;
    __esExport("ScalarExpression", expression_2.ScalarExpression);
    var minimum_1 = require(270) /* ./minimum */;
    __esExport("Minimum", minimum_1.Minimum);
    var maximum_1 = require(271) /* ./maximum */;
    __esExport("Maximum", maximum_1.Maximum);
},
/* models/expressions/customjs_expr.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const has_props_1 = require(14) /* ../../core/has_props */;
    const expression_1 = require(124) /* ./expression */;
    const types_1 = require(24) /* ../../core/types */;
    const array_1 = require(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../core/util/object */;
    const string_1 = require(34) /* ../../core/util/string */;
    const types_2 = require(8) /* ../../core/util/types */;
    class CustomJSExpr extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        static init_CustomJSExpr() {
            this.define(({ Unknown, String, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            }));
        }
        connect_signals() {
            super.connect_signals();
            for (const value of object_1.values(this.args)) {
                if (value instanceof has_props_1.HasProps) {
                    value.change.connect(() => {
                        this._result.clear();
                        this.change.emit();
                    });
                }
            }
        }
        get names() {
            return object_1.keys(this.args);
        }
        get values() {
            return object_1.values(this.args);
        }
        get func() {
            const code = string_1.use_strict(this.code);
            return new types_1.GeneratorFunction(...this.names, code);
        }
        _v_compute(source) {
            const generator = this.func.apply(source, this.values);
            let result = generator.next();
            if (result.done && result.value !== undefined) {
                const { value } = result;
                if (types_2.isArray(value) || types_2.isTypedArray(value))
                    return value;
                else if (types_2.isIterable(value))
                    return [...value];
                else
                    return array_1.repeat(value, source.length);
            }
            else {
                const array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!result.done);
                return array;
            }
        }
    }
    exports.CustomJSExpr = CustomJSExpr;
    CustomJSExpr.__name__ = "CustomJSExpr";
    CustomJSExpr.init_CustomJSExpr();
},
/* models/expressions/stack.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(124) /* ./expression */;
    class Stack extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        static init_Stack() {
            this.define(({ String, Array }) => ({
                fields: [Array(String), []],
            }));
        }
        _v_compute(source) {
            var _a;
            const n = (_a = source.get_length()) !== null && _a !== void 0 ? _a : 0;
            const result = new Float64Array(n);
            for (const f of this.fields) {
                const column = source.data[f];
                if (column != null) {
                    for (let i = 0, k = Math.min(n, column.length); i < k; i++) {
                        result[i] += column[i];
                    }
                }
            }
            return result;
        }
    }
    exports.Stack = Stack;
    Stack.__name__ = "Stack";
    Stack.init_Stack();
},
/* models/expressions/cumsum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(124) /* ./expression */;
    class CumSum extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        static init_CumSum() {
            this.define(({ Boolean, String }) => ({
                field: [String],
                include_zero: [Boolean, false],
            }));
        }
        _v_compute(source) {
            var _a;
            const result = new Float64Array((_a = source.get_length()) !== null && _a !== void 0 ? _a : 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;
    CumSum.__name__ = "CumSum";
    CumSum.init_CumSum();
},
/* models/expressions/minimum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(124) /* ./expression */;
    const array_1 = require(9) /* ../../core/util/array */;
    class Minimum extends expression_1.ScalarExpression {
        constructor(attrs) {
            super(attrs);
        }
        static init_Minimum() {
            this.define(({ Number, String, Nullable }) => ({
                field: [String],
                initial: [Nullable(Number), null],
            }));
        }
        _compute(source) {
            var _a, _b;
            const column = (_a = source.data[this.field]) !== null && _a !== void 0 ? _a : [];
            return Math.min((_b = this.initial) !== null && _b !== void 0 ? _b : Infinity, array_1.min(column));
        }
    }
    exports.Minimum = Minimum;
    Minimum.__name__ = "Minimum";
    Minimum.init_Minimum();
},
/* models/expressions/maximum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const expression_1 = require(124) /* ./expression */;
    const array_1 = require(9) /* ../../core/util/array */;
    class Maximum extends expression_1.ScalarExpression {
        constructor(attrs) {
            super(attrs);
        }
        static init_Maximum() {
            this.define(({ Number, String, Nullable }) => ({
                field: [String],
                initial: [Nullable(Number), null],
            }));
        }
        _compute(source) {
            var _a, _b;
            const column = (_a = source.data[this.field]) !== null && _a !== void 0 ? _a : [];
            return Math.max((_b = this.initial) !== null && _b !== void 0 ? _b : -Infinity, array_1.max(column));
        }
    }
    exports.Maximum = Maximum;
    Maximum.__name__ = "Maximum";
    Maximum.init_Maximum();
},
/* models/filters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var boolean_filter_1 = require(273) /* ./boolean_filter */;
    __esExport("BooleanFilter", boolean_filter_1.BooleanFilter);
    var customjs_filter_1 = require(274) /* ./customjs_filter */;
    __esExport("CustomJSFilter", customjs_filter_1.CustomJSFilter);
    var filter_1 = require(121) /* ./filter */;
    __esExport("Filter", filter_1.Filter);
    var group_filter_1 = require(275) /* ./group_filter */;
    __esExport("GroupFilter", group_filter_1.GroupFilter);
    var index_filter_1 = require(276) /* ./index_filter */;
    __esExport("IndexFilter", index_filter_1.IndexFilter);
},
/* models/filters/boolean_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(121) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class BooleanFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static init_BooleanFilter() {
            this.define(({ Boolean, Array, Nullable }) => ({
                booleans: [Nullable(Array(Boolean)), null],
            }));
        }
        compute_indices(source) {
            const size = source.length;
            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;
    BooleanFilter.__name__ = "BooleanFilter";
    BooleanFilter.init_BooleanFilter();
},
/* models/filters/customjs_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(121) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    const object_1 = require(13) /* ../../core/util/object */;
    const types_2 = require(8) /* ../../core/util/types */;
    const string_1 = require(34) /* ../../core/util/string */;
    class CustomJSFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static init_CustomJSFilter() {
            this.define(({ Unknown, String, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            }));
        }
        get names() {
            return object_1.keys(this.args);
        }
        get values() {
            return object_1.values(this.args);
        }
        get func() {
            const code = string_1.use_strict(this.code);
            return new Function(...this.names, "source", code);
        }
        compute_indices(source) {
            const size = source.length;
            const filter = this.func(...this.values, source);
            if (filter == null)
                return types_1.Indices.all_set(size);
            else if (types_2.isArrayOf(filter, types_2.isInteger))
                return types_1.Indices.from_indices(size, filter);
            else if (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;
    CustomJSFilter.__name__ = "CustomJSFilter";
    CustomJSFilter.init_CustomJSFilter();
},
/* models/filters/group_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(121) /* ./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);
        }
        static init_GroupFilter() {
            this.define(({ String }) => ({
                column_name: [String],
                group: [String],
            }));
        }
        compute_indices(source) {
            const column = source.get_column(this.column_name);
            if (column == null) {
                logging_1.logger.warn(`${this}: groupby column '${this.column_name}' not found in the data source`);
                return new types_1.Indices(source.length, 1);
            }
            else {
                const indices = new types_1.Indices(source.length);
                for (let i = 0; i < indices.size; i++) {
                    if (column[i] === this.group)
                        indices.set(i);
                }
                return indices;
            }
        }
    }
    exports.GroupFilter = GroupFilter;
    GroupFilter.__name__ = "GroupFilter";
    GroupFilter.init_GroupFilter();
},
/* models/filters/index_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(121) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class IndexFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        static init_IndexFilter() {
            this.define(({ Int, Array, Nullable }) => ({
                indices: [Nullable(Array(Int)), null],
            }));
        }
        compute_indices(source) {
            const size = source.length;
            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;
    IndexFilter.__name__ = "IndexFilter";
    IndexFilter.init_IndexFilter();
},
/* models/glyphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var annular_wedge_1 = require(278) /* ./annular_wedge */;
    __esExport("AnnularWedge", annular_wedge_1.AnnularWedge);
    var annulus_1 = require(279) /* ./annulus */;
    __esExport("Annulus", annulus_1.Annulus);
    var arc_1 = require(280) /* ./arc */;
    __esExport("Arc", arc_1.Arc);
    var bezier_1 = require(281) /* ./bezier */;
    __esExport("Bezier", bezier_1.Bezier);
    var circle_1 = require(282) /* ./circle */;
    __esExport("Circle", circle_1.Circle);
    var ellipse_1 = require(286) /* ./ellipse */;
    __esExport("Ellipse", ellipse_1.Ellipse);
    var ellipse_oval_1 = require(287) /* ./ellipse_oval */;
    __esExport("EllipseOval", ellipse_oval_1.EllipseOval);
    var glyph_1 = require(98) /* ./glyph */;
    __esExport("Glyph", glyph_1.Glyph);
    var harea_1 = require(117) /* ./harea */;
    __esExport("HArea", harea_1.HArea);
    var hbar_1 = require(289) /* ./hbar */;
    __esExport("HBar", hbar_1.HBar);
    var hex_tile_1 = require(291) /* ./hex_tile */;
    __esExport("HexTile", hex_tile_1.HexTile);
    var image_1 = require(292) /* ./image */;
    __esExport("Image", image_1.Image);
    var image_rgba_1 = require(294) /* ./image_rgba */;
    __esExport("ImageRGBA", image_rgba_1.ImageRGBA);
    var image_url_1 = require(295) /* ./image_url */;
    __esExport("ImageURL", image_url_1.ImageURL);
    var line_1 = require(63) /* ./line */;
    __esExport("Line", line_1.Line);
    var multi_line_1 = require(127) /* ./multi_line */;
    __esExport("MultiLine", multi_line_1.MultiLine);
    var multi_polygons_1 = require(297) /* ./multi_polygons */;
    __esExport("MultiPolygons", multi_polygons_1.MultiPolygons);
    var oval_1 = require(298) /* ./oval */;
    __esExport("Oval", oval_1.Oval);
    var patch_1 = require(116) /* ./patch */;
    __esExport("Patch", patch_1.Patch);
    var patches_1 = require(128) /* ./patches */;
    __esExport("Patches", patches_1.Patches);
    var quad_1 = require(299) /* ./quad */;
    __esExport("Quad", quad_1.Quad);
    var quadratic_1 = require(300) /* ./quadratic */;
    __esExport("Quadratic", quadratic_1.Quadratic);
    var ray_1 = require(301) /* ./ray */;
    __esExport("Ray", ray_1.Ray);
    var rect_1 = require(302) /* ./rect */;
    __esExport("Rect", rect_1.Rect);
    var scatter_1 = require(303) /* ./scatter */;
    __esExport("Scatter", scatter_1.Scatter);
    var segment_1 = require(306) /* ./segment */;
    __esExport("Segment", segment_1.Segment);
    var spline_1 = require(307) /* ./spline */;
    __esExport("Spline", spline_1.Spline);
    var step_1 = require(309) /* ./step */;
    __esExport("Step", step_1.Step);
    var text_1 = require(310) /* ./text */;
    __esExport("Text", text_1.Text);
    var varea_1 = require(119) /* ./varea */;
    __esExport("VArea", varea_1.VArea);
    var vbar_1 = require(311) /* ./vbar */;
    __esExport("VBar", vbar_1.VBar);
    var wedge_1 = require(312) /* ./wedge */;
    __esExport("Wedge", wedge_1.Wedge);
},
/* models/glyphs/annular_wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const utils_1 = require(106) /* ./utils */;
    const property_mixins_1 = require(48) /* ../../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(10) /* ../../core/util/math */;
    const selection_1 = require(59) /* ../selections/selection */;
    class AnnularWedgeView extends xy_glyph_1.XYGlyphView {
        _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 = 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 = types_1.to_screen(this.outer_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 (isNaN(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);
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            // check radius first
            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 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]);
                if (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) {
            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);
        }
        static init_AnnularWedge() {
            this.prototype.default_view = AnnularWedgeView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.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" }],
            }));
        }
    }
    exports.AnnularWedge = AnnularWedge;
    AnnularWedge.__name__ = "AnnularWedge";
    AnnularWedge.init_AnnularWedge();
},
/* models/glyphs/annulus.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const types_1 = require(24) /* ../../core/types */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const platform_1 = require(27) /* ../../core/util/platform */;
    const selection_1 = require(59) /* ../selections/selection */;
    class AnnulusView extends xy_glyph_1.XYGlyphView {
        _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 = 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 = 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 (isNaN(sx_i + sy_i + sinner_radius_i + souter_radius_i))
                    continue;
                // Because this visual has a whole in it, it proved "challenging"
                // for some browsers to render if drawn in one go --- i.e. it did not
                // work on IE. If we render in two parts (upper and lower part),
                // it is unambiguous what part should be filled. The line is
                // better drawn in one go though, otherwise the part where the pieces
                // meet will not be fully closed due to aa.
                function fill_path() {
                    ctx.beginPath();
                    if (platform_1.is_ie) {
                        // Draw two halves of the donut. Works on IE, but causes an aa line on Safari.
                        for (const clockwise of [false, true]) {
                            ctx.arc(sx_i, sy_i, sinner_radius_i, 0, Math.PI, clockwise);
                            ctx.arc(sx_i, sy_i, souter_radius_i, Math.PI, 0, !clockwise);
                        }
                    }
                    else {
                        // Draw donut in one go. Does not work on iE.
                        ctx.arc(sx_i, sy_i, sinner_radius_i, 0, 2 * Math.PI, true);
                        ctx.arc(sx_i, sy_i, souter_radius_i, 2 * Math.PI, 0, false);
                    }
                }
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    fill_path();
                    ctx.fill();
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    fill_path();
                    ctx.fill();
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.beginPath();
                    ctx.arc(sx_i, sy_i, sinner_radius_i, 0, 2 * Math.PI);
                    ctx.moveTo(sx_i + souter_radius_i, sy_i);
                    ctx.arc(sx_i, sy_i, souter_radius_i, 0, 2 * Math.PI);
                    ctx.stroke();
                }
            }
        }
        _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);
        }
        static init_Annulus() {
            this.prototype.default_view = AnnulusView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({}) => ({
                inner_radius: [p.DistanceSpec, { field: "inner_radius" }],
                outer_radius: [p.DistanceSpec, { field: "outer_radius" }],
            }));
        }
    }
    exports.Annulus = Annulus;
    Annulus.__name__ = "Annulus";
    Annulus.init_Annulus();
},
/* models/glyphs/arc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const utils_1 = require(106) /* ./utils */;
    const property_mixins_1 = require(48) /* ../../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 = types_1.to_screen(this.radius);
        }
        _render(ctx, indices, data) {
            if (this.visuals.line.doit) {
                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 (isNaN(sx_i + sy_i + sradius_i + start_angle_i + end_angle_i))
                        continue;
                    ctx.beginPath();
                    ctx.arc(sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            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);
        }
        static init_Arc() {
            this.prototype.default_view = ArcView;
            this.mixins(property_mixins_1.LineVector);
            this.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" }],
            }));
        }
    }
    exports.Arc = Arc;
    Arc.__name__ = "Arc";
    Arc.init_Arc();
},
/* models/glyphs/bezier.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const glyph_1 = require(98) /* ./glyph */;
    const utils_1 = require(106) /* ./utils */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    // algorithm adapted from http://stackoverflow.com/a/14429749/3406693
    function _cbb(x0, y0, x1, y1, x2, y2, x3, y3) {
        const tvalues = [];
        const bounds = [[], []];
        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 (Math.abs(a) < 1e-12) { // Numerical robustness
                if (Math.abs(b) < 1e-12) // Numerical robustness
                    continue;
                const t = -c / b;
                if (0 < t && t < 1)
                    tvalues.push(t);
                continue;
            }
            const b2ac = (b * b) - (4 * c * a);
            const sqrtb2ac = Math.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);
        }
        let j = tvalues.length;
        const jlen = j;
        while (j--) {
            const t = tvalues[j];
            const mt = 1 - t;
            const x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
            bounds[0][j] = x;
            const y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
            bounds[1][j] = y;
        }
        bounds[0][jlen] = x0;
        bounds[1][jlen] = y0;
        bounds[0][jlen + 1] = x3;
        bounds[1][jlen + 1] = y3;
        return [
            Math.min(...bounds[0]),
            Math.max(...bounds[1]),
            Math.max(...bounds[0]),
            Math.min(...bounds[1]),
        ];
    }
    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 (isNaN(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] = _cbb(x0_i, y0_i, x1_i, y1_i, cx0_i, cy0_i, cx1_i, cy1_i);
                    index.add(x0, y0, x1, y1);
                }
            }
        }
        _render(ctx, indices, data) {
            if (this.visuals.line.doit) {
                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 (isNaN(sx0_i + sy0_i + sx1_i + sy1_i + scx0_i + scy0_i + scx1_i + scy1_i))
                        continue;
                    ctx.beginPath();
                    ctx.moveTo(sx0_i, sy0_i);
                    ctx.bezierCurveTo(scx0_i, scy0_i, scx1_i, scy1_i, sx1_i, sy1_i);
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            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);
        }
        static init_Bezier() {
            this.prototype.default_view = BezierView;
            this.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" }],
            }));
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.Bezier = Bezier;
    Bezier.__name__ = "Bezier";
    Bezier.init_Bezier();
},
/* models/glyphs/circle.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const markers_1 = require(283) /* ./webgl/markers */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const array_1 = require(9) /* ../../core/util/array */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const selection_1 = require(59) /* ../selections/selection */;
    class CircleView extends xy_glyph_1.XYGlyphView {
        initialize() {
            super.initialize();
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null) {
                this.glglyph = new markers_1.MarkerGL(webgl.gl, this, "circle");
            }
        }
        get use_radius() {
            return !(this.radius.is_Scalar() && isNaN(this.radius.value));
        }
        _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 = 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 = arrayable_1.map(sradius_x, (s, i) => Math.min(s, sradius_y[i]));
                            break;
                        }
                    }
                }
                else {
                    this.sradius = types_1.to_screen(this.radius);
                    this._configure("max_size", { value: 2 * this.max_radius });
                }
            }
            else {
                const ssize = new types_1.ScreenArray(this.size);
                this.sradius = 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 (isNaN(sx_i + sy_i + sradius_i))
                    continue;
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sradius_i, 0, 2 * Math.PI, false);
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        _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;
            let x0, x1, y0, y1;
            if (this.use_radius && this.model.properties.radius.units == "data") {
                x0 = x - this.max_radius * hit_dilation;
                x1 = x + this.max_radius * hit_dilation;
                y0 = y - this.max_radius * hit_dilation;
                y1 = y + this.max_radius * hit_dilation;
            }
            else {
                const sx0 = sx - this.max_size * hit_dilation;
                const sx1 = sx + this.max_size * hit_dilation;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                const sy0 = sy - this.max_size * hit_dilation;
                const sy1 = sy + this.max_size * hit_dilation;
                [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            }
            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();
            let x0, x1, y0, y1;
            if (geometry.direction == 'h') {
                // use circle bounds instead of current pointer y coordinates
                let sx0, sx1;
                y0 = bounds.y0;
                y1 = bounds.y1;
                if (this.use_radius && this.model.properties.radius.units == "data") {
                    sx0 = sx - this.max_radius;
                    sx1 = sx + this.max_radius;
                    [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                }
                else {
                    const ms = this.max_size / 2;
                    sx0 = sx - ms;
                    sx1 = sx + ms;
                    [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                }
            }
            else {
                // use circle bounds instead of current pointer x coordinates
                let sy0, sy1;
                x0 = bounds.x0;
                x1 = bounds.x1;
                if (this.use_radius && this.model.properties.radius.units == "data") {
                    sy0 = sy - this.max_radius;
                    sy1 = sy + this.max_radius;
                    [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                }
                else {
                    const ms = this.max_size / 2;
                    sy0 = sy - ms;
                    sy1 = sy + ms;
                    [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_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, sy } = geometry;
            // TODO (bev) use spatial index to pare candidate list
            const candidates = array_1.range(0, this.sx.length);
            const indices = [];
            for (let i = 0, end = candidates.length; i < end; i++) {
                const index = candidates[i];
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices });
        }
        // 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);
        }
        static init_Circle() {
            this.prototype.default_view = CircleView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({ Number }) => ({
                angle: [p.AngleSpec, 0],
                size: [p.ScreenDistanceSpec, { value: 4 }],
                radius: [p.NullDistanceSpec, null],
                radius_dimension: [enums_1.RadiusDimension, "x"],
                hit_dilation: [Number, 1.0],
            }));
        }
    }
    exports.Circle = Circle;
    Circle.__name__ = "Circle";
    Circle.init_Circle();
},
/* models/glyphs/webgl/markers.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const utils_1 = require(109) /* ./utils */;
    const base_1 = require(113) /* ./base */;
    const markers_vert_1 = tslib_1.__importDefault(require(284) /* ./markers.vert */);
    const markers_frag_1 = tslib_1.__importDefault(require(285) /* ./markers.frag */);
    const circle_1 = require(282) /* ../circle */;
    const arrayable_1 = require(12) /* ../../../core/util/arrayable */;
    const logging_1 = require(19) /* ../../../core/logging */;
    const types_1 = require(24) /* ../../../core/types */;
    const color_1 = require(22) /* ../../../core/util/color */;
    const assert_1 = require(11) /* ../../../core/util/assert */;
    function attach_float(prog, vbo, att_name, n, visual, prop) {
        // Attach a float attribute to the program. Use singleton value if we can,
        // otherwise use VBO to apply array.
        if (!visual.doit) {
            vbo.used = false;
            prog.set_attribute(att_name, 'float', [0]);
        }
        else if (prop.is_Scalar()) {
            vbo.used = false;
            prog.set_attribute(att_name, 'float', [prop.value]);
        }
        else if (prop.is_Vector()) {
            vbo.used = true;
            const a = new Float32Array(prop.array); // TODO: .buffer
            vbo.set_size(n * 4);
            vbo.set_data(0, a);
            prog.set_attribute(att_name, 'float', vbo);
        }
    }
    function attach_color(prog, vbo, att_name, n, visual, color_prop, alpha_prop) {
        // Attach the color attribute to the program. If there's just one color,
        // then use this single color for all vertices (no VBO). Otherwise we
        // create an array and upload that to the VBO, which we attahce to the prog.
        if (!visual.doit) {
            // Don't draw (draw transparent)
            vbo.used = false;
            prog.set_attribute(att_name, 'vec4', [0, 0, 0, 0]);
        }
        else if (color_prop.is_Scalar() && alpha_prop.is_Scalar()) {
            vbo.used = false;
            const [r, g, b, a] = color_1.color2rgba(color_prop.value, alpha_prop.value);
            prog.set_attribute(att_name, 'vec4', [r / 255, g / 255, b / 255, a / 255]);
        }
        else {
            vbo.used = true;
            let colors;
            if (color_prop.is_Vector()) {
                // TODO: compose alpha in visuals or earlier to avoid this copy
                const array = new types_1.ColorArray(color_prop.array);
                colors = new types_1.RGBAArray(array.buffer);
                if (!(alpha_prop.is_Scalar() && alpha_prop.value == 1.0)) {
                    for (let i = 0; i < n; i++) {
                        const k = 4 * i + 3;
                        const a = colors[k];
                        if (a == 255) {
                            colors[k] = alpha_prop.get(i) * 255;
                        }
                    }
                }
            }
            else if (color_prop.is_Scalar() && alpha_prop.is_Vector()) {
                const array = new types_1.ColorArray(n);
                array.fill(color_prop.value);
                colors = new types_1.RGBAArray(array.buffer);
                for (let i = 0; i < n; i++) {
                    for (let i = 0; i < n; i++) {
                        const k = 4 * i + 3;
                        const a = colors[k];
                        if (a == 255) {
                            colors[k] = alpha_prop.get(i) * 255;
                        }
                    }
                }
            }
            else
                assert_1.unreachable();
            // Attach vbo
            vbo.set_size(4 * n);
            vbo.set_data(0, colors);
            prog.set_attribute(att_name, 'vec4_uint8', vbo, 0, 0, true);
        }
    }
    // Base class for markers. All markers share the same GLSL, except for one
    // function that defines the marker geometry.
    class MarkerGL extends base_1.BaseGLGlyph {
        constructor(gl, glyph, marker_type) {
            super(gl, glyph);
            this.glyph = glyph;
            this.marker_type = marker_type;
            const defs = [`#define USE_${marker_type.toUpperCase()}`];
            const vert = markers_vert_1.default;
            const frag = `${defs.join("\n")}\n\n${markers_frag_1.default}`;
            // The program
            this.prog = new utils_1.Program(gl);
            this.prog.set_shaders(vert, frag);
            // Real attributes
            this.vbo_sx = new utils_1.VertexBuffer(gl);
            this.prog.set_attribute('a_sx', 'float', this.vbo_sx);
            this.vbo_sy = new utils_1.VertexBuffer(gl);
            this.prog.set_attribute('a_sy', 'float', this.vbo_sy);
            this.vbo_s = new utils_1.VertexBuffer(gl);
            this.prog.set_attribute('a_size', 'float', this.vbo_s);
            this.vbo_a = new utils_1.VertexBuffer(gl);
            this.prog.set_attribute('a_angle', 'float', this.vbo_a);
            // VBO's for attributes (they may not be used if value is singleton)
            this.vbo_linewidth = new utils_1.VertexBuffer(gl);
            this.vbo_fg_color = new utils_1.VertexBuffer(gl);
            this.vbo_bg_color = new utils_1.VertexBuffer(gl);
            this.index_buffer = new utils_1.IndexBuffer(gl);
        }
        static is_supported(marker_type) {
            switch (marker_type) {
                case "asterisk":
                case "circle":
                case "circle_cross":
                case "circle_x":
                case "cross":
                case "diamond":
                case "diamond_cross":
                case "hex":
                case "inverted_triangle":
                case "square":
                case "square_cross":
                case "square_x":
                case "star":
                case "triangle":
                case "x":
                    return true;
                default:
                    return false;
            }
        }
        draw(indices, main_glyph, trans) {
            // The main glyph has the data, *this* glyph has the visuals.
            const mainGlGlyph = main_glyph.glglyph;
            const { nvertices } = mainGlGlyph;
            // Upload data if we must. Only happens for main glyph.
            if (mainGlGlyph.data_changed) {
                mainGlGlyph._set_data(nvertices);
                if (this.glyph instanceof circle_1.CircleView && this.glyph.radius != null) {
                    // Keep screen radius up-to-date for circle glyph. Only happens when a radius is given
                    this.vbo_s.set_data(0, arrayable_1.map(this.glyph.sradius, (s) => s * 2));
                }
                mainGlGlyph.data_changed = false;
            }
            // Update visuals if we must. Can happen for all glyphs.
            if (this.visuals_changed) {
                this._set_visuals(nvertices);
                this.visuals_changed = false;
            }
            // Handle transformation to device coordinates
            this.prog.set_uniform('u_pixel_ratio', 'float', [trans.pixel_ratio]);
            this.prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height]);
            // Select buffers from main glyph
            // (which may be this glyph but maybe not if this is a (non)selection glyph)
            this.prog.set_attribute('a_sx', 'float', mainGlGlyph.vbo_sx);
            this.prog.set_attribute('a_sy', 'float', mainGlGlyph.vbo_sy);
            this.prog.set_attribute('a_size', 'float', mainGlGlyph.vbo_s);
            this.prog.set_attribute('a_angle', 'float', mainGlGlyph.vbo_a);
            // Draw directly or using indices. Do not handle indices if they do not
            // fit in a uint16; WebGL 1.0 does not support uint32.
            if (indices.length == 0)
                return;
            else if (indices.length === nvertices)
                this.prog.draw(this.gl.POINTS, [0, nvertices]);
            else if (nvertices < 65535) {
                // On IE the marker size is reduced to 1 px when using an index buffer
                // A MS Edge dev on Twitter said on 24-04-2014: "gl_PointSize > 1.0 works
                // in DrawArrays; gl_PointSize > 1.0 in DrawElements is coming soon in the
                // next renderer update.
                const ua = window.navigator.userAgent;
                if ((ua.indexOf("MSIE ") + ua.indexOf("Trident/") + ua.indexOf("Edge/")) > 0) {
                    logging_1.logger.warn('WebGL warning: IE is known to produce 1px sprites whith selections.');
                }
                this.index_buffer.set_size(indices.length * 2);
                this.index_buffer.set_data(0, new Uint16Array(indices));
                this.prog.draw(this.gl.POINTS, this.index_buffer);
            }
            else {
                // Work around the limit that the indexbuffer must be uint16. We draw in chunks.
                // First collect indices in chunks
                const chunksize = 64000; // 65536
                const chunks = [];
                for (let i = 0, end = Math.ceil(nvertices / chunksize); i < end; i++) {
                    chunks.push([]);
                }
                for (let i = 0, end = indices.length; i < end; i++) {
                    const uint16_index = indices[i] % chunksize;
                    const chunk = Math.floor(indices[i] / chunksize);
                    chunks[chunk].push(uint16_index);
                }
                // Then draw each chunk
                for (let chunk = 0, end = chunks.length; chunk < end; chunk++) {
                    const these_indices = new Uint16Array(chunks[chunk]);
                    const offset = chunk * chunksize * 4;
                    if (these_indices.length === 0) {
                        continue;
                    }
                    this.prog.set_attribute('a_sx', 'float', mainGlGlyph.vbo_sx, 0, offset);
                    this.prog.set_attribute('a_sy', 'float', mainGlGlyph.vbo_sy, 0, offset);
                    this.prog.set_attribute('a_size', 'float', mainGlGlyph.vbo_s, 0, offset);
                    this.prog.set_attribute('a_angle', 'float', mainGlGlyph.vbo_a, 0, offset);
                    if (this.vbo_linewidth.used) {
                        this.prog.set_attribute('a_linewidth', 'float', this.vbo_linewidth, 0, offset);
                    }
                    if (this.vbo_fg_color.used) {
                        this.prog.set_attribute('a_fg_color', 'vec4_uint8', this.vbo_fg_color, 0, offset * 4, true);
                    }
                    if (this.vbo_bg_color.used) {
                        this.prog.set_attribute('a_bg_color', 'vec4_uint8', this.vbo_bg_color, 0, offset * 4, true);
                    }
                    // The actual drawing
                    this.index_buffer.set_size(these_indices.length * 2);
                    this.index_buffer.set_data(0, these_indices);
                    this.prog.draw(this.gl.POINTS, this.index_buffer);
                }
            }
        }
        _set_data(nvertices) {
            const n = nvertices * 4; // in bytes
            // Set buffer size
            this.vbo_sx.set_size(n);
            this.vbo_sy.set_size(n);
            this.vbo_a.set_size(n);
            this.vbo_s.set_size(n);
            this.vbo_sx.set_data(0, this.glyph.sx);
            this.vbo_sy.set_data(0, this.glyph.sy);
            if (this.glyph.angle != null) {
                this.vbo_a.set_data(0, new Float32Array(this.glyph.angle)); // TODO: use attach_float()
            }
            if (this.glyph instanceof circle_1.CircleView && this.glyph.radius != null)
                this.vbo_s.set_data(0, arrayable_1.map(this.glyph.sradius, (s) => s * 2));
            else
                this.vbo_s.set_data(0, new Float32Array(this.glyph.size));
        }
        _set_visuals(nvertices) {
            const { line, fill } = this.glyph.visuals;
            attach_float(this.prog, this.vbo_linewidth, 'a_linewidth', nvertices, line, line.line_width);
            attach_color(this.prog, this.vbo_fg_color, 'a_fg_color', nvertices, line, line.line_color, line.line_alpha);
            attach_color(this.prog, this.vbo_bg_color, 'a_bg_color', nvertices, fill, fill.fill_color, fill.fill_alpha);
            // Static value for antialias. Smaller aa-region to obtain crisper images
            this.prog.set_uniform('u_antialias', 'float', [0.8]);
        }
    }
    exports.MarkerGL = MarkerGL;
    MarkerGL.__name__ = "MarkerGL";
},
/* models/glyphs/webgl/markers.vert.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const shader = `
precision mediump float;
const float SQRT_2 = 1.4142135623730951;
//
uniform float u_pixel_ratio;
uniform vec2 u_canvas_size;
uniform vec2 u_offset;
uniform vec2 u_scale;
uniform float u_antialias;
//
attribute float a_sx;
attribute float a_sy;
attribute float a_size;
attribute float a_angle;  // in radians
attribute float a_linewidth;
attribute vec4  a_fg_color;
attribute vec4  a_bg_color;
//
varying float v_linewidth;
varying float v_size;
varying vec4  v_fg_color;
varying vec4  v_bg_color;
varying vec2  v_rotation;

void main (void)
{
    v_size = a_size * u_pixel_ratio;
    v_linewidth = a_linewidth * u_pixel_ratio;
    v_fg_color = a_fg_color;
    v_bg_color = a_bg_color;
    v_rotation = vec2(cos(-a_angle), sin(-a_angle));
    vec2 pos = vec2(a_sx, a_sy);  // in pixels
    pos += 0.5;  // make up for Bokeh's offset
    pos /= u_canvas_size / u_pixel_ratio;  // in 0..1
    gl_Position = vec4(pos*2.0-1.0, 0.0, 1.0);
    gl_Position.y *= -1.0;
    gl_PointSize = SQRT_2 * v_size + 2.0 * (v_linewidth + 1.5*u_antialias);
}
`;
    exports.default = shader;
},
/* models/glyphs/webgl/markers.frag.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const shader = `
precision mediump float;

const float SQRT_2 = 1.4142135623730951;
const float PI = 3.14159265358979323846264;

const float IN_ANGLE = 0.6283185307179586; // PI/5. = 36 degrees (star of 5 pikes)
//const float OUT_ANGLE = PI/2. - IN_ANGLE; // External angle for regular stars
const float COS_A = 0.8090169943749475; // cos(IN_ANGLE)
const float SIN_A = 0.5877852522924731; // sin(IN_ANGLE)
const float COS_B = 0.5877852522924731; // cos(OUT_ANGLE)
const float SIN_B = 0.8090169943749475; // sin(OUT_ANGLE)

//
uniform float u_antialias;
//
varying vec4  v_fg_color;
varying vec4  v_bg_color;
varying float v_linewidth;
varying float v_size;
varying vec2  v_rotation;

#ifdef USE_ASTERISK
// asterisk
float marker(vec2 P, float size)
{
    // Masks
    float diamond = max(abs(SQRT_2 / 2.0 * (P.x - P.y)), abs(SQRT_2 / 2.0 * (P.x + P.y))) - size / (2.0 * SQRT_2);
    float square = max(abs(P.x), abs(P.y)) - size / (2.0 * SQRT_2);
    // Shapes
    float X = min(abs(P.x - P.y), abs(P.x + P.y)) - size / 100.0;  // bit of "width" for aa
    float cross = min(abs(P.x), abs(P.y)) - size / 100.0;  // bit of "width" for aa
    // Result is union of masked shapes
    return min(max(X, diamond), max(cross, square));
}
#endif

#ifdef USE_CIRCLE
// circle
float marker(vec2 P, float size)
{
    return length(P) - size/2.0;
}
#endif

#ifdef USE_SQUARE
// square
float marker(vec2 P, float size)
{
    return max(abs(P.x), abs(P.y)) - size/2.0;
}
#endif

#ifdef USE_DIAMOND
// diamond
float marker(vec2 P, float size)
{
    float x = SQRT_2 / 2.0 * (P.x * 1.5 - P.y);
    float y = SQRT_2 / 2.0 * (P.x * 1.5 + P.y);
    float r1 = max(abs(x), abs(y)) - size / (2.0 * SQRT_2);
    return r1 / SQRT_2;
}
#endif

#ifdef USE_HEX
// hex
float marker(vec2 P, float size)
{
    vec2 q = abs(P);
    return max(q.y * 0.57735 + q.x - 1.0 * size/2.0, q.y - 0.866 * size/2.0);
}
#endif

#ifdef USE_STAR
// star
// https://iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm
float marker(vec2 P, float size)
{
    float bn = mod(atan(P.x, -P.y), 2.0*IN_ANGLE) - IN_ANGLE;
    P = length(P)*vec2(cos(bn), abs(sin(bn)));
    P -= size*vec2(COS_A, SIN_A)/2.;
    P += vec2(COS_B, SIN_B)*clamp(-(P.x*COS_B + P.y*SIN_B), 0.0, size*SIN_A/SIN_B/2.);

    return length(P)*sign(P.x);
}
#endif

#ifdef USE_TRIANGLE
// triangle
float marker(vec2 P, float size)
{
    P.y -= size * 0.3;
    float x = SQRT_2 / 2.0 * (P.x * 1.7 - P.y);
    float y = SQRT_2 / 2.0 * (P.x * 1.7 + P.y);
    float r1 = max(abs(x), abs(y)) - size / 1.6;
    float r2 = P.y;
    return max(r1 / SQRT_2, r2);  // Intersect diamond with rectangle
}
#endif

#ifdef USE_INVERTED_TRIANGLE
// inverted_triangle
float marker(vec2 P, float size)
{
    P.y += size * 0.3;
    float x = SQRT_2 / 2.0 * (P.x * 1.7 - P.y);
    float y = SQRT_2 / 2.0 * (P.x * 1.7 + P.y);
    float r1 = max(abs(x), abs(y)) - size / 1.6;
    float r2 = - P.y;
    return max(r1 / SQRT_2, r2);  // Intersect diamond with rectangle
}
#endif

#ifdef USE_CROSS
// cross
float marker(vec2 P, float size)
{
    float square = max(abs(P.x), abs(P.y)) - size / 2.5;   // 2.5 is a tweak
    float cross = min(abs(P.x), abs(P.y)) - size / 100.0;  // bit of "width" for aa
    return max(square, cross);
}
#endif

#ifdef USE_CIRCLE_CROSS
// circle_cross
float marker(vec2 P, float size)
{
    // Define quadrants
    float qs = size / 2.0;  // quadrant size
    float s1 = max(abs(P.x - qs), abs(P.y - qs)) - qs;
    float s2 = max(abs(P.x + qs), abs(P.y - qs)) - qs;
    float s3 = max(abs(P.x - qs), abs(P.y + qs)) - qs;
    float s4 = max(abs(P.x + qs), abs(P.y + qs)) - qs;
    // Intersect main shape with quadrants (to form cross)
    float circle = length(P) - size/2.0;
    float c1 = max(circle, s1);
    float c2 = max(circle, s2);
    float c3 = max(circle, s3);
    float c4 = max(circle, s4);
    // Union
    return min(min(min(c1, c2), c3), c4);
}
#endif

#ifdef USE_SQUARE_CROSS
// square_cross
float marker(vec2 P, float size)
{
    // Define quadrants
    float qs = size / 2.0;  // quadrant size
    float s1 = max(abs(P.x - qs), abs(P.y - qs)) - qs;
    float s2 = max(abs(P.x + qs), abs(P.y - qs)) - qs;
    float s3 = max(abs(P.x - qs), abs(P.y + qs)) - qs;
    float s4 = max(abs(P.x + qs), abs(P.y + qs)) - qs;
    // Intersect main shape with quadrants (to form cross)
    float square = max(abs(P.x), abs(P.y)) - size/2.0;
    float c1 = max(square, s1);
    float c2 = max(square, s2);
    float c3 = max(square, s3);
    float c4 = max(square, s4);
    // Union
    return min(min(min(c1, c2), c3), c4);
}
#endif

#ifdef USE_DIAMOND_CROSS
// diamond_cross
float marker(vec2 P, float size)
{
    // Define quadrants
    float qs = size / 2.0;  // quadrant size
    float s1 = max(abs(P.x - qs), abs(P.y - qs)) - qs;
    float s2 = max(abs(P.x + qs), abs(P.y - qs)) - qs;
    float s3 = max(abs(P.x - qs), abs(P.y + qs)) - qs;
    float s4 = max(abs(P.x + qs), abs(P.y + qs)) - qs;
    // Intersect main shape with quadrants (to form cross)
    float x = SQRT_2 / 2.0 * (P.x * 1.5 - P.y);
    float y = SQRT_2 / 2.0 * (P.x * 1.5 + P.y);
    float diamond = max(abs(x), abs(y)) - size / (2.0 * SQRT_2);
    diamond /= SQRT_2;
    float c1 = max(diamond, s1);
    float c2 = max(diamond, s2);
    float c3 = max(diamond, s3);
    float c4 = max(diamond, s4);
    // Union
    return min(min(min(c1, c2), c3), c4);
}
#endif

#ifdef USE_X
// x
float marker(vec2 P, float size)
{
    float circle = length(P) - size / 1.6;
    float X = min(abs(P.x - P.y), abs(P.x + P.y)) - size / 100.0;  // bit of "width" for aa
    return max(circle, X);
}
#endif

#ifdef USE_CIRCLE_X
// circle_x
float marker(vec2 P, float size)
{
    float x = P.x - P.y;
    float y = P.x + P.y;
    // Define quadrants
    float qs = size / 2.0;  // quadrant size
    float s1 = max(abs(x - qs), abs(y - qs)) - qs;
    float s2 = max(abs(x + qs), abs(y - qs)) - qs;
    float s3 = max(abs(x - qs), abs(y + qs)) - qs;
    float s4 = max(abs(x + qs), abs(y + qs)) - qs;
    // Intersect main shape with quadrants (to form cross)
    float circle = length(P) - size/2.0;
    float c1 = max(circle, s1);
    float c2 = max(circle, s2);
    float c3 = max(circle, s3);
    float c4 = max(circle, s4);
    // Union
    float almost = min(min(min(c1, c2), c3), c4);
    // In this case, the X is also outside of the main shape
    float Xmask = length(P) - size / 1.6;  // a circle
    float X = min(abs(P.x - P.y), abs(P.x + P.y)) - size / 100.0;  // bit of "width" for aa
    return min(max(X, Xmask), almost);
}
#endif

#ifdef USE_SQUARE_X
// square_x
float marker(vec2 P, float size)
{
    float x = P.x - P.y;
    float y = P.x + P.y;
    // Define quadrants
    float qs = size / 2.0;  // quadrant size
    float s1 = max(abs(x - qs), abs(y - qs)) - qs;
    float s2 = max(abs(x + qs), abs(y - qs)) - qs;
    float s3 = max(abs(x - qs), abs(y + qs)) - qs;
    float s4 = max(abs(x + qs), abs(y + qs)) - qs;
    // Intersect main shape with quadrants (to form cross)
    float square = max(abs(P.x), abs(P.y)) - size/2.0;
    float c1 = max(square, s1);
    float c2 = max(square, s2);
    float c3 = max(square, s3);
    float c4 = max(square, s4);
    // Union
    return min(min(min(c1, c2), c3), c4);
}
#endif

vec4 outline(float distance, float linewidth, float antialias, vec4 fg_color, vec4 bg_color)
{
    vec4 frag_color;
    float t = linewidth/2.0 - antialias;
    float signed_distance = distance;
    float border_distance = abs(signed_distance) - t;
    float alpha = border_distance/antialias;
    alpha = exp(-alpha*alpha);

    // If fg alpha is zero, it probably means no outline. To avoid a dark outline
    // shining through due to aa, we set the fg color to the bg color. Avoid if (i.e. branching).
    float select = float(bool(fg_color.a));
    fg_color.rgb = select * fg_color.rgb + (1.0  - select) * bg_color.rgb;
    // Similarly, if we want a transparent bg
    select = float(bool(bg_color.a));
    bg_color.rgb = select * bg_color.rgb + (1.0  - select) * fg_color.rgb;

    if( border_distance < 0.0)
        frag_color = fg_color;
    else if( signed_distance < 0.0 ) {
        frag_color = mix(bg_color, fg_color, sqrt(alpha));
    } else {
        if( abs(signed_distance) < (linewidth/2.0 + antialias) ) {
            frag_color = vec4(fg_color.rgb, fg_color.a * alpha);
        } else {
            discard;
        }
    }
    return frag_color;
}

void main()
{
    vec2 P = gl_PointCoord.xy - vec2(0.5, 0.5);
    P = vec2(v_rotation.x*P.x - v_rotation.y*P.y,
             v_rotation.y*P.x + v_rotation.x*P.y);
    float point_size = SQRT_2*v_size  + 2.0 * (v_linewidth + 1.5*u_antialias);
    float distance = marker(P*point_size, v_size);
    gl_FragColor = outline(distance, v_linewidth, u_antialias, v_fg_color, v_bg_color);
}
`;
    exports.default = shader;
},
/* models/glyphs/ellipse.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ellipse_oval_1 = require(287) /* ./ellipse_oval */;
    class EllipseView extends ellipse_oval_1.EllipseOvalView {
    }
    exports.EllipseView = EllipseView;
    EllipseView.__name__ = "EllipseView";
    class Ellipse extends ellipse_oval_1.EllipseOval {
        constructor(attrs) {
            super(attrs);
        }
        static init_Ellipse() {
            this.prototype.default_view = EllipseView;
        }
    }
    exports.Ellipse = Ellipse;
    Ellipse.__name__ = "Ellipse";
    Ellipse.init_Ellipse();
},
/* models/glyphs/ellipse_oval.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const center_rotatable_1 = require(288) /* ./center_rotatable */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const types_1 = require(24) /* ../../core/types */;
    const selection_1 = require(59) /* ../selections/selection */;
    class EllipseOvalView 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 = 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 = 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 (isNaN(sx_i + sy_i + sw_i + sh_i + angle_i))
                    continue;
                ctx.beginPath();
                ctx.ellipse(sx_i, sy_i, sw_i / 2.0, sh_i / 2.0, angle_i, 0, 2 * Math.PI);
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        _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 len = index + 1;
            const sx = new Array(len);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(len);
            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(len);
            const sh = new Array(len);
            if (scale > 1) {
                sw[index] = d;
                sh[index] = d / scale;
            }
            else {
                sw[index] = d * scale;
                sh[index] = d;
            }
            this._render(ctx, [index], { sx, sy, sw, sh, _angle: [0] }); // XXX
        }
    }
    exports.EllipseOvalView = EllipseOvalView;
    EllipseOvalView.__name__ = "EllipseOvalView";
    class EllipseOval extends center_rotatable_1.CenterRotatable {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.EllipseOval = EllipseOval;
    EllipseOval.__name__ = "EllipseOval";
},
/* models/glyphs/center_rotatable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const property_mixins_1 = require(48) /* ../../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);
        }
        static init_CenterRotatable() {
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({}) => ({
                angle: [p.AngleSpec, 0],
                width: [p.DistanceSpec, { field: "width" }],
                height: [p.DistanceSpec, { field: "height" }],
            }));
        }
    }
    exports.CenterRotatable = CenterRotatable;
    CenterRotatable.__name__ = "CenterRotatable";
    CenterRotatable.init_CenterRotatable();
},
/* models/glyphs/hbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const box_1 = require(290) /* ./box */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class HBarView extends box_1.BoxView {
        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 box_1.Box {
        constructor(attrs) {
            super(attrs);
        }
        static init_HBar() {
            this.prototype.default_view = HBarView;
            this.define(({}) => ({
                left: [p.XCoordinateSpec, { value: 0 }],
                y: [p.YCoordinateSpec, { field: "y" }],
                height: [p.NumberSpec, { value: 1 }],
                right: [p.XCoordinateSpec, { field: "right" }],
            }));
        }
    }
    exports.HBar = HBar;
    HBar.__name__ = "HBar";
    HBar.init_HBar();
},
/* models/glyphs/box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const glyph_1 = require(98) /* ./glyph */;
    const utils_1 = require(106) /* ./utils */;
    const selection_1 = require(59) /* ../selections/selection */;
    class BoxView extends glyph_1.GlyphView {
        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 };
            }
        }
        _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);
                if (isNaN(l + r + t + b) || !isFinite(l + r + t + b))
                    index.add_empty();
                else
                    index.add(min(l, r), min(t, b), max(r, l), max(t, b));
            }
        }
        _render(ctx, indices, data) {
            const { sleft, sright, stop, sbottom } = 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 (isNaN(sleft_i + stop_i + sright_i + sbottom_i))
                    continue;
                // XXX: this is needed for SVG canvas, because fill and hatch visuals
                // share Context2d.fillStyle, which gets overriden in SVG, instead of
                // causing overpaint (as in canvas).
                function path() {
                    ctx.beginPath();
                    ctx.rect(sleft_i, stop_i, sright_i - sleft_i, sbottom_i - stop_i);
                }
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    path();
                    ctx.fill();
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    path();
                    ctx.fill();
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    path();
                    ctx.stroke();
                }
            }
        }
        // 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) {
            utils_1.generic_area_vector_legend(this.visuals, ctx, bbox, index);
        }
    }
    exports.BoxView = BoxView;
    BoxView.__name__ = "BoxView";
    class Box extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
        static init_Box() {
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        }
    }
    exports.Box = Box;
    Box.__name__ = "Box";
    Box.init_Box();
},
/* models/glyphs/hex_tile.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(98) /* ./glyph */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const enums_1 = require(20) /* ../../core/enums */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    const utils_1 = require(106) /* ./utils */;
    const selection_1 = require(59) /* ../selections/selection */;
    class HexTileView extends glyph_1.GlyphView {
        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];
                if (isNaN(x + y) || !isFinite(x + y))
                    index.add_empty();
                else
                    index.add(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() {
            [this.sx, this.sy] = this.renderer.coordinates.map_to_screen(this._x, this._y);
            [this.svx, this.svy] = this._get_unscaled_vertices();
        }
        _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 (isNaN(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);
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        _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) {
            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);
        }
        static init_HexTile() {
            this.prototype.default_view = HexTileView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.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"],
            }));
            this.override({ line_color: null });
        }
    }
    exports.HexTile = HexTile;
    HexTile.__name__ = "HexTile";
    HexTile.init_HexTile();
},
/* models/glyphs/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const image_base_1 = require(293) /* ./image_base */;
    const color_mapper_1 = require(203) /* ../mappers/color_mapper */;
    const linear_color_mapper_1 = require(214) /* ../mappers/linear_color_mapper */;
    class ImageView extends image_base_1.ImageBaseView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.color_mapper.change, () => this._update_image());
        }
        _update_image() {
            // 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);
        }
        static init_Image() {
            this.prototype.default_view = ImageView;
            this.define(({ Ref }) => ({
                color_mapper: [Ref(color_mapper_1.ColorMapper), () => new linear_color_mapper_1.LinearColorMapper({ palette: Greys9() })],
            }));
        }
    }
    exports.Image = Image;
    Image.__name__ = "Image";
    Image.init_Image();
},
/* models/glyphs/image_base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(59) /* ../selections/selection */;
    const array_1 = require(9) /* ../../core/util/array */;
    const ndarray_1 = require(29) /* ../../core/util/ndarray */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    class ImageBaseView extends xy_glyph_1.XYGlyphView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.global_alpha.change, () => this.renderer.request_render());
        }
        _render(ctx, indices, data) {
            const { image_data, sx, sy, sw, sh } = data !== null && data !== void 0 ? data : this;
            const old_smoothing = ctx.getImageSmoothingEnabled();
            ctx.setImageSmoothingEnabled(false);
            ctx.globalAlpha = this.model.global_alpha;
            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 || isNaN(sx_i + sy_i + sw_i + sh_i))
                    continue;
                const y_offset = sy_i;
                ctx.translate(0, y_offset);
                ctx.scale(1, -1);
                ctx.translate(0, -y_offset);
                ctx.drawImage(image_data_i, sx_i | 0, sy_i | 0, sw_i, sh_i);
                ctx.translate(0, y_offset);
                ctx.scale(1, -1);
                ctx.translate(0, -y_offset);
            }
            ctx.setImageSmoothingEnabled(old_smoothing);
        }
        _set_data(indices) {
            this._set_width_heigh_data();
            for (let i = 0, end = this.image.length; i < end; i++) {
                if (indices != null && indices.indexOf(i) < 0)
                    continue;
                const img = this.image.get(i);
                let flat_img;
                if (ndarray_1.is_NDArray(img)) {
                    assert_1.assert(img.dimension == 2, "expected a 2D array");
                    flat_img = img;
                    this._height[i] = img.shape[0];
                    this._width[i] = img.shape[1];
                }
                else {
                    flat_img = array_1.concat(img);
                    this._height[i] = img.length;
                    this._width[i] = img[0].length;
                }
                const buf8 = this._flat_img_to_buf8(flat_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);
                if (isNaN(l + r + t + b) || !isFinite(l + r + t + b))
                    index.add_empty();
                else
                    index.add(l, b, r, t);
            }
        }
        _lrtb(i) {
            const dw_i = this.dw.get(i);
            const dh_i = this.dh.get(i);
            const xr = this.renderer.xscale.source_range;
            const x1 = this._x[i];
            const x2 = xr.is_reversed ? x1 - dw_i : x1 + dw_i;
            const yr = this.renderer.yscale.source_range;
            const y1 = this._y[i];
            const y2 = yr.is_reversed ? y1 - dh_i : y1 + dh_i;
            const [l, r] = x1 < x2 ? [x1, x2] : [x2, x1];
            const [b, t] = y1 < y2 ? [y1, y2] : [y2, y1];
            return [l, r, t, b];
        }
        _set_width_heigh_data() {
            if (this.image_data == null || this.image_data.length != this.image.length)
                this.image_data = new Array(this.image.length);
            if (this._width == null || this._width.length != this.image.length)
                this._width = new Uint32Array(this.image.length);
            if (this._height == null || this._height.length != this.image.length)
                this._height = new Uint32Array(this.image.length);
        }
        _get_or_create_canvas(i) {
            const _image_data = this.image_data[i];
            if (_image_data != null && _image_data.width == this._width[i] &&
                _image_data.height == this._height[i])
                return _image_data;
            else {
                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 = 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 = 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 dim1 = Math.floor((x - l) / dx);
            let dim2 = Math.floor((y - b) / dy);
            if (this.renderer.xscale.source_range.is_reversed)
                dim1 = width - dim1 - 1;
            if (this.renderer.yscale.source_range.is_reversed)
                dim2 = height - dim2 - 1;
            return { index, dim1, dim2, flat_index: dim2 * width + dim1 };
        }
        _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();
            for (const index of candidates) {
                if (sx != Infinity && sy != Infinity) {
                    result.image_indices.push(this._image_index(index, x, y));
                }
            }
            return result;
        }
    }
    exports.ImageBaseView = ImageBaseView;
    ImageBaseView.__name__ = "ImageBaseView";
    class ImageBase extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static init_ImageBase() {
            this.define(({ Boolean, Alpha }) => ({
                image: [p.NDArraySpec, { field: "image" }],
                dw: [p.DistanceSpec, { field: "dw" }],
                dh: [p.DistanceSpec, { field: "dh" }],
                dilate: [Boolean, false],
                global_alpha: [Alpha, 1.0],
            }));
        }
    }
    exports.ImageBase = ImageBase;
    ImageBase.__name__ = "ImageBase";
    ImageBase.init_ImageBase();
},
/* models/glyphs/image_rgba.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const image_base_1 = require(293) /* ./image_base */;
    const types_1 = require(8) /* ../../core/util/types */;
    class ImageRGBAView extends image_base_1.ImageBaseView {
        _flat_img_to_buf8(img) {
            let array;
            if (types_1.isArray(img)) {
                array = new Uint32Array(img);
            }
            else {
                array = img;
            }
            return new Uint8ClampedArray(array.buffer);
        }
    }
    exports.ImageRGBAView = ImageRGBAView;
    ImageRGBAView.__name__ = "ImageRGBAView";
    class ImageRGBA extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
        static init_ImageRGBA() {
            this.prototype.default_view = ImageRGBAView;
        }
    }
    exports.ImageRGBA = ImageRGBA;
    ImageRGBA.__name__ = "ImageRGBA";
    ImageRGBA.init_ImageRGBA();
},
/* models/glyphs/image_url.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./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(12) /* ../../core/util/arrayable */;
    const image_1 = require(296) /* ../../core/util/image */;
    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);
            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;
                new image_1.ImageLoader(url, {
                    loaded: (image) => {
                        if (this._set_data_iteration == _set_data_iteration) {
                            this.image[i] = image;
                            this.renderer.request_render();
                        }
                    },
                    attempts: retry_attempts + 1,
                    timeout: retry_timeout,
                });
            }
            const w_data = this.model.properties.w.units == "data";
            const h_data = this.model.properties.h.units == "data";
            const n = this._x.length;
            const xs = new types_1.ScreenArray(w_data ? 2 * n : n);
            const ys = new types_1.ScreenArray(h_data ? 2 * n : n);
            const { anchor } = this.model;
            function x0x1(x, w) {
                switch (anchor) {
                    case "top_left":
                    case "bottom_left":
                    case "left":
                    case "center_left":
                        return [x, x + w];
                    case "top":
                    case "top_center":
                    case "bottom":
                    case "bottom_center":
                    case "center":
                    case "center_center":
                        return [x - w / 2, x + w / 2];
                    case "top_right":
                    case "bottom_right":
                    case "right":
                    case "center_right":
                        return [x - w, x];
                }
            }
            function y0y1(y, h) {
                switch (anchor) {
                    case "top_left":
                    case "top":
                    case "top_center":
                    case "top_right":
                        return [y, y - h];
                    case "bottom_left":
                    case "bottom":
                    case "bottom_center":
                    case "bottom_right":
                        return [y + h, y];
                    case "left":
                    case "center_left":
                    case "center":
                    case "center_center":
                    case "right":
                    case "center_right":
                        return [y + h / 2, y - h / 2];
                }
            }
            // if the width/height are in screen units, don't try to include them in bounds
            if (w_data) {
                for (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] = arrayable_1.minmax(xs);
            const [y0, y1] = arrayable_1.minmax(ys);
            this._bounds_rect = { x0, x1, y0, y1 };
        }
        has_finished() {
            return super.has_finished() && this._images_rendered == true;
        }
        _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 = 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 = types_1.to_screen(this.h);
        }
        _render(ctx, indices, data) {
            const { image, sx, sy, sw, sh, angle } = data !== null && data !== void 0 ? data : this;
            // TODO (bev): take actual border width into account when clipping
            const { frame } = this.renderer.plot_view;
            ctx.rect(frame.bbox.left + 1, frame.bbox.top + 1, frame.bbox.width - 2, frame.bbox.height - 2);
            ctx.clip();
            let finished = true;
            for (const i of indices) {
                if (isNaN(sx[i] + sy[i] + angle.get(i)))
                    continue;
                const img = image[i];
                if (img == null) {
                    finished = false;
                    continue;
                }
                this._render_image(ctx, i, img, sx, sy, sw, sh, angle);
            }
            if (finished && !this._images_rendered) {
                this._images_rendered = true;
                this.notify_finished();
            }
        }
        _final_sx_sy(anchor, sx, sy, sw, sh) {
            switch (anchor) {
                case 'top_left': return [sx, sy];
                case 'top':
                case 'top_center': return [sx - (sw / 2), sy];
                case 'top_right': return [sx - sw, sy];
                case 'right':
                case 'center_right': return [sx - sw, sy - (sh / 2)];
                case 'bottom_right': return [sx - sw, sy - sh];
                case 'bottom':
                case 'bottom_center': return [sx - (sw / 2), sy - sh];
                case 'bottom_left': return [sx, sy - sh];
                case 'left':
                case 'center_left': return [sx, sy - (sh / 2)];
                case 'center':
                case 'center_center': return [sx - (sw / 2), sy - (sh / 2)];
            }
        }
        _render_image(ctx, i, image, sx, sy, sw, sh, angle) {
            if (isNaN(sw[i]))
                sw[i] = image.width;
            if (isNaN(sh[i]))
                sh[i] = image.height;
            const sw_i = sw[i];
            const sh_i = sh[i];
            const { anchor } = this.model;
            const [sx_i, sy_i] = this._final_sx_sy(anchor, sx[i], sy[i], sw_i, sh_i);
            const angle_i = angle.get(i);
            ctx.save();
            ctx.globalAlpha = this.model.global_alpha;
            const sw2 = sw_i / 2;
            const sh2 = sh_i / 2;
            if (angle_i) {
                ctx.translate(sx_i, sy_i);
                //rotation about center of image
                ctx.translate(sw2, sh2);
                ctx.rotate(angle_i);
                ctx.translate(-sw2, -sh2);
                ctx.drawImage(image, 0, 0, sw_i, sh_i);
                ctx.translate(sw2, sh2);
                ctx.rotate(-angle_i);
                ctx.translate(-sw2, -sh2);
                ctx.translate(-sx_i, -sy_i);
            }
            else
                ctx.drawImage(image, sx_i, sy_i, sw_i, sh_i);
            ctx.restore();
        }
        bounds() {
            return this._bounds_rect;
        }
    }
    exports.ImageURLView = ImageURLView;
    ImageURLView.__name__ = "ImageURLView";
    class ImageURL extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static init_ImageURL() {
            this.prototype.default_view = ImageURLView;
            this.define(({ Boolean, Int, Alpha }) => ({
                url: [p.StringSpec, { field: "url" }],
                anchor: [enums_1.Anchor, "top_left"],
                global_alpha: [Alpha, 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],
            }));
        }
    }
    exports.ImageURL = ImageURL;
    ImageURL.__name__ = "ImageURL";
    ImageURL.init_ImageURL();
},
/* core/util/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const logging_1 = require(19) /* ../logging */;
    class ImageLoader {
        constructor(url, options = {}) {
            this._image = new Image();
            this._finished = false;
            const { attempts = 1, timeout = 1 } = options;
            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 (options.failed != null)
                                options.failed();
                            return; // XXX reject(new Error(message))
                        }
                    }
                    setTimeout(() => this._image.src = url, timeout);
                };
                this._image.onload = () => {
                    this._finished = true;
                    if (options.loaded != null)
                        options.loaded(this._image);
                    resolve(this._image);
                };
                this._image.src = url;
            });
        }
        get finished() {
            return this._finished;
        }
        get image() {
            if (this._finished)
                return this._image;
            else
                throw new Error("not loaded yet");
        }
    }
    exports.ImageLoader = ImageLoader;
    ImageLoader.__name__ = "ImageLoader";
},
/* models/glyphs/multi_polygons.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const spatial_1 = require(101) /* ../../core/util/spatial */;
    const glyph_1 = require(98) /* ./glyph */;
    const utils_1 = require(106) /* ./utils */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const arrayable_2 = require(12) /* ../../core/util/arrayable */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(59) /* ../selections/selection */;
    const assert_1 = require(11) /* ../../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] = arrayable_1.minmax(xsij);
                        const [yij0, yij1] = arrayable_1.minmax(ysij);
                        xi0 = min(xi0, xij0);
                        xi1 = max(xi1, xij1);
                        yi0 = min(yi0, yij0);
                        yi1 = max(yi1, yij1);
                    }
                }
                if (!isFinite(xi0 + xi1 + yi0 + yi1))
                    index.add_empty();
                else
                    index.add(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] = arrayable_1.minmax(xsij[k]);
                            const [yij0, yij1] = arrayable_1.minmax(ysij[k]);
                            xi0 = min(xi0, xij0);
                            xi1 = max(xi1, xij1);
                            yi0 = min(yi0, yij0);
                            yi1 = max(yi1, yij1);
                        }
                    }
                }
                if (!isFinite(xi0 + xi1 + yi0 + yi1))
                    index.add_empty();
                else
                    index.add(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,
            });
        }
        _inner_loop(ctx, sx, sy) {
            ctx.beginPath();
            for (let j = 0, endj = sx.length; j < endj; j++) {
                for (let k = 0, endk = sx[j].length; k < endk; k++) {
                    const _sx = sx[j][k];
                    const _sy = sy[j][k];
                    for (let l = 0, endl = _sx.length; l < endl; l++) {
                        if (l == 0) {
                            ctx.moveTo(_sx[l], _sy[l]);
                            continue;
                        }
                        else
                            ctx.lineTo(_sx[l], _sy[l]);
                    }
                    ctx.closePath();
                }
            }
        }
        _render(ctx, indices, data) {
            if (this.visuals.fill.doit || this.visuals.line.doit) {
                const { sxs, sys } = data !== null && data !== void 0 ? data : this;
                for (const i of indices) {
                    const sx_i = sxs[i];
                    const sy_i = sys[i];
                    if (this.visuals.fill.doit) {
                        this.visuals.fill.set_vectorize(ctx, i);
                        this._inner_loop(ctx, sx_i, sy_i);
                        ctx.fill("evenodd");
                    }
                    if (this.visuals.hatch.doit) {
                        this.visuals.hatch.set_vectorize(ctx, i);
                        this._inner_loop(ctx, sx_i, sy_i);
                        ctx.fill("evenodd");
                    }
                    if (this.visuals.line.doit) {
                        this.visuals.line.set_vectorize(ctx, i);
                        this._inner_loop(ctx, sx_i, sy_i);
                        ctx.stroke();
                    }
                }
            }
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const xs = [sx0, sx1, sx1, sx0];
            const ys = [sy0, sy0, sy1, sy1];
            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 index of candidates) {
                const sxss = this.sxs[index];
                const syss = this.sys[index];
                let hit = true;
                for (let j = 0, endj = sxss.length; j < endj; j++) {
                    for (let k = 0, endk = sxss[j][0].length; k < endk; k++) {
                        const sx = sxss[j][0][k];
                        const sy = syss[j][0][k];
                        if (!hittest.point_in_poly(sx, sy, xs, ys)) {
                            hit = false;
                            break;
                        }
                    }
                    if (!hit)
                        break;
                }
                if (hit) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _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 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];
                    }
                }
            }
            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) {
            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);
        }
        static init_MultiPolygons() {
            this.prototype.default_view = MultiPolygonsView;
            this.define(({}) => ({
                xs: [p.XCoordinateSeqSeqSeqSpec, { field: "xs" }],
                ys: [p.YCoordinateSeqSeqSeqSpec, { field: "ys" }],
            }));
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        }
    }
    exports.MultiPolygons = MultiPolygons;
    MultiPolygons.__name__ = "MultiPolygons";
    MultiPolygons.init_MultiPolygons();
},
/* models/glyphs/oval.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ellipse_oval_1 = require(287) /* ./ellipse_oval */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    class OvalView extends ellipse_oval_1.EllipseOvalView {
        _map_data() {
            super._map_data();
            arrayable_1.mul(this.sw, 0.75); // oval drawn from bezier curves = ellipse with width reduced by 3/4
        }
    }
    exports.OvalView = OvalView;
    OvalView.__name__ = "OvalView";
    class Oval extends ellipse_oval_1.EllipseOval {
        constructor(attrs) {
            super(attrs);
        }
        static init_Oval() {
            this.prototype.default_view = OvalView;
        }
    }
    exports.Oval = Oval;
    Oval.__name__ = "Oval";
    Oval.init_Oval();
},
/* models/glyphs/quad.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const box_1 = require(290) /* ./box */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class QuadView extends box_1.BoxView {
        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 box_1.Box {
        constructor(attrs) {
            super(attrs);
        }
        static init_Quad() {
            this.prototype.default_view = QuadView;
            this.define(({}) => ({
                right: [p.XCoordinateSpec, { field: "right" }],
                bottom: [p.YCoordinateSpec, { field: "bottom" }],
                left: [p.XCoordinateSpec, { field: "left" }],
                top: [p.YCoordinateSpec, { field: "top" }],
            }));
        }
    }
    exports.Quad = Quad;
    Quad.__name__ = "Quad";
    Quad.init_Quad();
},
/* models/glyphs/quadratic.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    const glyph_1 = require(98) /* ./glyph */;
    const utils_1 = require(106) /* ./utils */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    // Formula from: http://pomax.nihongoresources.com/pages/bezier/
    //
    // if segment is quadratic bezier do:
    //   for both directions do:
    //     if control between start and end, compute linear bounding box
    //     otherwise, compute
    //       bound = u(1-t)^2 + 2v(1-t)t + wt^2
    //         (with t = ((u-v) / (u-2v+w)), with {u = start, v = control, w = end})
    //       if control precedes start, min = bound, otherwise max = bound
    function _qbb(u, v, w) {
        if (v == (u + w) / 2)
            return [u, w];
        else {
            const t = (u - v) / ((u - (2 * v)) + w);
            const bd = (u * (1 - t) ** 2) + (2 * v * (1 - t) * t) + (w * t ** 2);
            return [Math.min(u, w, bd), Math.max(u, w, bd)];
        }
    }
    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 (isNaN(x0_i + x1_i + y0_i + y1_i + cx_i + cy_i))
                    index.add_empty();
                else {
                    const [x0, x1] = _qbb(x0_i, cx_i, x1_i);
                    const [y0, y1] = _qbb(y0_i, cy_i, y1_i);
                    index.add(x0, y0, x1, y1);
                }
            }
        }
        _render(ctx, indices, data) {
            if (this.visuals.line.doit) {
                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 (isNaN(sx0_i + sy0_i + sx1_i + sy1_i + scx_i + scy_i))
                        continue;
                    ctx.beginPath();
                    ctx.moveTo(sx0_i, sy0_i);
                    ctx.quadraticCurveTo(scx_i, scy_i, sx1_i, sy1_i);
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            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);
        }
        static init_Quadratic() {
            this.prototype.default_view = QuadraticView;
            this.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" }],
            }));
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.Quadratic = Quadratic;
    Quadratic.__name__ = "Quadratic";
    Quadratic.init_Quadratic();
},
/* models/glyphs/ray.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const utils_1 = require(106) /* ./utils */;
    const property_mixins_1 = require(48) /* ../../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 = 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) {
            const { sx, sy, slength, angle } = data !== null && data !== void 0 ? data : this;
            if (this.visuals.line.doit) {
                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 (isNaN(sx_i + sy_i + angle_i + slength_i))
                        continue;
                    ctx.translate(sx_i, sy_i);
                    ctx.rotate(angle_i);
                    ctx.beginPath();
                    ctx.moveTo(0, 0);
                    ctx.lineTo(slength_i, 0);
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                    ctx.rotate(-angle_i);
                    ctx.translate(-sx_i, -sy_i);
                }
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            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);
        }
        static init_Ray() {
            this.prototype.default_view = RayView;
            this.mixins(property_mixins_1.LineVector);
            this.define(({}) => ({
                length: [p.DistanceSpec, 0],
                angle: [p.AngleSpec, 0],
            }));
        }
    }
    exports.Ray = Ray;
    Ray.__name__ = "Ray";
    Ray.init_Ray();
},
/* models/glyphs/rect.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const center_rotatable_1 = require(288) /* ./center_rotatable */;
    const utils_1 = require(106) /* ./utils */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(12) /* ../../core/util/arrayable */;
    const selection_1 = require(59) /* ../selections/selection */;
    class RectView extends center_rotatable_1.CenterRotatableView {
        _map_data() {
            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 = types_1.to_screen(this.width);
                const n = this.sx.length;
                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 = types_1.to_screen(this.height);
                const n = this.sy.length;
                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 n = this.sw.length;
            this.ssemi_diag = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++)
                this.ssemi_diag[i] = Math.sqrt((this.sw[i] / 2 * this.sw[i]) / 2 + (this.sh[i] / 2 * this.sh[i]) / 2);
        }
        _render(ctx, indices, data) {
            const { sx, sy, sx0, sy1, 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 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 (isNaN(sx_i + sy_i + sx0_i + sy1_i + sw_i + sh_i + angle_i))
                    continue;
                if (sw_i == 0 || sh_i == 0)
                    continue;
                ctx.beginPath();
                if (angle_i) {
                    ctx.translate(sx_i, sy_i);
                    ctx.rotate(angle_i);
                    ctx.rect(-sw_i / 2, -sh_i / 2, sw_i, sh_i);
                    ctx.rotate(-angle_i);
                    ctx.translate(-sx_i, -sy_i);
                }
                else
                    ctx.rect(sx0_i, sy1_i, sw_i, sh_i);
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        _hit_rect(geometry) {
            return this._hit_rect_against_index(geometry);
        }
        _hit_point(geometry) {
            let { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const n = this.sx0.length;
            const scenter_x = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++) {
                scenter_x[i] = this.sx0[i] + this.sw[i] / 2;
            }
            const scenter_y = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++) {
                scenter_y[i] = this.sy1[i] + this.sh[i] / 2;
            }
            const max_x2_ddist = arrayable_1.max(this._ddist(0, scenter_x, this.ssemi_diag));
            const max_y2_ddist = arrayable_1.max(this._ddist(1, scenter_y, this.ssemi_diag));
            const x0 = x - max_x2_ddist;
            const x1 = x + max_x2_ddist;
            const y0 = y - max_y2_ddist;
            const y1 = y + max_y2_ddist;
            let width_in;
            let height_in;
            const indices = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const angle_i = this.angle.get(i);
                if (angle_i) {
                    const s = Math.sin(-angle_i);
                    const c = Math.cos(-angle_i);
                    const px = c * (sx - this.sx[i]) - s * (sy - this.sy[i]) + this.sx[i];
                    const py = s * (sx - this.sx[i]) + c * (sy - this.sy[i]) + this.sy[i];
                    sx = px;
                    sy = py;
                    width_in = Math.abs(this.sx[i] - sx) <= this.sw[i] / 2;
                    height_in = Math.abs(this.sy[i] - sy) <= this.sh[i] / 2;
                }
                else {
                    const dx = sx - this.sx0[i];
                    const dy = sy - this.sy1[i];
                    width_in = 0 <= dx && dx <= this.sw[i];
                    height_in = 0 <= dy && dy <= this.sh[i];
                }
                if (width_in && height_in) {
                    indices.push(i);
                }
            }
            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 = 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] = Math.abs(pt1[i] - pt0[i]);
            return ddist;
        }
        draw_legend_for_index(ctx, bbox, index) {
            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);
        }
        static init_Rect() {
            this.prototype.default_view = RectView;
            this.define(({ Boolean }) => ({
                dilate: [Boolean, false],
            }));
        }
    }
    exports.Rect = Rect;
    Rect.__name__ = "Rect";
    Rect.init_Rect();
},
/* models/glyphs/scatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const marker_1 = require(304) /* ./marker */;
    const defs_1 = require(305) /* ./defs */;
    const markers_1 = require(283) /* ./webgl/markers */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class ScatterView extends marker_1.MarkerView {
        _init_webgl() {
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null) {
                const marker_types = new Set(this.marker);
                if (marker_types.size == 1) {
                    const [marker_type] = [...marker_types];
                    if (markers_1.MarkerGL.is_supported(marker_type)) {
                        const { glglyph } = this;
                        if (glglyph == null || glglyph.marker_type != marker_type) {
                            this.glglyph = new markers_1.MarkerGL(webgl.gl, this, marker_type);
                            return;
                        }
                    }
                }
            }
            delete this.glglyph;
        }
        _set_data(indices) {
            super._set_data(indices);
            this._init_webgl();
        }
        _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 (isNaN(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)
                    ctx.rotate(angle_i);
                defs_1.marker_funcs[marker_i](ctx, i, r, this.visuals);
                if (angle_i)
                    ctx.rotate(-angle_i);
                ctx.translate(-sx_i, -sy_i);
            }
        }
        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);
        }
        static init_Scatter() {
            this.prototype.default_view = ScatterView;
            this.define(() => ({
                marker: [p.MarkerSpec, { value: "circle" }],
            }));
        }
    }
    exports.Scatter = Scatter;
    Scatter.__name__ = "Scatter";
    Scatter.init_Scatter();
},
/* models/glyphs/marker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const array_1 = require(9) /* ../../core/util/array */;
    const selection_1 = require(59) /* ../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 (isNaN(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)
                    ctx.rotate(angle_i);
                this._render_one(ctx, i, r, this.visuals);
                if (angle_i)
                    ctx.rotate(-angle_i);
                ctx.translate(-sx_i, -sy_i);
            }
        }
        _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 ms = this.max_size / 2;
            let x0, x1, y0, y1;
            if (geometry.direction == 'h') {
                y0 = bounds.y0;
                y1 = bounds.y1;
                const sx0 = sx - ms;
                const sx1 = sx + ms;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            }
            else {
                x0 = bounds.x0;
                x1 = bounds.x1;
                const sy0 = sy - ms;
                const sy1 = sy + ms;
                [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_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, sy } = geometry;
            // TODO (bev) use spatial index to pare candidate list
            const candidates = array_1.range(0, this.sx.length);
            const indices = [];
            for (let i = 0, end = candidates.length; i < end; i++) {
                const index = candidates[i];
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _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);
        }
        static init_Marker() {
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.define(({ Number }) => ({
                size: [p.ScreenDistanceSpec, { value: 4 }],
                angle: [p.AngleSpec, 0],
                hit_dilation: [Number, 1.0],
            }));
        }
    }
    exports.Marker = Marker;
    Marker.__name__ = "Marker";
    Marker.init_Marker();
},
/* 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);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function circle(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function circle_cross(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            _one_cross(ctx, r);
            ctx.stroke();
        }
    }
    function circle_dot(ctx, i, r, visuals) {
        circle(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function circle_y(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            _one_y(ctx, r);
            ctx.stroke();
        }
    }
    function circle_x(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            _one_x(ctx, r);
            ctx.stroke();
        }
    }
    function cross(ctx, i, r, visuals) {
        _one_cross(ctx, r);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function diamond(ctx, i, r, visuals) {
        _one_diamond(ctx, r);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function diamond_cross(ctx, i, r, visuals) {
        _one_diamond(ctx, r);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.moveTo(0, r);
            ctx.lineTo(0, -r);
            ctx.moveTo(-r / 1.5, 0);
            ctx.lineTo(r / 1.5, 0);
            ctx.stroke();
        }
    }
    function diamond_dot(ctx, i, r, visuals) {
        diamond(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function dot(ctx, i, r, visuals) {
        _one_dot(ctx, r);
        visuals.line.set_vectorize(ctx, i);
        ctx.fillStyle = ctx.strokeStyle; // NOTE: dots use line color for fill to match
        ctx.fill();
    }
    function hex(ctx, i, r, visuals) {
        _one_hex(ctx, r);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    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);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    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();
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function square(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    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();
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function square_cross(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            _one_cross(ctx, r);
            ctx.stroke();
        }
    }
    function square_dot(ctx, i, r, visuals) {
        square(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function square_x(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.moveTo(-r, r);
            ctx.lineTo(r, -r);
            ctx.moveTo(-r, -r);
            ctx.lineTo(r, r);
            ctx.stroke();
        }
    }
    function star(ctx, i, r, visuals) {
        _one_star(ctx, r);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    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);
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    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();
        if (visuals.fill.doit) {
            visuals.fill.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.hatch.doit) {
            visuals.hatch.set_vectorize(ctx, i);
            ctx.fill();
        }
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function dash(ctx, i, r, visuals) {
        _one_line(ctx, r);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function x(ctx, i, r, visuals) {
        _one_x(ctx, r);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    function y(ctx, i, r, visuals) {
        _one_y(ctx, r);
        if (visuals.line.doit) {
            visuals.line.set_vectorize(ctx, i);
            ctx.stroke();
        }
    }
    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) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    const glyph_1 = require(98) /* ./glyph */;
    const utils_1 = require(106) /* ./utils */;
    const selection_1 = require(59) /* ../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];
                if (isNaN(x0 + x1 + y0 + y1))
                    index.add_empty();
                else
                    index.add(min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1));
            }
        }
        _render(ctx, indices, data) {
            if (this.visuals.line.doit) {
                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 (isNaN(sx0_i + sy0_i + sx1_i + sy1_i))
                        continue;
                    ctx.beginPath();
                    ctx.moveTo(sx0_i, sy0_i);
                    ctx.lineTo(sx1_i, sy1_i);
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        _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) {
            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);
        }
        static init_Segment() {
            this.prototype.default_view = SegmentView;
            this.define(({}) => ({
                x0: [p.XCoordinateSpec, { field: "x0" }],
                y0: [p.YCoordinateSpec, { field: "y0" }],
                x1: [p.XCoordinateSpec, { field: "x1" }],
                y1: [p.YCoordinateSpec, { field: "y1" }],
            }));
            this.mixins(property_mixins_1.LineVector);
        }
    }
    exports.Segment = Segment;
    Segment.__name__ = "Segment";
    Segment.init_Segment();
},
/* models/glyphs/spline.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const interpolation_1 = require(308) /* ../../core/util/interpolation */;
    class SplineView extends xy_glyph_1.XYGlyphView {
        _set_data() {
            const { tension, closed } = this.model;
            [this._xt, this._yt] = 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;
            this.visuals.line.set_value(ctx);
            const n = sx.length;
            for (let j = 0; j < n; j++) {
                if (j == 0) {
                    ctx.beginPath();
                    ctx.moveTo(sx[j], sy[j]);
                    continue;
                }
                else if (isNaN(sx[j]) || isNaN(sy[j])) {
                    ctx.stroke();
                    ctx.beginPath();
                    continue;
                }
                else
                    ctx.lineTo(sx[j], sy[j]);
            }
            ctx.stroke();
        }
    }
    exports.SplineView = SplineView;
    SplineView.__name__ = "SplineView";
    class Spline extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static init_Spline() {
            this.prototype.default_view = SplineView;
            this.mixins(mixins.LineScalar);
            this.define(({ Boolean, Number }) => ({
                tension: [Number, 0.5],
                closed: [Boolean, false],
            }));
        }
    }
    exports.Spline = Spline;
    Spline.__name__ = "Spline";
    Spline.init_Spline();
},
/* core/util/interpolation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(24) /* ../types */;
    const assert_1 = require(11) /* ./assert */;
    function catmullrom_spline(x, y, T = 10, tension = 0.5, closed = false) {
        /** Centripetal Catmull-Rom spline. */
        assert_1.assert(x.length == y.length);
        const n = x.length;
        const N = closed ? n + 1 : n;
        const ArrayType = 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) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const utils_1 = require(106) /* ./utils */;
    const mixins = tslib_1.__importStar(require(48) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    class StepView extends xy_glyph_1.XYGlyphView {
        _render(ctx, indices, data) {
            const { sx, sy } = data !== null && data !== void 0 ? data : this;
            let drawing = false;
            let last_index = null;
            this.visuals.line.set_value(ctx);
            const L = indices.length;
            if (L < 2)
                return;
            ctx.beginPath();
            ctx.moveTo(sx[0], sy[0]);
            for (const i of indices) {
                let x1, x2;
                let y1, y2;
                switch (this.model.mode) {
                    case "before": {
                        [x1, y1] = [sx[i - 1], sy[i]];
                        [x2, y2] = [sx[i], sy[i]];
                        break;
                    }
                    case "after": {
                        [x1, y1] = [sx[i], sy[i - 1]];
                        [x2, y2] = [sx[i], sy[i]];
                        break;
                    }
                    case "center": {
                        const xm = (sx[i - 1] + sx[i]) / 2;
                        [x1, y1] = [xm, sy[i - 1]];
                        [x2, y2] = [xm, sy[i]];
                        break;
                    }
                    default:
                        throw new Error("unexpected");
                }
                if (drawing) {
                    if (!isFinite(sx[i] + sy[i])) {
                        ctx.stroke();
                        ctx.beginPath();
                        drawing = false;
                        last_index = i;
                        continue;
                    }
                    if (last_index != null && i - last_index > 1) {
                        ctx.stroke();
                        drawing = false;
                    }
                }
                if (drawing) {
                    ctx.lineTo(x1, y1);
                    ctx.lineTo(x2, y2);
                }
                else {
                    ctx.beginPath();
                    ctx.moveTo(sx[i], sy[i]);
                    drawing = true;
                }
                last_index = i;
            }
            ctx.lineTo(sx[L - 1], sy[L - 1]);
            ctx.stroke();
        }
        draw_legend_for_index(ctx, bbox, _index) {
            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);
        }
        static init_Step() {
            this.prototype.default_view = StepView;
            this.mixins(mixins.LineScalar);
            this.define(() => ({
                mode: [enums_1.StepMode, "before"],
            }));
        }
    }
    exports.Step = Step;
    Step.__name__ = "Step";
    Step.init_Step();
},
/* models/glyphs/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const property_mixins_1 = require(48) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(107) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const text_1 = require(143) /* ../../core/util/text */;
    const assert_1 = require(11) /* ../../core/util/assert */;
    const selection_1 = require(59) /* ../selections/selection */;
    class TextView extends xy_glyph_1.XYGlyphView {
        _rotate_point(x, y, xoff, yoff, angle) {
            const sxr = (x - xoff) * Math.cos(angle) - (y - yoff) * Math.sin(angle) + xoff;
            const syr = (x - xoff) * Math.sin(angle) + (y - yoff) * Math.cos(angle) + yoff;
            return [sxr, syr];
        }
        _text_bounds(x0, y0, width, height) {
            const xvals = [x0, x0 + width, x0 + width, x0, x0];
            const yvals = [y0, y0, y0 - height, y0 - height, y0];
            return [xvals, yvals];
        }
        _render(ctx, indices, data) {
            const { sx, sy, x_offset, y_offset, angle, text } = data !== null && data !== void 0 ? data : this;
            this._sys = [];
            this._sxs = [];
            for (const i of indices) {
                const sxs_i = this._sxs[i] = [];
                const sys_i = this._sys[i] = [];
                const sx_i = sx[i];
                const sy_i = sy[i];
                const x_offset_i = x_offset.get(i);
                const y_offset_i = y_offset.get(i);
                const angle_i = angle.get(i);
                const text_i = text.get(i);
                if (isNaN(sx_i + sy_i + x_offset_i + y_offset_i + angle_i) || text_i == null)
                    continue;
                if (this.visuals.text.doit) {
                    const text = `${text_i}`;
                    ctx.save();
                    ctx.translate(sx_i + x_offset_i, sy_i + y_offset_i);
                    ctx.rotate(angle_i);
                    this.visuals.text.set_vectorize(ctx, i);
                    const font = this.visuals.text.font_value(i);
                    const { height } = text_1.font_metrics(font);
                    const line_height = this.text_line_height.get(i) * height;
                    if (text.indexOf("\n") == -1) {
                        ctx.fillText(text, 0, 0);
                        const x0 = sx_i + x_offset_i;
                        const y0 = sy_i + y_offset_i;
                        const width = ctx.measureText(text).width;
                        const [xvalues, yvalues] = this._text_bounds(x0, y0, width, line_height);
                        sxs_i.push(xvalues);
                        sys_i.push(yvalues);
                    }
                    else {
                        const lines = text.split("\n");
                        const block_height = line_height * lines.length;
                        const baseline = this.text_baseline.get(i);
                        let y;
                        switch (baseline) {
                            case "top": {
                                y = 0;
                                break;
                            }
                            case "middle": {
                                y = (-block_height / 2) + (line_height / 2);
                                break;
                            }
                            case "bottom": {
                                y = -block_height + line_height;
                                break;
                            }
                            default: {
                                y = 0;
                                console.warn(`'${baseline}' baseline not supported with multi line text`);
                            }
                        }
                        for (const line of lines) {
                            ctx.fillText(line, 0, y);
                            const x0 = sx_i + x_offset_i;
                            const y0 = y + sy_i + y_offset_i;
                            const width = ctx.measureText(line).width;
                            const [xvalues, yvalues] = this._text_bounds(x0, y0, width, line_height);
                            sxs_i.push(xvalues);
                            sys_i.push(yvalues);
                            y += line_height;
                        }
                    }
                    ctx.restore();
                }
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const indices = [];
            for (let i = 0; i < this._sxs.length; i++) {
                const sxs = this._sxs[i];
                const sys = this._sys[i];
                const n = sxs.length;
                for (let j = 0, endj = n; j < endj; j++) {
                    const [sxr, syr] = this._rotate_point(sx, sy, sxs[n - 1][0], sys[n - 1][0], -this.angle.get(i));
                    if (hittest.point_in_poly(sxr, syr, sxs[j], sys[j])) {
                        indices.push(i);
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        scenterxy(i) {
            const sxs = this._sxs[i];
            const sys = this._sys[i];
            assert_1.assert(sxs.length != 0 && sys.length != 0);
            const sx0 = sxs[0][0];
            const sy0 = sys[0][0];
            const sxc = (sxs[0][2] + sx0) / 2;
            const syc = (sys[0][2] + sy0) / 2;
            const [sxcr, sycr] = this._rotate_point(sxc, syc, sx0, sy0, this.angle.get(i));
            return [sxcr, sycr];
        }
    }
    exports.TextView = TextView;
    TextView.__name__ = "TextView";
    class Text extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
        static init_Text() {
            this.prototype.default_view = TextView;
            this.mixins(property_mixins_1.TextVector);
            this.define(({}) => ({
                text: [p.NullStringSpec, { field: "text" }],
                angle: [p.AngleSpec, 0],
                x_offset: [p.NumberSpec, 0],
                y_offset: [p.NumberSpec, 0],
            }));
        }
    }
    exports.Text = Text;
    Text.__name__ = "Text";
    Text.init_Text();
},
/* models/glyphs/vbar.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const box_1 = require(290) /* ./box */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class VBarView extends box_1.BoxView {
        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 box_1.Box {
        constructor(attrs) {
            super(attrs);
        }
        static init_VBar() {
            this.prototype.default_view = VBarView;
            this.define(({}) => ({
                x: [p.XCoordinateSpec, { field: "x" }],
                bottom: [p.YCoordinateSpec, { value: 0 }],
                width: [p.NumberSpec, { value: 1 }],
                top: [p.YCoordinateSpec, { field: "top" }],
            }));
        }
    }
    exports.VBar = VBar;
    VBar.__name__ = "VBar";
    VBar.init_VBar();
},
/* models/glyphs/wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(64) /* ./xy_glyph */;
    const utils_1 = require(106) /* ./utils */;
    const property_mixins_1 = require(48) /* ../../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(10) /* ../../core/util/math */;
    const selection_1 = require(59) /* ../selections/selection */;
    class WedgeView 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 = types_1.to_screen(this.radius);
        }
        _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 (isNaN(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();
                if (this.visuals.fill.doit) {
                    this.visuals.fill.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.hatch.doit) {
                    this.visuals.hatch.set_vectorize(ctx, i);
                    ctx.fill();
                }
                if (this.visuals.line.doit) {
                    this.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
            }
        }
        _hit_point(geometry) {
            let dist, sx0, sx1, sy0, sy1, x0, x1, y0, y1;
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            // check diameter first
            const max_diameter = 2 * this.max_radius;
            if (this.model.properties.radius.units === "data") {
                x0 = x - max_diameter;
                x1 = x + max_diameter;
                y0 = y - max_diameter;
                y1 = y + max_diameter;
            }
            else {
                sx0 = sx - max_diameter;
                sx1 = sx + max_diameter;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                sy0 = sy - max_diameter;
                sy1 = sy + max_diameter;
                [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]);
                if (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) {
            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);
        }
        static init_Wedge() {
            this.prototype.default_view = WedgeView;
            this.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
            this.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" }],
            }));
        }
    }
    exports.Wedge = Wedge;
    Wedge.__name__ = "Wedge";
    Wedge.init_Wedge();
},
/* models/graphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(126) /* ./graph_hit_test_policy */, exports);
    tslib_1.__exportStar(require(125) /* ./layout_provider */, exports);
    tslib_1.__exportStar(require(314) /* ./static_layout_provider */, exports);
},
/* models/graphs/static_layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_provider_1 = require(125) /* ./layout_provider */;
    class StaticLayoutProvider extends layout_provider_1.LayoutProvider {
        constructor(attrs) {
            super(attrs);
        }
        static init_StaticLayoutProvider() {
            this.define(({ Number, Tuple, Dict }) => ({
                graph_layout: [Dict(Tuple(Number, Number)), {}],
            }));
        }
        get_node_coordinates(node_source) {
            var _a;
            const index = (_a = node_source.data.index) !== null && _a !== void 0 ? _a : [];
            const n = index.length;
            const xs = new Float64Array(n);
            const ys = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                const point = this.graph_layout[index[i]];
                const [x, y] = point !== null && point !== void 0 ? point : [NaN, NaN];
                xs[i] = x;
                ys[i] = y;
            }
            return [xs, ys];
        }
        get_edge_coordinates(edge_source) {
            var _a, _b;
            const starts = (_a = edge_source.data.start) !== null && _a !== void 0 ? _a : [];
            const ends = (_b = edge_source.data.end) !== null && _b !== void 0 ? _b : [];
            const n = Math.min(starts.length, ends.length);
            const xs = [];
            const ys = [];
            const has_paths = edge_source.data.xs != null && edge_source.data.ys != null;
            for (let i = 0; i < n; i++) {
                const in_layout = this.graph_layout[starts[i]] != null && this.graph_layout[ends[i]] != null;
                if (has_paths && in_layout) {
                    xs.push(edge_source.data.xs[i]);
                    ys.push(edge_source.data.ys[i]);
                }
                else {
                    let start, end;
                    if (in_layout) {
                        start = this.graph_layout[starts[i]];
                        end = this.graph_layout[ends[i]];
                    }
                    else {
                        start = [NaN, NaN];
                        end = [NaN, NaN];
                    }
                    xs.push([start[0], end[0]]);
                    ys.push([start[1], end[1]]);
                }
            }
            return [xs, ys];
        }
    }
    exports.StaticLayoutProvider = StaticLayoutProvider;
    StaticLayoutProvider.__name__ = "StaticLayoutProvider";
    StaticLayoutProvider.init_StaticLayoutProvider();
},
/* models/grids/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var grid_1 = require(316) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
},
/* models/grids/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const axes_1 = require(162) /* ../axes */;
    const guide_renderer_1 = require(164) /* ../renderers/guide_renderer */;
    const ticker_1 = require(165) /* ../tickers/ticker */;
    const mixins = tslib_1.__importStar(require(48) /* ../../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]);
                if (this.visuals.band_fill.doit) {
                    this.visuals.band_fill.set_value(ctx);
                    ctx.fill();
                }
                if (this.visuals.band_hatch.doit) {
                    this.visuals.band_hatch.set_value(ctx);
                    ctx.fill();
                }
            }
        }
        _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 = (i + 1) % 2;
            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 (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 = (i + 1) % 2;
            const [range, cross_range] = this.ranges();
            let [start, end] = this.computed_bounds();
            [start, end] = [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 = cross_range.min;
            const cmax = cross_range.max;
            if (!exclude_ends) {
                if (ticks[0] != min)
                    ticks.splice(0, 0, min);
                if (ticks[ticks.length - 1] != max)
                    ticks.push(max);
            }
            for (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);
        }
        static init_Grid() {
            this.prototype.default_view = GridView;
            this.mixins([
                ["grid_", mixins.Line],
                ["minor_grid_", mixins.Line],
                ["band_", mixins.Fill],
                ["band_", mixins.Hatch],
            ]);
            this.define(({ Number, Auto, Enum, Ref, Tuple, Or, Nullable }) => ({
                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],
            }));
            this.override({
                level: "underlay",
                band_fill_color: null,
                band_fill_alpha: 0,
                grid_line_color: '#e5e5e5',
                minor_grid_line_color: null,
            });
        }
        get_ticker() {
            if (this.ticker != null) {
                return this.ticker;
            }
            if (this.axis != null) {
                return this.axis.ticker;
            }
            return null;
        }
    }
    exports.Grid = Grid;
    Grid.__name__ = "Grid";
    Grid.init_Grid();
},
/* models/layouts/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var box_1 = require(318) /* ./box */;
    __esExport("Box", box_1.Box);
    var column_1 = require(320) /* ./column */;
    __esExport("Column", column_1.Column);
    var grid_box_1 = require(321) /* ./grid_box */;
    __esExport("GridBox", grid_box_1.GridBox);
    var html_box_1 = require(322) /* ./html_box */;
    __esExport("HTMLBox", html_box_1.HTMLBox);
    var layout_dom_1 = require(319) /* ./layout_dom */;
    __esExport("LayoutDOM", layout_dom_1.LayoutDOM);
    var panel_1 = require(323) /* ./panel */;
    __esExport("Panel", panel_1.Panel);
    var row_1 = require(324) /* ./row */;
    __esExport("Row", row_1.Row);
    var spacer_1 = require(325) /* ./spacer */;
    __esExport("Spacer", spacer_1.Spacer);
    var tabs_1 = require(326) /* ./tabs */;
    __esExport("Tabs", tabs_1.Tabs);
    var widget_box_1 = require(329) /* ./widget_box */;
    __esExport("WidgetBox", widget_box_1.WidgetBox);
},
/* models/layouts/box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(319) /* ./layout_dom */;
    class BoxView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.children.change, () => this.rebuild());
        }
        get child_models() {
            return this.model.children;
        }
    }
    exports.BoxView = BoxView;
    BoxView.__name__ = "BoxView";
    class Box extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static init_Box() {
            this.define(({ Number, Array, Ref }) => ({
                children: [Array(Ref(layout_dom_1.LayoutDOM)), []],
                spacing: [Number, 0],
            }));
        }
    }
    exports.Box = Box;
    Box.__name__ = "Box";
    Box.init_Box();
},
/* models/layouts/layout_dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const enums_1 = require(20) /* ../../core/enums */;
    const dom_1 = require(43) /* ../../core/dom */;
    const logging_1 = require(19) /* ../../core/logging */;
    const types_1 = require(8) /* ../../core/util/types */;
    const color_1 = require(22) /* ../../core/util/color */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const dom_view_1 = require(240) /* ../../core/dom_view */;
    const layout_1 = require(221) /* ../../core/layout */;
    const root_css_1 = require(44) /* ../../styles/root.css */;
    const canvas_1 = require(249) /* ../../core/util/canvas */;
    class LayoutDOMView extends dom_view_1.DOMView {
        constructor() {
            super(...arguments);
            this._idle_notified = false;
            this._offset_parent = null;
            this._viewport = {};
        }
        initialize() {
            super.initialize();
            this.el.style.position = this.is_root ? "relative" : "absolute";
            this._child_views = new Map();
        }
        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();
            if (this.is_root) {
                this._on_resize = () => this.resize_layout();
                window.addEventListener("resize", this._on_resize);
                this._parent_observer = setInterval(() => {
                    const offset_parent = this.el.offsetParent;
                    if (this._offset_parent != offset_parent) {
                        this._offset_parent = offset_parent;
                        if (offset_parent != null) {
                            this.compute_viewport();
                            this.invalidate_layout();
                        }
                    }
                }, 250);
            }
            const p = this.model.properties;
            this.on_change([
                p.width, p.height,
                p.min_width, p.min_height,
                p.max_width, p.max_height,
                p.margin,
                p.width_policy, p.height_policy, p.sizing_mode,
                p.aspect_ratio,
                p.visible,
            ], () => this.invalidate_layout());
            this.on_change([
                p.background,
                p.css_classes,
            ], () => this.invalidate_render());
        }
        disconnect_signals() {
            if (this._parent_observer != null)
                clearTimeout(this._parent_observer);
            if (this._on_resize != null)
                window.removeEventListener("resize", this._on_resize);
            super.disconnect_signals();
        }
        css_classes() {
            return super.css_classes().concat(this.model.css_classes);
        }
        get child_views() {
            return this.child_models.map((child) => this._child_views.get(child));
        }
        async build_child_views() {
            await build_views_1.build_views(this._child_views, this.child_models, { parent: this });
        }
        render() {
            super.render();
            dom_1.empty(this.el); // XXX: this should be in super
            const { background } = this.model;
            this.el.style.backgroundColor = background != null ? color_1.color2css(background) : "";
            dom_1.classes(this.el).clear().add(...this.css_classes());
            for (const child_view of this.child_views) {
                this.el.appendChild(child_view.el);
                child_view.render();
            }
        }
        update_layout() {
            for (const child_view of this.child_views)
                child_view.update_layout();
            this._update_layout();
        }
        update_position() {
            this.el.style.display = this.model.visible ? "block" : "none";
            const margin = this.is_root ? this.layout.sizing.margin : undefined;
            dom_1.position(this.el, this.layout.bbox, margin);
            for (const child_view of this.child_views)
                child_view.update_position();
        }
        after_layout() {
            for (const child_view of this.child_views)
                child_view.after_layout();
            this._has_finished = true;
        }
        compute_viewport() {
            this._viewport = this._viewport_size();
        }
        renderTo(element) {
            element.appendChild(this.el);
            this._offset_parent = this.el.offsetParent;
            this.compute_viewport();
            this.build();
        }
        build() {
            this.assert_root();
            this.render();
            this.update_layout();
            this.compute_layout();
            return this;
        }
        async rebuild() {
            await this.build_child_views();
            this.invalidate_render();
        }
        compute_layout() {
            const start = Date.now();
            this.layout.compute(this._viewport);
            this.update_position();
            this.after_layout();
            logging_1.logger.debug(`layout computed in ${Date.now() - start} ms`);
            this.notify_finished();
        }
        resize_layout() {
            this.root.compute_viewport();
            this.root.compute_layout();
        }
        invalidate_layout() {
            this.root.update_layout();
            this.root.compute_layout();
        }
        invalidate_render() {
            this.render();
            this.invalidate_layout();
        }
        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;
        }
        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);
                    }
                }
            }
        }
        _width_policy() {
            return this.model.width != null ? "fixed" : "fit";
        }
        _height_policy() {
            return this.model.height != null ? "fixed" : "fit";
        }
        box_sizing() {
            let { width_policy, height_policy, aspect_ratio } = this.model;
            if (width_policy == "auto")
                width_policy = this._width_policy();
            if (height_policy == "auto")
                height_policy = this._height_policy();
            const { sizing_mode } = this.model;
            if (sizing_mode != null) {
                if (sizing_mode == "fixed")
                    width_policy = height_policy = "fixed";
                else if (sizing_mode == "stretch_both")
                    width_policy = height_policy = "max";
                else if (sizing_mode == "stretch_width")
                    width_policy = "max";
                else if (sizing_mode == "stretch_height")
                    height_policy = "max";
                else {
                    if (aspect_ratio == null)
                        aspect_ratio = "auto";
                    switch (sizing_mode) {
                        case "scale_width":
                            width_policy = "max";
                            height_policy = "min";
                            break;
                        case "scale_height":
                            width_policy = "min";
                            height_policy = "max";
                            break;
                        case "scale_both":
                            width_policy = "max";
                            height_policy = "max";
                            break;
                    }
                }
            }
            const sizing = { width_policy, height_policy };
            const { min_width, min_height } = this.model;
            if (min_width != null)
                sizing.min_width = min_width;
            if (min_height != null)
                sizing.min_height = min_height;
            const { width, height } = this.model;
            if (width != null)
                sizing.width = width;
            if (height != null)
                sizing.height = height;
            const { max_width, max_height } = this.model;
            if (max_width != null)
                sizing.max_width = max_width;
            if (max_height != null)
                sizing.max_height = max_height;
            if (aspect_ratio == "auto" && width != null && height != null)
                sizing.aspect = width / height;
            else if (types_1.isNumber(aspect_ratio))
                sizing.aspect = aspect_ratio;
            const { margin } = this.model;
            if (margin != null) {
                if (types_1.isNumber(margin))
                    sizing.margin = { top: margin, right: margin, bottom: margin, left: margin };
                else if (margin.length == 2) {
                    const [vertical, horizontal] = margin;
                    sizing.margin = { top: vertical, right: horizontal, bottom: vertical, left: horizontal };
                }
                else {
                    const [top, right, bottom, left] = margin;
                    sizing.margin = { top, right, bottom, left };
                }
            }
            sizing.visible = this.model.visible;
            const { align } = this.model;
            if (types_1.isArray(align))
                [sizing.halign, sizing.valign] = align;
            else
                sizing.halign = sizing.valign = align;
            return sizing;
        }
        _viewport_size() {
            return dom_1.undisplayed(this.el, () => {
                let measuring = this.el;
                while (measuring = measuring.parentElement) {
                    // .bk-root element doesn't bring any value
                    if (measuring.classList.contains(root_css_1.root))
                        continue;
                    // we reached <body> element, so use viewport size
                    if (measuring == document.body) {
                        const { margin: { left, right, top, bottom } } = dom_1.extents(document.body);
                        const width = Math.ceil(document.documentElement.clientWidth - left - right);
                        const height = Math.ceil(document.documentElement.clientHeight - top - bottom);
                        return { width, height };
                    }
                    // stop on first element with sensible dimensions
                    const { padding: { left, right, top, bottom } } = dom_1.extents(measuring);
                    const { width, height } = measuring.getBoundingClientRect();
                    const inner_width = Math.ceil(width - left - right);
                    const inner_height = Math.ceil(height - top - bottom);
                    if (inner_width > 0 || inner_height > 0)
                        return {
                            width: inner_width > 0 ? inner_width : undefined,
                            height: inner_height > 0 ? inner_height : undefined,
                        };
                }
                // this element is detached from DOM
                return {};
            });
        }
        export(type, hidpi = true) {
            const output_backend = type == "png" ? "canvas" : "svg";
            const composite = new canvas_1.CanvasLayer(output_backend, hidpi);
            const { width, height } = this.layout.bbox;
            composite.resize(width, height);
            for (const view of this.child_views) {
                const region = view.export(type, hidpi);
                const { x, y } = view.layout.bbox;
                composite.ctx.drawImage(region.canvas, x, y);
            }
            return composite;
        }
        serializable_state() {
            return Object.assign(Object.assign({}, super.serializable_state()), { bbox: this.layout.bbox.box, children: this.child_views.map((child) => child.serializable_state()) });
        }
    }
    exports.LayoutDOMView = LayoutDOMView;
    LayoutDOMView.__name__ = "LayoutDOMView";
    class LayoutDOM extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_LayoutDOM() {
            this.define((types) => {
                const { Boolean, Number, String, Auto, Color, Array, Tuple, Or, Null, Nullable } = 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)), [0, 0, 0, 0]],
                    width_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                    height_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                    aspect_ratio: [Or(Number, Auto, Null), null],
                    sizing_mode: [Nullable(enums_1.SizingMode), null],
                    visible: [Boolean, true],
                    disabled: [Boolean, false],
                    align: [Or(enums_1.Align, Tuple(enums_1.Align, enums_1.Align)), "start"],
                    background: [Nullable(Color), null],
                    css_classes: [Array(String), []],
                };
            });
        }
    }
    exports.LayoutDOM = LayoutDOM;
    LayoutDOM.__name__ = "LayoutDOM";
    LayoutDOM.init_LayoutDOM();
},
/* models/layouts/column.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const box_1 = require(318) /* ./box */;
    const grid_1 = require(223) /* ../../core/layout/grid */;
    class ColumnView extends box_1.BoxView {
        _update_layout() {
            const items = this.child_views.map((child) => child.layout);
            this.layout = new grid_1.Column(items);
            this.layout.rows = this.model.rows;
            this.layout.spacing = [this.model.spacing, 0];
            this.layout.set_sizing(this.box_sizing());
        }
    }
    exports.ColumnView = ColumnView;
    ColumnView.__name__ = "ColumnView";
    class Column extends box_1.Box {
        constructor(attrs) {
            super(attrs);
        }
        static init_Column() {
            this.prototype.default_view = ColumnView;
            this.define(({ Any }) => ({
                rows: [Any /*TODO*/, "auto"],
            }));
        }
    }
    exports.Column = Column;
    Column.__name__ = "Column";
    Column.init_Column();
},
/* models/layouts/grid_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(319) /* ./layout_dom */;
    const grid_1 = require(223) /* ../../core/layout/grid */;
    class GridBoxView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            const { children, rows, cols, spacing } = this.model.properties;
            this.on_change([children, rows, cols, spacing], () => this.rebuild());
        }
        get child_models() {
            return this.model.children.map(([child]) => child);
        }
        _update_layout() {
            this.layout = new grid_1.Grid();
            this.layout.rows = this.model.rows;
            this.layout.cols = this.model.cols;
            this.layout.spacing = this.model.spacing;
            for (const [child, row, col, row_span, col_span] of this.model.children) {
                const child_view = this._child_views.get(child);
                this.layout.items.push({ layout: child_view.layout, row, col, row_span, col_span });
            }
            this.layout.set_sizing(this.box_sizing());
        }
    }
    exports.GridBoxView = GridBoxView;
    GridBoxView.__name__ = "GridBoxView";
    class GridBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static init_GridBox() {
            this.prototype.default_view = GridBoxView;
            this.define(({ Any, Int, Number, Tuple, Array, Ref, Or, Opt }) => ({
                children: [Array(Tuple(Ref(layout_dom_1.LayoutDOM), Int, Int, Opt(Int), Opt(Int))), []],
                rows: [Any /*TODO*/, "auto"],
                cols: [Any /*TODO*/, "auto"],
                spacing: [Or(Number, Tuple(Number, Number)), 0],
            }));
        }
    }
    exports.GridBox = GridBox;
    GridBox.__name__ = "GridBox";
    GridBox.init_GridBox();
},
/* models/layouts/html_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(319) /* ../layouts/layout_dom */;
    const layout_1 = require(221) /* ../../core/layout */;
    class HTMLBoxView extends layout_dom_1.LayoutDOMView {
        get child_models() {
            return [];
        }
        _update_layout() {
            this.layout = new layout_1.ContentBox(this.el);
            this.layout.set_sizing(this.box_sizing());
        }
    }
    exports.HTMLBoxView = HTMLBoxView;
    HTMLBoxView.__name__ = "HTMLBoxView";
    class HTMLBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTMLBox = HTMLBox;
    HTMLBox.__name__ = "HTMLBox";
},
/* models/layouts/panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const layout_dom_1 = require(319) /* ./layout_dom */;
    class Panel extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_Panel() {
            this.define(({ Boolean, String, Ref }) => ({
                title: [String, ""],
                child: [Ref(layout_dom_1.LayoutDOM)],
                closable: [Boolean, false],
            }));
        }
    }
    exports.Panel = Panel;
    Panel.__name__ = "Panel";
    Panel.init_Panel();
},
/* models/layouts/row.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const box_1 = require(318) /* ./box */;
    const grid_1 = require(223) /* ../../core/layout/grid */;
    class RowView extends box_1.BoxView {
        _update_layout() {
            const items = this.child_views.map((child) => child.layout);
            this.layout = new grid_1.Row(items);
            this.layout.cols = this.model.cols;
            this.layout.spacing = [0, this.model.spacing];
            this.layout.set_sizing(this.box_sizing());
        }
    }
    exports.RowView = RowView;
    RowView.__name__ = "RowView";
    class Row extends box_1.Box {
        constructor(attrs) {
            super(attrs);
        }
        static init_Row() {
            this.prototype.default_view = RowView;
            this.define(({ Any }) => ({
                cols: [Any /*TODO*/, "auto"],
            }));
        }
    }
    exports.Row = Row;
    Row.__name__ = "Row";
    Row.init_Row();
},
/* models/layouts/spacer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layout_dom_1 = require(319) /* ./layout_dom */;
    const layout_1 = require(221) /* ../../core/layout */;
    class SpacerView extends layout_dom_1.LayoutDOMView {
        get child_models() {
            return [];
        }
        _update_layout() {
            this.layout = new layout_1.LayoutItem();
            this.layout.set_sizing(this.box_sizing());
        }
    }
    exports.SpacerView = SpacerView;
    SpacerView.__name__ = "SpacerView";
    class Spacer extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static init_Spacer() {
            this.prototype.default_view = SpacerView;
        }
    }
    exports.Spacer = Spacer;
    Spacer.__name__ = "Spacer";
    Spacer.init_Spacer();
},
/* models/layouts/tabs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const layout_1 = require(221) /* ../../core/layout */;
    const dom_1 = require(43) /* ../../core/dom */;
    const array_1 = require(9) /* ../../core/util/array */;
    const enums_1 = require(20) /* ../../core/enums */;
    const layout_dom_1 = require(319) /* ./layout_dom */;
    const panel_1 = require(323) /* ./panel */;
    const tabs_css_1 = tslib_1.__importStar(require(327) /* ../../styles/tabs.css */), tabs = tabs_css_1;
    const buttons_css_1 = tslib_1.__importStar(require(328) /* ../../styles/buttons.css */), buttons = buttons_css_1;
    const menus_css_1 = tslib_1.__importStar(require(243) /* ../../styles/menus.css */), menus = menus_css_1;
    class TabsView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.tabs.change, () => this.rebuild());
            this.connect(this.model.properties.active.change, () => this.on_active_change());
        }
        styles() {
            return [...super.styles(), buttons_css_1.default, menus_css_1.default, tabs_css_1.default];
        }
        get child_models() {
            return this.model.tabs.map((tab) => tab.child);
        }
        _update_layout() {
            const loc = this.model.tabs_location;
            const vertical = loc == "above" || loc == "below";
            // XXX: this is a hack, this should be handled by "fit" policy in grid layout
            const { scroll_el, headers_el } = this;
            this.header = new class extends layout_1.ContentBox {
                _measure(viewport) {
                    const min_headers = 3;
                    const scroll = dom_1.size(scroll_el);
                    const headers = dom_1.children(headers_el).slice(0, min_headers).map((el) => dom_1.size(el));
                    const { width, height } = super._measure(viewport);
                    if (vertical) {
                        const min_width = scroll.width + array_1.sum(headers.map((size) => size.width));
                        return { width: viewport.width != Infinity ? viewport.width : min_width, height };
                    }
                    else {
                        const min_height = scroll.height + array_1.sum(headers.map((size) => size.height));
                        return { width, height: viewport.height != Infinity ? viewport.height : min_height };
                    }
                }
            }(this.header_el);
            if (vertical)
                this.header.set_sizing({ width_policy: "fit", height_policy: "fixed" });
            else
                this.header.set_sizing({ width_policy: "fixed", height_policy: "fit" });
            let row = 1;
            let col = 1;
            switch (loc) {
                case "above":
                    row -= 1;
                    break;
                case "below":
                    row += 1;
                    break;
                case "left":
                    col -= 1;
                    break;
                case "right":
                    col += 1;
                    break;
            }
            const header = { layout: this.header, row, col };
            const panels = this.child_views.map((child_view) => {
                return { layout: child_view.layout, row: 1, col: 1 };
            });
            this.layout = new layout_1.Grid([header, ...panels]);
            this.layout.set_sizing(this.box_sizing());
        }
        update_position() {
            super.update_position();
            this.header_el.style.position = "absolute"; // XXX: do it in position()
            dom_1.position(this.header_el, this.header.bbox);
            const loc = this.model.tabs_location;
            const vertical = loc == "above" || loc == "below";
            const scroll_el_size = dom_1.size(this.scroll_el);
            const headers_el_size = dom_1.scroll_size(this.headers_el);
            if (vertical) {
                const { width } = this.header.bbox;
                if (headers_el_size.width > width) {
                    this.wrapper_el.style.maxWidth = `${width - scroll_el_size.width}px`;
                    dom_1.display(this.scroll_el);
                }
                else {
                    this.wrapper_el.style.maxWidth = "";
                    dom_1.undisplay(this.scroll_el);
                }
            }
            else {
                const { height } = this.header.bbox;
                if (headers_el_size.height > height) {
                    this.wrapper_el.style.maxHeight = `${height - scroll_el_size.height}px`;
                    dom_1.display(this.scroll_el);
                }
                else {
                    this.wrapper_el.style.maxHeight = "";
                    dom_1.undisplay(this.scroll_el);
                }
            }
            const { child_views } = this;
            for (const child_view of child_views)
                dom_1.hide(child_view.el);
            const tab = child_views[this.model.active];
            if (tab != null)
                dom_1.show(tab.el);
        }
        render() {
            super.render();
            const { active } = this.model;
            const loc = this.model.tabs_location;
            const vertical = loc == "above" || loc == "below";
            const headers = this.model.tabs.map((tab, i) => {
                const el = dom_1.div({ class: [tabs.tab, i == active ? tabs.active : null] }, tab.title);
                el.addEventListener("click", (event) => {
                    if (event.target == event.currentTarget)
                        this.change_active(i);
                });
                if (tab.closable) {
                    const close_el = dom_1.div({ class: tabs.close });
                    close_el.addEventListener("click", (event) => {
                        if (event.target == event.currentTarget) {
                            this.model.tabs = 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);
                }
                return el;
            });
            this.headers_el = dom_1.div({ class: [tabs.headers] }, headers);
            this.wrapper_el = dom_1.div({ class: tabs.headers_wrapper }, this.headers_el);
            const left_el = dom_1.div({ class: [buttons.btn, buttons.btn_default], disabled: "" }, dom_1.div({ class: [menus.caret, tabs.left] }));
            const right_el = dom_1.div({ class: [buttons.btn, buttons.btn_default] }, dom_1.div({ class: [menus.caret, tabs.right] }));
            let scroll_index = 0;
            const do_scroll = (dir) => {
                return () => {
                    const ntabs = this.model.tabs.length;
                    if (dir == "left")
                        scroll_index = Math.max(scroll_index - 1, 0);
                    else
                        scroll_index = Math.min(scroll_index + 1, ntabs - 1);
                    if (scroll_index == 0)
                        left_el.setAttribute("disabled", "");
                    else
                        left_el.removeAttribute("disabled");
                    if (scroll_index == ntabs - 1)
                        right_el.setAttribute("disabled", "");
                    else
                        right_el.removeAttribute("disabled");
                    const sizes = dom_1.children(this.headers_el)
                        .slice(0, scroll_index)
                        .map((el) => el.getBoundingClientRect());
                    if (vertical) {
                        const left = -array_1.sum(sizes.map((size) => size.width));
                        this.headers_el.style.left = `${left}px`;
                    }
                    else {
                        const top = -array_1.sum(sizes.map((size) => size.height));
                        this.headers_el.style.top = `${top}px`;
                    }
                };
            };
            left_el.addEventListener("click", do_scroll("left"));
            right_el.addEventListener("click", do_scroll("right"));
            this.scroll_el = dom_1.div({ class: buttons.btn_group }, left_el, right_el);
            this.header_el = dom_1.div({ class: [tabs.tabs_header, tabs[loc]] }, this.scroll_el, this.wrapper_el);
            this.el.appendChild(this.header_el);
        }
        change_active(i) {
            if (i != this.model.active) {
                this.model.active = i;
            }
        }
        on_active_change() {
            const i = this.model.active;
            const headers = dom_1.children(this.headers_el);
            for (const el of headers)
                el.classList.remove(tabs.active);
            headers[i].classList.add(tabs.active);
            const { child_views } = this;
            for (const child_view of child_views)
                dom_1.hide(child_view.el);
            dom_1.show(child_views[i].el);
        }
    }
    exports.TabsView = TabsView;
    TabsView.__name__ = "TabsView";
    class Tabs extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static init_Tabs() {
            this.prototype.default_view = TabsView;
            this.define(({ Int, Array, Ref }) => ({
                tabs: [Array(Ref(panel_1.Panel)), []],
                tabs_location: [enums_1.Location, "above"],
                active: [Int, 0],
            }));
        }
    }
    exports.Tabs = Tabs;
    Tabs.__name__ = "Tabs";
    Tabs.init_Tabs();
},
/* styles/tabs.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tabs_header = "bk-tabs-header";
    exports.btn_group = "bk-btn-group";
    exports.btn = "bk-btn";
    exports.headers_wrapper = "bk-headers-wrapper";
    exports.above = "bk-above";
    exports.right = "bk-right";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.headers = "bk-headers";
    exports.tab = "bk-tab";
    exports.active = "bk-active";
    exports.close = "bk-close";
    exports.default = `.bk-root .bk-tabs-header{display:flex;display:-webkit-flex;flex-wrap:nowrap;-webkit-flex-wrap:nowrap;align-items:center;-webkit-align-items:center;overflow:hidden;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;}.bk-root .bk-tabs-header .bk-btn-group{height:auto;margin-right:5px;}.bk-root .bk-tabs-header .bk-btn-group > .bk-btn{flex-grow:0;-webkit-flex-grow:0;height:auto;padding:4px 4px;}.bk-root .bk-tabs-header .bk-headers-wrapper{flex-grow:1;-webkit-flex-grow:1;overflow:hidden;color:#666666;}.bk-root .bk-tabs-header.bk-above .bk-headers-wrapper{border-bottom:1px solid #e6e6e6;}.bk-root .bk-tabs-header.bk-right .bk-headers-wrapper{border-left:1px solid #e6e6e6;}.bk-root .bk-tabs-header.bk-below .bk-headers-wrapper{border-top:1px solid #e6e6e6;}.bk-root .bk-tabs-header.bk-left .bk-headers-wrapper{border-right:1px solid #e6e6e6;}.bk-root .bk-tabs-header.bk-above,.bk-root .bk-tabs-header.bk-below{flex-direction:row;-webkit-flex-direction:row;}.bk-root .bk-tabs-header.bk-above .bk-headers,.bk-root .bk-tabs-header.bk-below .bk-headers{flex-direction:row;-webkit-flex-direction:row;}.bk-root .bk-tabs-header.bk-left,.bk-root .bk-tabs-header.bk-right{flex-direction:column;-webkit-flex-direction:column;}.bk-root .bk-tabs-header.bk-left .bk-headers,.bk-root .bk-tabs-header.bk-right .bk-headers{flex-direction:column;-webkit-flex-direction:column;}.bk-root .bk-tabs-header .bk-headers{position:relative;display:flex;display:-webkit-flex;flex-wrap:nowrap;-webkit-flex-wrap:nowrap;align-items:center;-webkit-align-items:center;}.bk-root .bk-tabs-header .bk-tab{padding:4px 8px;border:solid transparent;white-space:nowrap;cursor:pointer;}.bk-root .bk-tabs-header .bk-tab:hover{background-color:#f2f2f2;}.bk-root .bk-tabs-header .bk-tab.bk-active{color:#4d4d4d;background-color:white;border-color:#e6e6e6;}.bk-root .bk-tabs-header .bk-tab .bk-close{margin-left:10px;}.bk-root .bk-tabs-header.bk-above .bk-tab{border-width:3px 1px 0px 1px;border-radius:4px 4px 0 0;}.bk-root .bk-tabs-header.bk-right .bk-tab{border-width:1px 3px 1px 0px;border-radius:0 4px 4px 0;}.bk-root .bk-tabs-header.bk-below .bk-tab{border-width:0px 1px 3px 1px;border-radius:0 0 4px 4px;}.bk-root .bk-tabs-header.bk-left .bk-tab{border-width:1px 0px 1px 3px;border-radius:4px 0 0 4px;}.bk-root .bk-close{display:inline-block;width:10px;height:10px;vertical-align:middle;background-image:url('data:image/svg+xml;utf8,\
      <svg viewPort="0 0 10 10" version="1.1" xmlns="http://www.w3.org/2000/svg">\
        <line x1="1" y1="9" x2="9" y2="1" stroke="gray" stroke-width="2"/>\
        <line x1="1" y1="1" x2="9" y2="9" stroke="gray" stroke-width="2"/>\
      </svg>');}.bk-root .bk-close:hover{background-image:url('data:image/svg+xml;utf8,\
      <svg viewPort="0 0 10 10" version="1.1" xmlns="http://www.w3.org/2000/svg">\
        <line x1="1" y1="9" x2="9" y2="1" stroke="red" stroke-width="2"/>\
        <line x1="1" y1="1" x2="9" y2="9" stroke="red" stroke-width="2"/>\
      </svg>');}`;
},
/* styles/buttons.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.btn = "bk-btn";
    exports.active = "bk-active";
    exports.btn_default = "bk-btn-default";
    exports.btn_primary = "bk-btn-primary";
    exports.btn_success = "bk-btn-success";
    exports.btn_warning = "bk-btn-warning";
    exports.btn_danger = "bk-btn-danger";
    exports.btn_light = "bk-btn-light";
    exports.btn_group = "bk-btn-group";
    exports.dropdown_toggle = "bk-dropdown-toggle";
    exports.default = `.bk-root .bk-btn{height:100%;display:inline-block;text-align:center;vertical-align:middle;white-space:nowrap;cursor:pointer;padding:6px 12px;font-size:12px;border:1px solid transparent;border-radius:4px;outline:0;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;}.bk-root .bk-btn:hover,.bk-root .bk-btn:focus{text-decoration:none;}.bk-root .bk-btn:active,.bk-root .bk-btn.bk-active{background-image:none;box-shadow:inset 0 3px 5px rgba(0, 0, 0, 0.125);}.bk-root .bk-btn[disabled]{cursor:not-allowed;pointer-events:none;opacity:0.65;box-shadow:none;}.bk-root .bk-btn-default{color:#333;background-color:#fff;border-color:#ccc;}.bk-root .bk-btn-default:hover{background-color:#f5f5f5;border-color:#b8b8b8;}.bk-root .bk-btn-default.bk-active{background-color:#ebebeb;border-color:#adadad;}.bk-root .bk-btn-default[disabled],.bk-root .bk-btn-default[disabled]:hover,.bk-root .bk-btn-default[disabled]:focus,.bk-root .bk-btn-default[disabled]:active,.bk-root .bk-btn-default[disabled].bk-active{background-color:#e6e6e6;border-color:#ccc;}.bk-root .bk-btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd;}.bk-root .bk-btn-primary:hover{background-color:#3681c1;border-color:#2c699e;}.bk-root .bk-btn-primary.bk-active{background-color:#3276b1;border-color:#285e8e;}.bk-root .bk-btn-primary[disabled],.bk-root .bk-btn-primary[disabled]:hover,.bk-root .bk-btn-primary[disabled]:focus,.bk-root .bk-btn-primary[disabled]:active,.bk-root .bk-btn-primary[disabled].bk-active{background-color:#506f89;border-color:#357ebd;}.bk-root .bk-btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c;}.bk-root .bk-btn-success:hover{background-color:#4eb24e;border-color:#409240;}.bk-root .bk-btn-success.bk-active{background-color:#47a447;border-color:#398439;}.bk-root .bk-btn-success[disabled],.bk-root .bk-btn-success[disabled]:hover,.bk-root .bk-btn-success[disabled]:focus,.bk-root .bk-btn-success[disabled]:active,.bk-root .bk-btn-success[disabled].bk-active{background-color:#667b66;border-color:#4cae4c;}.bk-root .bk-btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236;}.bk-root .bk-btn-warning:hover{background-color:#eea43b;border-color:#e89014;}.bk-root .bk-btn-warning.bk-active{background-color:#ed9c28;border-color:#d58512;}.bk-root .bk-btn-warning[disabled],.bk-root .bk-btn-warning[disabled]:hover,.bk-root .bk-btn-warning[disabled]:focus,.bk-root .bk-btn-warning[disabled]:active,.bk-root .bk-btn-warning[disabled].bk-active{background-color:#c89143;border-color:#eea236;}.bk-root .bk-btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a;}.bk-root .bk-btn-danger:hover{background-color:#d5433e;border-color:#bd2d29;}.bk-root .bk-btn-danger.bk-active{background-color:#d2322d;border-color:#ac2925;}.bk-root .bk-btn-danger[disabled],.bk-root .bk-btn-danger[disabled]:hover,.bk-root .bk-btn-danger[disabled]:focus,.bk-root .bk-btn-danger[disabled]:active,.bk-root .bk-btn-danger[disabled].bk-active{background-color:#a55350;border-color:#d43f3a;}.bk-root .bk-btn-light{color:#333;background-color:#fff;border-color:#ccc;border-color:transparent;}.bk-root .bk-btn-light:hover{background-color:#f5f5f5;border-color:#b8b8b8;}.bk-root .bk-btn-light.bk-active{background-color:#ebebeb;border-color:#adadad;}.bk-root .bk-btn-light[disabled],.bk-root .bk-btn-light[disabled]:hover,.bk-root .bk-btn-light[disabled]:focus,.bk-root .bk-btn-light[disabled]:active,.bk-root .bk-btn-light[disabled].bk-active{background-color:#e6e6e6;border-color:#ccc;}.bk-root .bk-btn-group{height:100%;display:flex;display:-webkit-flex;flex-wrap:nowrap;-webkit-flex-wrap:nowrap;align-items:center;-webkit-align-items:center;flex-direction:row;-webkit-flex-direction:row;}.bk-root .bk-btn-group > .bk-btn{flex-grow:1;-webkit-flex-grow:1;}.bk-root .bk-btn-group > .bk-btn + .bk-btn{margin-left:-1px;}.bk-root .bk-btn-group > .bk-btn:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0;}.bk-root .bk-btn-group > .bk-btn:not(:first-child):last-child{border-bottom-left-radius:0;border-top-left-radius:0;}.bk-root .bk-btn-group > .bk-btn:not(:first-child):not(:last-child){border-radius:0;}.bk-root .bk-btn-group .bk-dropdown-toggle{flex:0 0 0;-webkit-flex:0 0 0;padding:6px 6px;}`;
},
/* models/layouts/widget_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const column_1 = require(320) /* ./column */;
    class WidgetBoxView extends column_1.ColumnView {
    }
    exports.WidgetBoxView = WidgetBoxView;
    WidgetBoxView.__name__ = "WidgetBoxView";
    class WidgetBox extends column_1.Column {
        constructor(attrs) {
            super(attrs);
        }
        static init_WidgetBox() {
            this.prototype.default_view = WidgetBoxView;
        }
    }
    exports.WidgetBox = WidgetBox;
    WidgetBox.__name__ = "WidgetBox";
    WidgetBox.init_WidgetBox();
},
/* models/plots/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var gmap_plot_1 = require(331) /* ./gmap_plot */;
    __esExport("MapOptions", gmap_plot_1.MapOptions);
    var gmap_plot_2 = require(331) /* ./gmap_plot */;
    __esExport("GMapOptions", gmap_plot_2.GMapOptions);
    var gmap_plot_3 = require(331) /* ./gmap_plot */;
    __esExport("GMapPlot", gmap_plot_3.GMapPlot);
    var plot_1 = require(332) /* ./plot */;
    __esExport("Plot", plot_1.Plot);
},
/* models/plots/gmap_plot.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const plot_1 = require(332) /* ./plot */;
    const model_1 = require(53) /* ../../model */;
    const range1d_1 = require(156) /* ../ranges/range1d */;
    const gmap_plot_canvas_1 = require(337) /* ./gmap_plot_canvas */;
    __esExport("GMapPlotView", gmap_plot_canvas_1.GMapPlotView);
    class MapOptions extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_MapOptions() {
            this.define(({ Int, Number }) => ({
                lat: [Number],
                lng: [Number],
                zoom: [Int, 12],
            }));
        }
    }
    exports.MapOptions = MapOptions;
    MapOptions.__name__ = "MapOptions";
    MapOptions.init_MapOptions();
    class GMapOptions extends MapOptions {
        constructor(attrs) {
            super(attrs);
        }
        static init_GMapOptions() {
            this.define(({ Boolean, Int, String }) => ({
                map_type: [String, "roadmap"],
                scale_control: [Boolean, false],
                styles: [String],
                tilt: [Int, 45],
            }));
        }
    }
    exports.GMapOptions = GMapOptions;
    GMapOptions.__name__ = "GMapOptions";
    GMapOptions.init_GMapOptions();
    class GMapPlot extends plot_1.Plot {
        constructor(attrs) {
            super(attrs);
            this.use_map = true;
        }
        static init_GMapPlot() {
            this.prototype.default_view = gmap_plot_canvas_1.GMapPlotView;
            // This seems to be necessary so that everything can initialize.
            // Feels very clumsy, but I'm not sure how the properties system wants
            // to handle something like this situation.
            this.define(({ String, Ref }) => ({
                map_options: [Ref(GMapOptions)],
                api_key: [String],
                api_version: [String, "3.43"],
            }));
            this.override({
                x_range: () => new range1d_1.Range1d(),
                y_range: () => new range1d_1.Range1d(),
            });
        }
    }
    exports.GMapPlot = GMapPlot;
    GMapPlot.__name__ = "GMapPlot";
    GMapPlot.init_GMapPlot();
},
/* models/plots/plot.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const mixins = tslib_1.__importStar(require(48) /* ../../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(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const layout_dom_1 = require(319) /* ../layouts/layout_dom */;
    const axis_1 = require(163) /* ../axes/axis */;
    const grid_1 = require(316) /* ../grids/grid */;
    const annotation_1 = require(40) /* ../annotations/annotation */;
    const title_1 = require(138) /* ../annotations/title */;
    const linear_scale_1 = require(218) /* ../scales/linear_scale */;
    const toolbar_1 = require(235) /* ../tools/toolbar */;
    const range_1 = require(105) /* ../ranges/range */;
    const scale_1 = require(146) /* ../scales/scale */;
    const column_data_source_1 = require(130) /* ../sources/column_data_source */;
    const renderer_1 = require(41) /* ../renderers/renderer */;
    const data_renderer_1 = require(62) /* ../renderers/data_renderer */;
    const glyph_renderer_1 = require(61) /* ../renderers/glyph_renderer */;
    const data_range1d_1 = require(159) /* ../ranges/data_range1d */;
    const plot_canvas_1 = require(333) /* ./plot_canvas */;
    __esExport("PlotView", plot_canvas_1.PlotView);
    class Plot extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
            this.use_map = false;
        }
        static init_Plot() {
            this.prototype.default_view = plot_canvas_1.PlotView;
            this.mixins([
                ["outline_", mixins.Line],
                ["background_", mixins.Fill],
                ["border_", mixins.Fill],
            ]);
            this.define(({ Boolean, Number, String, Array, Dict, Or, Ref, Null, Nullable }) => ({
                toolbar: [Ref(toolbar_1.Toolbar), () => new toolbar_1.Toolbar()],
                toolbar_location: [Nullable(enums_1.Location), "right"],
                toolbar_sticky: [Boolean, true],
                plot_width: [p.Alias("width")],
                plot_height: [p.Alias("height")],
                frame_width: [Nullable(Number), null],
                frame_height: [Nullable(Number), null],
                title: [Or(Ref(title_1.Title), String, Null), () => new title_1.Title({ text: "" })],
                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()],
                extra_x_ranges: [Dict(Ref(range_1.Range)), {}],
                y_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
                extra_y_ranges: [Dict(Ref(range_1.Range)), {}],
                x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
                y_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
                lod_factor: [Number, 10],
                lod_interval: [Number, 300],
                lod_threshold: [Nullable(Number), 2000],
                lod_timeout: [Number, 500],
                hidpi: [Boolean, true],
                output_backend: [enums_1.OutputBackend, "canvas"],
                min_border: [Nullable(Number), 5],
                min_border_top: [Nullable(Number), null],
                min_border_left: [Nullable(Number), null],
                min_border_bottom: [Nullable(Number), null],
                min_border_right: [Nullable(Number), null],
                inner_width: [Number, 0],
                inner_height: [Number, 0],
                outer_width: [Number, 0],
                outer_height: [Number, 0],
                match_aspect: [Boolean, false],
                aspect_scale: [Number, 1],
                reset_policy: [enums_1.ResetPolicy, "standard"],
            }));
            this.override({
                width: 600,
                height: 600,
                outline_line_color: "#e5e5e5",
                border_fill_color: "#ffffff",
                background_fill_color: "#ffffff",
            });
        }
        _doc_attached() {
            super._doc_attached();
            this._push_changes([
                [this.properties.inner_height, null, this.inner_height],
                [this.properties.inner_width, null, this.inner_width],
            ]);
        }
        initialize() {
            super.initialize();
            this.reset = new signaling_1.Signal0(this, "reset");
            for (const xr of object_1.values(this.extra_x_ranges).concat(this.x_range)) {
                let plots = xr.plots;
                if (types_1.isArray(plots)) {
                    plots = plots.concat(this);
                    xr.setv({ plots }, { silent: true });
                }
            }
            for (const yr of object_1.values(this.extra_y_ranges).concat(this.y_range)) {
                let plots = yr.plots;
                if (types_1.isArray(plots)) {
                    plots = plots.concat(this);
                    yr.setv({ plots }, { silent: true });
                }
            }
        }
        add_layout(renderer, side = "center") {
            const renderers = this.properties[side].get_value();
            this.setv({ [side]: [...renderers, renderer] });
        }
        remove_layout(renderer) {
            const del = (items) => {
                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.concat(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) {
            this.toolbar.tools = this.toolbar.tools.concat(tools);
        }
        get panels() {
            return [...this.side_panels, ...this.center];
        }
        get side_panels() {
            const { above, below, left, right } = this;
            return array_1.concat([above, below, left, right]);
        }
    }
    exports.Plot = Plot;
    Plot.__name__ = "Plot";
    Plot.init_Plot();
},
/* models/plots/plot_canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const cartesian_frame_1 = require(144) /* ../canvas/cartesian_frame */;
    const canvas_1 = require(262) /* ../canvas/canvas */;
    const layout_dom_1 = require(319) /* ../layouts/layout_dom */;
    const annotation_1 = require(40) /* ../annotations/annotation */;
    const title_1 = require(138) /* ../annotations/title */;
    const axis_1 = require(163) /* ../axes/axis */;
    const toolbar_panel_1 = require(234) /* ../annotations/toolbar_panel */;
    const bokeh_events_1 = require(264) /* ../../core/bokeh_events */;
    const build_views_1 = require(122) /* ../../core/build_views */;
    const visuals_1 = require(45) /* ../../core/visuals */;
    const logging_1 = require(19) /* ../../core/logging */;
    const throttle_1 = require(334) /* ../../core/util/throttle */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(9) /* ../../core/util/array */;
    const canvas_2 = require(249) /* ../../core/util/canvas */;
    const alignments_1 = require(222) /* ../../core/layout/alignments */;
    const border_1 = require(225) /* ../../core/layout/border */;
    const grid_1 = require(223) /* ../../core/layout/grid */;
    const side_panel_1 = require(140) /* ../../core/layout/side_panel */;
    const bbox_1 = require(99) /* ../../core/util/bbox */;
    const range_manager_1 = require(335) /* ./range_manager */;
    const state_manager_1 = require(336) /* ./state_manager */;
    const settings_1 = require(28) /* ../../core/settings */;
    class PlotView extends layout_dom_1.LayoutDOMView {
        constructor() {
            super(...arguments);
            this._outer_bbox = new bbox_1.BBox();
            this._inner_bbox = new bbox_1.BBox();
            this._needs_paint = true;
            this._needs_layout = false;
            this._invalidated_painters = new Set();
            this._invalidate_all = true;
        }
        get canvas() {
            return this.canvas_view;
        }
        get state() {
            return this._state_manager;
        }
        set invalidate_dataranges(value) {
            this._range_manager.invalidate_dataranges = value;
        }
        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 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 -= 1;
            if (this._is_paused == 0 && !no_render)
                this.request_paint("everything");
        }
        // 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 (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._needs_layout = true;
            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() {
            build_views_1.remove_views(this.renderer_views);
            build_views_1.remove_views(this.tool_views);
            this.canvas_view.remove();
            super.remove();
        }
        render() {
            super.render();
            this.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(),
                dimensions: { width: 0, height: 0 },
            };
            this.visibility_callbacks = [];
            this.renderer_views = new Map();
            this.tool_views = new Map();
            this.frame = new cartesian_frame_1.CartesianFrame(this.model.x_scale, this.model.y_scale, this.model.x_range, this.model.y_range, this.model.extra_x_ranges, this.model.extra_y_ranges);
            this._range_manager = new range_manager_1.RangeManager(this);
            this._state_manager = new state_manager_1.StateManager(this, this._initial_state);
            this.throttled_paint = throttle_1.throttle(() => 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 } = this.model;
            if (toolbar_location != null && toolbar != null) {
                this._toolbar = new toolbar_panel_1.ToolbarPanel({ toolbar });
                toolbar.toolbar_location = toolbar_location;
            }
        }
        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 build_views_1.build_view(canvas, { parent: this });
            this.canvas_view.plot_views = [this];
            await this.build_renderer_views();
            await this.build_tool_views();
            this._range_manager.update_dataranges();
            this.unpause(true);
            logging_1.logger.debug("PlotView initialized");
        }
        _width_policy() {
            return this.model.frame_width == null ? super._width_policy() : "min";
        }
        _height_policy() {
            return this.model.frame_height == null ? super._height_policy() : "min";
        }
        _update_layout() {
            var _a, _b, _c, _d, _e;
            this.layout = new border_1.BorderLayout();
            this.layout.set_sizing(this.box_sizing());
            const above = array_1.copy(this.model.above);
            const below = array_1.copy(this.model.below);
            const left = array_1.copy(this.model.left);
            const right = array_1.copy(this.model.right);
            const get_side = (side) => {
                switch (side) {
                    case "above": return above;
                    case "below": return below;
                    case "left": return left;
                    case "right": return right;
                }
            };
            const { title_location, title } = this.model;
            if (title_location != null && title != null) {
                get_side(title_location).push(this._title);
            }
            const { toolbar_location, toolbar } = this.model;
            if (toolbar_location != null && toolbar != null) {
                const panels = get_side(toolbar_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 (toolbar_location == "above" || toolbar_location == "below")
                                panels[i] = [panel, this._toolbar];
                            else
                                panels[i] = [this._toolbar, panel];
                            push_toolbar = false;
                            break;
                        }
                    }
                }
                if (push_toolbar)
                    panels.push(this._toolbar);
            }
            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 (types_1.isArray(panel)) {
                        const items = panel.map((subpanel) => {
                            const item = set_layout(side, subpanel);
                            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;
                        });
                        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
                        layouts.push(set_layout(side, panel));
                }
                return layouts;
            };
            const min_border = (_a = this.model.min_border) !== null && _a !== void 0 ? _a : 0;
            this.layout.min_border = {
                left: (_b = this.model.min_border_left) !== null && _b !== void 0 ? _b : min_border,
                top: (_c = this.model.min_border_top) !== null && _c !== void 0 ? _c : min_border,
                right: (_d = this.model.min_border_right) !== null && _d !== void 0 ? _d : min_border,
                bottom: (_e = this.model.min_border_bottom) !== null && _e !== void 0 ? _e : min_border,
            };
            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.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 = array_1.reversed(set_layouts("above", above));
            bottom_panel.children = set_layouts("below", below);
            left_panel.children = array_1.reversed(set_layouts("left", left));
            right_panel.children = set_layouts("right", right);
            top_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: this.layout.min_border.top*/ });
            bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: this.layout.min_width.bottom*/ });
            left_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: this.layout.min_width.left*/ });
            right_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: this.layout.min_width.right*/ });
            this.layout.center_panel = center_panel;
            this.layout.top_panel = top_panel;
            this.layout.bottom_panel = bottom_panel;
            this.layout.left_panel = left_panel;
            this.layout.right_panel = right_panel;
        }
        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;
        }
        set_toolbar_visibility(visible) {
            for (const callback of this.visibility_callbacks)
                callback(visible);
        }
        update_range(range_info, options) {
            this.pause();
            this._range_manager.update(range_info, options);
            this.unpause();
        }
        reset_range() {
            this.update_range(null);
        }
        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() {
            const needs_layout = () => {
                var _a;
                for (const panel of this.model.side_panels) {
                    const view = this.renderer_views.get(panel);
                    if ((_a = view.layout) === null || _a === void 0 ? void 0 : _a.has_size_changed()) {
                        this.invalidate_painters(view);
                        return true;
                    }
                }
                return false;
            };
            if (needs_layout())
                this.root.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 tool of this.model.toolbar.tools) {
                if (tool.overlay != null)
                    yield tool.overlay;
                yield* tool.synthetic_renderers;
            }
        }
        async build_renderer_views() {
            this.computed_renderers = [...this._compute_renderers()];
            await build_views_1.build_views(this.renderer_views, this.computed_renderers, { parent: this });
        }
        async build_tool_views() {
            const tool_models = this.model.toolbar.tools;
            const new_tool_views = await build_views_1.build_views(this.tool_views, tool_models, { parent: this });
            new_tool_views.map((tool_view) => this.canvas_view.ui_event_bus.register_tool(tool_view));
        }
        connect_signals() {
            super.connect_signals();
            const { x_ranges, y_ranges } = this.frame;
            for (const [, range] of x_ranges) {
                this.connect(range.change, () => { this._needs_layout = true; this.request_paint("everything"); });
            }
            for (const [, range] of y_ranges) {
                this.connect(range.change, () => { this._needs_layout = true; this.request_paint("everything"); });
            }
            const { above, below, left, right, center, renderers } = this.model.properties;
            this.on_change([above, below, left, right, center, renderers], async () => await this.build_renderer_views());
            this.connect(this.model.toolbar.properties.tools.change, async () => {
                await this.build_renderer_views();
                await this.build_tool_views();
            });
            this.connect(this.model.change, () => this.request_paint("everything"));
            this.connect(this.model.reset, () => this.reset());
        }
        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();
            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._needs_layout = false;
            this.model.setv({
                inner_width: Math.round(this.frame.bbox.width),
                inner_height: Math.round(this.frame.bbox.height),
                outer_width: Math.round(this.layout.bbox.width),
                outer_height: Math.round(this.layout.bbox.height),
            }, { no_change: true });
            if (this.model.match_aspect !== false) {
                this.pause();
                this._range_manager.update_dataranges();
                this.unpause(true);
            }
            if (!this._outer_bbox.equals(this.layout.bbox)) {
                const { width, height } = this.layout.bbox;
                this.canvas_view.resize(width, height);
                this._outer_bbox = this.layout.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._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() {
            if (this._needs_layout)
                this._invalidate_layout();
            this.paint();
        }
        paint() {
            var _a;
            if (this.is_paused || !this.model.visible)
                return;
            logging_1.logger.trace(`PlotView.paint() for ${this.model.id}`);
            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();
            }
            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._map_hook(primary.ctx, frame_box);
                this._paint_empty(primary.ctx, frame_box);
                this._paint_outline(primary.ctx, frame_box);
                this._paint_levels(primary.ctx, "image", frame_box, true);
                this._paint_levels(primary.ctx, "underlay", frame_box, true);
                this._paint_levels(primary.ctx, "glyph", frame_box, true);
                this._paint_levels(primary.ctx, "guide", frame_box, false);
                this._paint_levels(primary.ctx, "annotation", frame_box, false);
                primary.finish();
            }
            if (do_overlays || settings_1.settings.wireframe) {
                overlays.prepare();
                this._paint_levels(overlays.ctx, "overlay", frame_box, false);
                if (settings_1.settings.wireframe)
                    this._paint_layout(overlays.ctx, this.layout);
                overlays.finish();
            }
            if (this._initial_state.range == null) {
                this._initial_state.range = (_a = this._range_manager.compute_initial()) !== null && _a !== void 0 ? _a : undefined;
            }
            this._needs_paint = false;
        }
        _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 && renderer_view.needs_webgl_blit) {
                    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();
            }
        }
        _map_hook(_ctx, _frame_box) { }
        _paint_empty(ctx, frame_box) {
            const [cx, cy, cw, ch] = [0, 0, this.layout.bbox.width, this.layout.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.layout.bbox.width) {
                    w -= 1;
                }
                if (y0 + h == this.layout.bbox.height) {
                    h -= 1;
                }
                ctx.strokeRect(x0, y0, w, h);
                ctx.restore();
            }
        }
        to_blob() {
            return this.canvas_view.to_blob();
        }
        export(type, hidpi = true) {
            const output_backend = type == "png" ? "canvas" : "svg";
            const composite = new canvas_2.CanvasLayer(output_backend, hidpi);
            const { width, height } = this.layout.bbox;
            composite.resize(width, height);
            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()
                .map((view) => view.serializable_state())
                .filter((item) => item.bbox != null);
            return Object.assign(Object.assign({}, state), { children: [...children !== null && children !== void 0 ? children : [], ...renderers] });
        }
    }
    exports.PlotView = PlotView;
    PlotView.__name__ = "PlotView";
},
/* core/util/throttle.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    /**
     * Returns a function, that, when invoked, will only be triggered at
     * most once during a given interval of time and no more frequently
     * than the animation frame rate allows it.
     *
     * @param func [function] the function to throttle
     * @param wait [number] time in milliseconds to use for window
     * @return [function] throttled function
     */
    function throttle(func, wait) {
        let timeout = null;
        let previous = 0;
        let pending = false;
        return function () {
            return new Promise((resolve, reject) => {
                const later = function () {
                    previous = Date.now();
                    timeout = 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;
                    requestAnimationFrame(later);
                }
                else if (!timeout && !pending) {
                    timeout = setTimeout(() => requestAnimationFrame(later), remaining);
                }
                else {
                    resolve();
                }
            });
        };
    }
    exports.throttle = throttle;
},
/* models/plots/range_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_range1d_1 = require(159) /* ../ranges/data_range1d */;
    const logging_1 = require(19) /* ../../core/logging */;
    class RangeManager {
        constructor(parent) {
            this.parent = parent;
            this.invalidate_dataranges = true;
        }
        get frame() {
            return this.parent.frame;
        }
        update(range_info, options) {
            const { x_ranges, y_ranges } = this.frame;
            if (range_info == null) {
                for (const [, range] of x_ranges) {
                    range.reset();
                }
                for (const [, range] of y_ranges) {
                    range.reset();
                }
                this.update_dataranges();
            }
            else {
                const range_info_iter = [];
                for (const [name, range] of x_ranges) {
                    range_info_iter.push([range, range_info.xrs.get(name)]);
                }
                for (const [name, range] of y_ranges) {
                    range_info_iter.push([range, range_info.yrs.get(name)]);
                }
                if (options === null || options === void 0 ? void 0 : options.scrolling) {
                    this._update_ranges_together(range_info_iter); // apply interval bounds while keeping aspect
                }
                this._update_ranges_individually(range_info_iter, options);
            }
        }
        reset() {
            this.update(null);
        }
        update_dataranges() {
            // Update any DataRange1ds here
            const bounds = new Map();
            const log_bounds = new Map();
            let calculate_log_bounds = false;
            for (const [, xr] of this.frame.x_ranges) {
                if (xr instanceof data_range1d_1.DataRange1d && xr.scale_hint == "log")
                    calculate_log_bounds = true;
            }
            for (const [, yr] of this.frame.y_ranges) {
                if (yr instanceof data_range1d_1.DataRange1d && yr.scale_hint == "log")
                    calculate_log_bounds = true;
            }
            for (const renderer of this.parent.model.data_renderers) {
                const renderer_view = this.parent.renderer_view(renderer);
                if (renderer_view == null)
                    continue;
                const bds = renderer_view.glyph_view.bounds();
                if (bds != null)
                    bounds.set(renderer, bds);
                if (calculate_log_bounds) {
                    const log_bds = renderer_view.glyph_view.log_bounds();
                    if (log_bds != null)
                        log_bounds.set(renderer, log_bds);
                }
            }
            let follow_enabled = false;
            let has_bounds = false;
            const { width, height } = this.frame.bbox;
            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 this.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.model, r);
                    if (xr.follow) {
                        follow_enabled = true;
                    }
                }
                if (xr.bounds != null)
                    has_bounds = true;
            }
            for (const [, yr] of this.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.model, r);
                    if (yr.follow) {
                        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 this.frame.x_ranges) {
                    xr.bounds = null;
                }
                for (const [, yr] of this.frame.y_ranges) {
                    yr.bounds = 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 [name, range] of x_ranges) {
                const { start, end } = range;
                if (start == null || end == null || isNaN(start + end)) {
                    good_vals = false;
                    break;
                }
                xrs.set(name, { start, end });
            }
            if (good_vals) {
                for (const [name, range] of y_ranges) {
                    const { start, end } = range;
                    if (start == null || end == null || isNaN(start + end)) {
                        good_vals = false;
                        break;
                    }
                    yrs.set(name, { start, end });
                }
            }
            if (good_vals)
                return { xrs, yrs };
            else {
                logging_1.logger.warn('could not set initial ranges');
                return null;
            }
        }
        _update_ranges_together(range_info_iter) {
            // 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_info_iter) {
                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_info_iter) {
                    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_info_iter, options) {
            const panning = !!(options === null || options === void 0 ? void 0 : options.panning);
            const scrolling = !!(options === null || options === void 0 ? void 0 : options.scrolling);
            let hit_bound = false;
            for (const [rng, range_info] of range_info_iter) {
                // 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 && rng.bounds != "auto") { // check `auto` for type-checking purpose
                    const [min, max] = rng.bounds;
                    const new_interval = Math.abs(range_info.end - range_info.start);
                    if (rng.is_reversed) {
                        if (min != null) {
                            if (min >= range_info.end) {
                                hit_bound = true;
                                range_info.end = min;
                                if (panning || scrolling) {
                                    range_info.start = min + new_interval;
                                }
                            }
                        }
                        if (max != null) {
                            if (max <= range_info.start) {
                                hit_bound = true;
                                range_info.start = max;
                                if (panning || scrolling) {
                                    range_info.end = max - new_interval;
                                }
                            }
                        }
                    }
                    else {
                        if (min != null) {
                            if (min >= range_info.start) {
                                hit_bound = true;
                                range_info.start = min;
                                if (panning || scrolling) {
                                    range_info.end = min + new_interval;
                                }
                            }
                        }
                        if (max != null) {
                            if (max <= range_info.end) {
                                hit_bound = true;
                                range_info.end = max;
                                if (panning || scrolling) {
                                    range_info.start = max - new_interval;
                                }
                            }
                        }
                    }
                }
            }
            // Cancel the event when hitting a bound while scrolling. This ensures that
            // the scroll-zoom tool maintains its focus position. Setting `maintain_focus`
            // to false results in a more "gliding" behavior, allowing one to
            // zoom out more smoothly, at the cost of losing the focus position.
            if (scrolling && hit_bound && (options === null || options === void 0 ? void 0 : options.maintain_focus))
                return;
            for (const [rng, range_info] of range_info_iter) {
                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.parent = parent;
            this.initial_state = initial_state;
            this.changed = new signaling_1.Signal0(this.parent, "state_changed");
            this.history = [];
            this.index = -1;
        }
        _do_state_change(index) {
            const state = this.history[index] != null ? this.history[index].state : this.initial_state;
            if (state.range != null)
                this.parent.update_range(state.range);
            if (state.selection != null)
                this.parent.update_selection(state.selection);
        }
        push(type, new_state) {
            const { history, index } = this;
            const prev_state = history[index] != null ? 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;
                this._do_state_change(this.index);
                this.changed.emit();
            }
        }
        redo() {
            if (this.can_redo) {
                this.index += 1;
                this._do_state_change(this.index);
                this.changed.emit();
            }
        }
        get can_undo() {
            return this.index >= 0;
        }
        get can_redo() {
            return this.index < this.history.length - 1;
        }
    }
    exports.StateManager = StateManager;
    StateManager.__name__ = "StateManager";
},
/* 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(43) /* ../../core/dom */;
    const projections_1 = require(65) /* ../../core/util/projections */;
    const color_1 = require(22) /* ../../core/util/color */;
    const plot_canvas_1 = require(333) /* ./plot_canvas */;
    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() {
            this.pause();
            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;
            if (!this.model.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.`);
            }
            if (typeof google === "undefined" || google.maps == null) {
                if (typeof window._bokeh_gmaps_callback === "undefined") {
                    const { api_key, api_version } = this.model;
                    load_google_api(api_key, api_version);
                }
                gmaps_ready.connect(() => this.request_paint("everything"));
            }
            this.unpause();
        }
        remove() {
            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.update_range(null, options);
                // PAN ----------------------------
            }
            else if (range_info.sdx != null || range_info.sdy != null) {
                this.map.panBy((_a = range_info.sdx) !== null && _a !== void 0 ? _a : 0, (_b = range_info.sdy) !== null && _b !== void 0 ? _b : 0);
                super.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();
                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_el = dom_1.div({ style: { position: "absolute" } });
            this.canvas_view.add_underlay(this.map_el);
            this.map = new maps.Map(this.map_el, map_options);
            // update bokeh ranges whenever the map idles, which should be after most UI action
            maps.event.addListener(this.map, 'idle', () => 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_styles());
            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) {
            const c = this.map.getCenter().toJSON();
            c[fld] = this.model.map_options[fld];
            this.map.setCenter(c);
            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_styles();
            this._update_center('lat');
            this._update_center('lng');
            this._update_zoom();
            this._update_map_type();
        }
        _update_styles() {
            this.map.setOptions({ styles: JSON.parse(this.model.map_options.styles) });
        }
        _update_zoom() {
            this.map.setOptions({ zoom: this.model.map_options.zoom });
            this._set_bokeh_ranges();
        }
        // this method is expected and called by PlotView.render
        _map_hook(_ctx, frame_box) {
            if (this.map == null && typeof google !== "undefined" && google.maps != null)
                this._build_map();
            if (this.map_el != null) {
                const [left, top, width, height] = frame_box;
                this.map_el.style.top = `${top}px`;
                this.map_el.style.left = `${left}px`;
                this.map_el.style.width = `${width}px`;
                this.map_el.style.height = `${height}px`;
            }
        }
        // this overrides the standard _paint_empty to make the inner canvas transparent
        _paint_empty(ctx, frame_box) {
            const ow = this.layout.bbox.width;
            const oh = this.layout.bbox.height;
            const [left, top, iw, ih] = frame_box;
            ctx.clearRect(0, 0, ow, oh);
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.lineTo(0, oh);
            ctx.lineTo(ow, oh);
            ctx.lineTo(ow, 0);
            ctx.lineTo(0, 0);
            ctx.moveTo(left, top);
            ctx.lineTo(left + iw, top);
            ctx.lineTo(left + iw, top + ih);
            ctx.lineTo(left, top + ih);
            ctx.lineTo(left, top);
            ctx.closePath();
            if (this.model.border_fill_color != null) {
                ctx.fillStyle = color_1.color2css(this.model.border_fill_color);
                ctx.fill();
            }
        }
    }
    exports.GMapPlotView = GMapPlotView;
    GMapPlotView.__name__ = "GMapPlotView";
},
/* models/policies/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(169) /* ./labeling */, exports);
},
/* models/renderers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var glyph_renderer_1 = require(61) /* ./glyph_renderer */;
    __esExport("GlyphRenderer", glyph_renderer_1.GlyphRenderer);
    var graph_renderer_1 = require(123) /* ./graph_renderer */;
    __esExport("GraphRenderer", graph_renderer_1.GraphRenderer);
    var guide_renderer_1 = require(164) /* ./guide_renderer */;
    __esExport("GuideRenderer", guide_renderer_1.GuideRenderer);
    var renderer_1 = require(41) /* ./renderer */;
    __esExport("Renderer", renderer_1.Renderer);
},
/* models/selections/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(129) /* ./interaction_policy */, exports);
    var selection_1 = require(59) /* ./selection */;
    __esExport("Selection", selection_1.Selection);
},
/* models/sources/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var server_sent_data_source_1 = require(342) /* ./server_sent_data_source */;
    __esExport("ServerSentDataSource", server_sent_data_source_1.ServerSentDataSource);
    var ajax_data_source_1 = require(344) /* ./ajax_data_source */;
    __esExport("AjaxDataSource", ajax_data_source_1.AjaxDataSource);
    var column_data_source_1 = require(130) /* ./column_data_source */;
    __esExport("ColumnDataSource", column_data_source_1.ColumnDataSource);
    var columnar_data_source_1 = require(57) /* ./columnar_data_source */;
    __esExport("ColumnarDataSource", columnar_data_source_1.ColumnarDataSource);
    var cds_view_1 = require(120) /* ./cds_view */;
    __esExport("CDSView", cds_view_1.CDSView);
    var data_source_1 = require(58) /* ./data_source */;
    __esExport("DataSource", data_source_1.DataSource);
    var geojson_data_source_1 = require(345) /* ./geojson_data_source */;
    __esExport("GeoJSONDataSource", geojson_data_source_1.GeoJSONDataSource);
    var web_data_source_1 = require(343) /* ./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(343) /* ./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 = (event) => {
                    var _a;
                    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) {
    __esModule();
    const column_data_source_1 = require(130) /* ./column_data_source */;
    const enums_1 = require(20) /* ../../core/enums */;
    class WebDataSource extends column_data_source_1.ColumnDataSource {
        constructor(attrs) {
            super(attrs);
        }
        get_column(colname) {
            const column = this.data[colname];
            return column != null ? column : [];
        }
        get_length() {
            var _a;
            return (_a = super.get_length()) !== null && _a !== void 0 ? _a : 0;
        }
        initialize() {
            super.initialize();
            this.setup();
        }
        load_data(raw_data, mode, max_size) {
            const { adapter } = this;
            let data;
            if (adapter != null)
                data = adapter.execute(this, { response: raw_data });
            else
                data = raw_data;
            switch (mode) {
                case "replace": {
                    this.data = data;
                    break;
                }
                case "append": {
                    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;
                }
            }
        }
        static init_WebDataSource() {
            this.define(({ Any, Int, String, Nullable }) => ({
                max_size: [Nullable(Int), null],
                mode: [enums_1.UpdateMode, "replace"],
                adapter: [Nullable(Any /*TODO*/), null],
                data_url: [String],
            }));
        }
    }
    exports.WebDataSource = WebDataSource;
    WebDataSource.__name__ = "WebDataSource";
    WebDataSource.init_WebDataSource();
},
/* models/sources/ajax_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const web_data_source_1 = require(343) /* ./web_data_source */;
    const enums_1 = require(20) /* ../../core/enums */;
    const logging_1 = require(19) /* ../../core/logging */;
    const object_1 = require(13) /* ../../core/util/object */;
    class AjaxDataSource extends web_data_source_1.WebDataSource {
        constructor(attrs) {
            super(attrs);
            this.interval = null;
            this.initialized = false;
        }
        static init_AjaxDataSource() {
            this.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],
            }));
        }
        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 object_1.entries(http_headers)) {
                xhr.setRequestHeader(name, value);
            }
            return xhr;
        }
        do_load(xhr, mode, max_size) {
            if (xhr.status === 200) {
                const raw_data = JSON.parse(xhr.responseText);
                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;
    AjaxDataSource.__name__ = "AjaxDataSource";
    AjaxDataSource.init_AjaxDataSource();
},
/* models/sources/geojson_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const columnar_data_source_1 = require(57) /* ./columnar_data_source */;
    const logging_1 = require(19) /* ../../core/logging */;
    const array_1 = require(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../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);
        }
        static init_GeoJSONDataSource() {
            this.define(({ String }) => ({
                geojson: [String],
            }));
            this.internal(({ Dict, Arrayable }) => ({
                data: [Dict(Arrayable), {}],
            }));
        }
        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 array_1.range(0, length).map((_i) => []);
        }
        _get_new_nan_array(length) {
            return array_1.range(0, length).map((_i) => NaN);
        }
        _add_properties(item, data, i, item_count) {
            var _a;
            const properties = (_a = item.properties) !== null && _a !== void 0 ? _a : {};
            for (const [property, value] of 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 (geojson.geometries == null)
                        throw new Error('No geometries found in GeometryCollection');
                    if (geojson.geometries.length === 0)
                        throw new Error('geojson.geometries must have one or more items');
                    items = geojson.geometries;
                    break;
                }
                case "FeatureCollection": {
                    if (geojson.features == null)
                        throw new Error('No features found in FeaturesCollection');
                    if (geojson.features.length == 0)
                        throw new Error('geojson.features must have one or more items');
                    items = geojson.features;
                    break;
                }
                default:
                    throw new Error('Bokeh only supports type GeometryCollection and FeatureCollection at top level');
            }
            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;
    GeoJSONDataSource.__name__ = "GeoJSONDataSource";
    GeoJSONDataSource.init_GeoJSONDataSource();
},
/* models/tiles/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var bbox_tile_source_1 = require(347) /* ./bbox_tile_source */;
    __esExport("BBoxTileSource", bbox_tile_source_1.BBoxTileSource);
    var mercator_tile_source_1 = require(348) /* ./mercator_tile_source */;
    __esExport("MercatorTileSource", mercator_tile_source_1.MercatorTileSource);
    var quadkey_tile_source_1 = require(351) /* ./quadkey_tile_source */;
    __esExport("QUADKEYTileSource", quadkey_tile_source_1.QUADKEYTileSource);
    var tile_renderer_1 = require(352) /* ./tile_renderer */;
    __esExport("TileRenderer", tile_renderer_1.TileRenderer);
    var tile_source_1 = require(349) /* ./tile_source */;
    __esExport("TileSource", tile_source_1.TileSource);
    var tms_tile_source_1 = require(355) /* ./tms_tile_source */;
    __esExport("TMSTileSource", tms_tile_source_1.TMSTileSource);
    var wmts_tile_source_1 = require(353) /* ./wmts_tile_source */;
    __esExport("WMTSTileSource", wmts_tile_source_1.WMTSTileSource);
},
/* models/tiles/bbox_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(348) /* ./mercator_tile_source */;
    class BBoxTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        static init_BBoxTileSource() {
            this.define(({ Boolean }) => ({
                use_latlon: [Boolean, false],
            }));
        }
        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;
    BBoxTileSource.__name__ = "BBoxTileSource";
    BBoxTileSource.init_BBoxTileSource();
},
/* models/tiles/mercator_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tile_source_1 = require(349) /* ./tile_source */;
    const array_1 = require(9) /* ../../core/util/array */;
    const tile_utils_1 = require(350) /* ./tile_utils */;
    class MercatorTileSource extends tile_source_1.TileSource {
        constructor(attrs) {
            super(attrs);
        }
        static init_MercatorTileSource() {
            this.define(({ Boolean }) => ({
                snap_to_zoom: [Boolean, false],
                wrap_around: [Boolean, true],
            }));
            this.override({
                x_origin_offset: 20037508.34,
                y_origin_offset: 20037508.34,
                initial_resolution: 156543.03392804097,
            });
        }
        initialize() {
            super.initialize();
            this._resolutions = 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] = 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;
    MercatorTileSource.__name__ = "MercatorTileSource";
    MercatorTileSource.init_MercatorTileSource();
},
/* models/tiles/tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const object_1 = require(13) /* ../../core/util/object */;
    class TileSource extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_TileSource() {
            this.define(({ Number, String, Dict, Nullable }) => ({
                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],
            }));
        }
        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 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;
    TileSource.__name__ = "TileSource";
    TileSource.init_TileSource();
},
/* models/tiles/tile_utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const projections_1 = require(65) /* ../../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(348) /* ./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) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tile_source_1 = require(349) /* ./tile_source */;
    const wmts_tile_source_1 = require(353) /* ./wmts_tile_source */;
    const renderer_1 = require(41) /* ../renderers/renderer */;
    const range1d_1 = require(156) /* ../ranges/range1d */;
    const dom_1 = require(43) /* ../../core/dom */;
    const image_1 = require(296) /* ../../core/util/image */;
    const array_1 = require(9) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    const tiles_css_1 = tslib_1.__importStar(require(354) /* ../../styles/tiles.css */);
    class TileRendererView extends renderer_1.RendererView {
        initialize() {
            this._tiles = [];
            super.initialize();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_render());
            this.connect(this.model.tile_source.change, () => this.request_render());
        }
        styles() {
            return [...super.styles(), tiles_css_1.default];
        }
        get_extent() {
            return [this.x_range.start, this.y_range.start, this.x_range.end, this.y_range.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)
                dom_1.removeElement(this.attribution_el);
            const { attribution } = this.model.tile_source;
            if (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 = dom_1.div({
                    class: tiles_css_1.tile_attribution,
                    style: {
                        position: "absolute",
                        right: `${offset_right}px`,
                        bottom: `${offset_bottom}px`,
                        'max-width': `${max_width - 4 /*padding*/}px`,
                        padding: "2px",
                        'background-color': 'rgba(255,255,255,0.5)',
                        'font-size': '9px',
                        'line-height': '1.05',
                        'white-space': 'nowrap',
                        overflow: 'hidden',
                        'text-overflow': 'ellipsis',
                    },
                });
                this.plot_view.canvas_view.add_event(this.attribution_el);
                this.attribution_el.innerHTML = attribution;
                this.attribution_el.title = this.attribution_el.textContent.replace(/\s*\n\s*/g, " ");
            }
        }
        _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 [nx, ny, nz] = this.model.tile_source.normalize_xyz(x, y, z);
            const tile = {
                img: undefined,
                tile_coords: [x, y, z],
                normalized_coords: [nx, ny, nz],
                quadkey: this.model.tile_source.tile_xyz_to_quadkey(x, y, z),
                cache_key: this.model.tile_source.tile_xyz_to_key(x, y, z),
                bounds,
                loaded: false,
                finished: false,
                x_coord: bounds[0],
                y_coord: bounds[3],
            };
            const src = this.model.tile_source.get_image_url(nx, ny, nz);
            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;
                },
            });
            this.model.tile_source.tiles.set(tile.cache_key, tile);
            this._tiles.push(tile);
        }
        _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.length === 0) {
                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.getImageSmoothingEnabled();
                this.map_canvas.setImageSmoothingEnabled(this.model.smoothing);
                this.map_canvas.drawImage(tile_data.img, sx, sy, sw, sh);
                this.map_canvas.setImageSmoothingEnabled(old_smoothing);
                tile_data.finished = true;
            }
        }
        _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({ x_range: { 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 && !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);
        }
        static init_TileRenderer() {
            this.prototype.default_view = TileRendererView;
            this.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],
            }));
            this.override({
                level: "image",
            });
        }
    }
    exports.TileRenderer = TileRenderer;
    TileRenderer.__name__ = "TileRenderer";
    TileRenderer.init_TileRenderer();
},
/* models/tiles/wmts_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(348) /* ./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/tiles.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tile_attribution = "bk-tile-attribution";
    exports.default = `.bk-root .bk-tile-attribution a{color:black;}`;
},
/* models/tiles/tms_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(348) /* ./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(357) /* ./canvas_texture */;
    __esExport("CanvasTexture", canvas_texture_1.CanvasTexture);
    var image_url_texture_1 = require(359) /* ./image_url_texture */;
    __esExport("ImageURLTexture", image_url_texture_1.ImageURLTexture);
    var texture_1 = require(358) /* ./texture */;
    __esExport("Texture", texture_1.Texture);
},
/* models/textures/canvas_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const texture_1 = require(358) /* ./texture */;
    const string_1 = require(34) /* ../../core/util/string */;
    class CanvasTexture extends texture_1.Texture {
        constructor(attrs) {
            super(attrs);
        }
        static init_CanvasTexture() {
            this.define(({ String }) => ({
                code: [String],
            }));
        }
        get func() {
            const code = 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;
    CanvasTexture.__name__ = "CanvasTexture";
    CanvasTexture.init_CanvasTexture();
},
/* models/textures/texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../model */;
    const enums_1 = require(20) /* ../../core/enums */;
    class Texture extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_Texture() {
            this.define(() => ({
                repetition: [enums_1.TextureRepetition, "repeat"],
            }));
        }
    }
    exports.Texture = Texture;
    Texture.__name__ = "Texture";
    Texture.init_Texture();
},
/* models/textures/image_url_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const texture_1 = require(358) /* ./texture */;
    const image_1 = require(296) /* ../../core/util/image */;
    class ImageURLTexture extends texture_1.Texture {
        constructor(attrs) {
            super(attrs);
        }
        static init_ImageURLTexture() {
            this.define(({ String }) => ({
                url: [String],
            }));
        }
        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;
    ImageURLTexture.__name__ = "ImageURLTexture";
    ImageURLTexture.init_ImageURLTexture();
},
/* models/tools/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var action_tool_1 = require(251) /* ./actions/action_tool */;
    __esExport("ActionTool", action_tool_1.ActionTool);
    var custom_action_1 = require(361) /* ./actions/custom_action */;
    __esExport("CustomAction", custom_action_1.CustomAction);
    var help_tool_1 = require(252) /* ./actions/help_tool */;
    __esExport("HelpTool", help_tool_1.HelpTool);
    var redo_tool_1 = require(362) /* ./actions/redo_tool */;
    __esExport("RedoTool", redo_tool_1.RedoTool);
    var reset_tool_1 = require(363) /* ./actions/reset_tool */;
    __esExport("ResetTool", reset_tool_1.ResetTool);
    var save_tool_1 = require(364) /* ./actions/save_tool */;
    __esExport("SaveTool", save_tool_1.SaveTool);
    var undo_tool_1 = require(365) /* ./actions/undo_tool */;
    __esExport("UndoTool", undo_tool_1.UndoTool);
    var zoom_in_tool_1 = require(366) /* ./actions/zoom_in_tool */;
    __esExport("ZoomInTool", zoom_in_tool_1.ZoomInTool);
    var zoom_out_tool_1 = require(369) /* ./actions/zoom_out_tool */;
    __esExport("ZoomOutTool", zoom_out_tool_1.ZoomOutTool);
    var button_tool_1 = require(238) /* ./button_tool */;
    __esExport("ButtonTool", button_tool_1.ButtonTool);
    var edit_tool_1 = require(370) /* ./edit/edit_tool */;
    __esExport("EditTool", edit_tool_1.EditTool);
    var box_edit_tool_1 = require(371) /* ./edit/box_edit_tool */;
    __esExport("BoxEditTool", box_edit_tool_1.BoxEditTool);
    var freehand_draw_tool_1 = require(372) /* ./edit/freehand_draw_tool */;
    __esExport("FreehandDrawTool", freehand_draw_tool_1.FreehandDrawTool);
    var point_draw_tool_1 = require(373) /* ./edit/point_draw_tool */;
    __esExport("PointDrawTool", point_draw_tool_1.PointDrawTool);
    var poly_draw_tool_1 = require(374) /* ./edit/poly_draw_tool */;
    __esExport("PolyDrawTool", poly_draw_tool_1.PolyDrawTool);
    var poly_tool_1 = require(375) /* ./edit/poly_tool */;
    __esExport("PolyTool", poly_tool_1.PolyTool);
    var poly_edit_tool_1 = require(376) /* ./edit/poly_edit_tool */;
    __esExport("PolyEditTool", poly_edit_tool_1.PolyEditTool);
    var box_select_tool_1 = require(377) /* ./gestures/box_select_tool */;
    __esExport("BoxSelectTool", box_select_tool_1.BoxSelectTool);
    var box_zoom_tool_1 = require(379) /* ./gestures/box_zoom_tool */;
    __esExport("BoxZoomTool", box_zoom_tool_1.BoxZoomTool);
    var gesture_tool_1 = require(237) /* ./gestures/gesture_tool */;
    __esExport("GestureTool", gesture_tool_1.GestureTool);
    var lasso_select_tool_1 = require(380) /* ./gestures/lasso_select_tool */;
    __esExport("LassoSelectTool", lasso_select_tool_1.LassoSelectTool);
    var line_edit_tool_1 = require(382) /* ./edit/line_edit_tool */;
    __esExport("LineEditTool", line_edit_tool_1.LineEditTool);
    var pan_tool_1 = require(384) /* ./gestures/pan_tool */;
    __esExport("PanTool", pan_tool_1.PanTool);
    var poly_select_tool_1 = require(381) /* ./gestures/poly_select_tool */;
    __esExport("PolySelectTool", poly_select_tool_1.PolySelectTool);
    var range_tool_1 = require(385) /* ./gestures/range_tool */;
    __esExport("RangeTool", range_tool_1.RangeTool);
    var select_tool_1 = require(378) /* ./gestures/select_tool */;
    __esExport("SelectTool", select_tool_1.SelectTool);
    var tap_tool_1 = require(386) /* ./gestures/tap_tool */;
    __esExport("TapTool", tap_tool_1.TapTool);
    var wheel_pan_tool_1 = require(387) /* ./gestures/wheel_pan_tool */;
    __esExport("WheelPanTool", wheel_pan_tool_1.WheelPanTool);
    var wheel_zoom_tool_1 = require(388) /* ./gestures/wheel_zoom_tool */;
    __esExport("WheelZoomTool", wheel_zoom_tool_1.WheelZoomTool);
    var crosshair_tool_1 = require(389) /* ./inspectors/crosshair_tool */;
    __esExport("CrosshairTool", crosshair_tool_1.CrosshairTool);
    var customjs_hover_1 = require(390) /* ./inspectors/customjs_hover */;
    __esExport("CustomJSHover", customjs_hover_1.CustomJSHover);
    var hover_tool_1 = require(391) /* ./inspectors/hover_tool */;
    __esExport("HoverTool", hover_tool_1.HoverTool);
    var inspect_tool_1 = require(247) /* ./inspectors/inspect_tool */;
    __esExport("InspectTool", inspect_tool_1.InspectTool);
    var tool_1 = require(236) /* ./tool */;
    __esExport("Tool", tool_1.Tool);
    var tool_proxy_1 = require(392) /* ./tool_proxy */;
    __esExport("ToolProxy", tool_proxy_1.ToolProxy);
    var toolbar_1 = require(235) /* ./toolbar */;
    __esExport("Toolbar", toolbar_1.Toolbar);
    var toolbar_base_1 = require(248) /* ./toolbar_base */;
    __esExport("ToolbarBase", toolbar_base_1.ToolbarBase);
    var toolbar_box_1 = require(393) /* ./toolbar_box */;
    __esExport("ProxyToolbar", toolbar_box_1.ProxyToolbar);
    var toolbar_box_2 = require(393) /* ./toolbar_box */;
    __esExport("ToolbarBox", toolbar_box_2.ToolbarBox);
},
/* models/tools/actions/custom_action.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(251) /* ./action_tool */;
    class CustomActionButtonView extends action_tool_1.ActionToolButtonView {
        css_classes() {
            return super.css_classes().concat("bk-toolbar-button-custom-action");
        }
    }
    exports.CustomActionButtonView = CustomActionButtonView;
    CustomActionButtonView.__name__ = "CustomActionButtonView";
    class CustomActionView extends action_tool_1.ActionToolView {
        doit() {
            var _a;
            (_a = this.model.callback) === null || _a === void 0 ? void 0 : _a.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.button_view = CustomActionButtonView;
        }
        static init_CustomAction() {
            this.prototype.default_view = CustomActionView;
            this.define(({ Any, String, Nullable }) => ({
                callback: [Nullable(Any /*TODO*/)],
                icon: [String],
            }));
            this.override({
                description: "Perform a Custom Action",
            });
        }
    }
    exports.CustomAction = CustomAction;
    CustomAction.__name__ = "CustomAction";
    CustomAction.init_CustomAction();
},
/* models/tools/actions/redo_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(251) /* ./action_tool */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class RedoToolView extends action_tool_1.ActionToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.plot_view.state.changed, () => this.model.disabled = !this.plot_view.state.can_redo);
        }
        doit() {
            this.plot_view.state.redo();
        }
    }
    exports.RedoToolView = RedoToolView;
    RedoToolView.__name__ = "RedoToolView";
    class RedoTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Redo";
            this.icon = icons_css_1.tool_icon_redo;
        }
        static init_RedoTool() {
            this.prototype.default_view = RedoToolView;
            this.override({
                disabled: true,
            });
            this.register_alias("redo", () => new RedoTool());
        }
    }
    exports.RedoTool = RedoTool;
    RedoTool.__name__ = "RedoTool";
    RedoTool.init_RedoTool();
},
/* models/tools/actions/reset_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(251) /* ./action_tool */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class ResetToolView extends action_tool_1.ActionToolView {
        doit() {
            this.plot_view.reset();
        }
    }
    exports.ResetToolView = ResetToolView;
    ResetToolView.__name__ = "ResetToolView";
    class ResetTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Reset";
            this.icon = icons_css_1.tool_icon_reset;
        }
        static init_ResetTool() {
            this.prototype.default_view = ResetToolView;
            this.register_alias("reset", () => new ResetTool());
        }
    }
    exports.ResetTool = ResetTool;
    ResetTool.__name__ = "ResetTool";
    ResetTool.init_ResetTool();
},
/* models/tools/actions/save_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(251) /* ./action_tool */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class SaveToolView extends action_tool_1.ActionToolView {
        async copy() {
            const blob = await this.plot_view.to_blob();
            const item = new ClipboardItem({ [blob.type]: blob });
            await navigator.clipboard.write([item]);
        }
        async save(name) {
            const blob = await this.plot_view.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") {
            switch (action) {
                case "save":
                    this.save("bokeh_plot");
                    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.icon = icons_css_1.tool_icon_save;
        }
        static init_SaveTool() {
            this.prototype.default_view = SaveToolView;
            this.register_alias("save", () => new SaveTool());
        }
        get menu() {
            return [
                {
                    icon: "bk-tool-icon-copy-to-clipboard",
                    tooltip: "Copy image to clipboard",
                    if: () => typeof ClipboardItem !== "undefined",
                    handler: () => {
                        this.do.emit("copy");
                    },
                },
            ];
        }
    }
    exports.SaveTool = SaveTool;
    SaveTool.__name__ = "SaveTool";
    SaveTool.init_SaveTool();
},
/* models/tools/actions/undo_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(251) /* ./action_tool */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class UndoToolView extends action_tool_1.ActionToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.plot_view.state.changed, () => this.model.disabled = !this.plot_view.state.can_undo);
        }
        doit() {
            this.plot_view.state.undo();
        }
    }
    exports.UndoToolView = UndoToolView;
    UndoToolView.__name__ = "UndoToolView";
    class UndoTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Undo";
            this.icon = icons_css_1.tool_icon_undo;
        }
        static init_UndoTool() {
            this.prototype.default_view = UndoToolView;
            this.override({
                disabled: true,
            });
            this.register_alias("undo", () => new UndoTool());
        }
    }
    exports.UndoTool = UndoTool;
    UndoTool.__name__ = "UndoTool";
    UndoTool.init_UndoTool();
},
/* models/tools/actions/zoom_in_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const zoom_base_tool_1 = require(367) /* ./zoom_base_tool */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class ZoomInToolView extends zoom_base_tool_1.ZoomBaseToolView {
    }
    exports.ZoomInToolView = ZoomInToolView;
    ZoomInToolView.__name__ = "ZoomInToolView";
    class ZoomInTool extends zoom_base_tool_1.ZoomBaseTool {
        constructor(attrs) {
            super(attrs);
            this.sign = 1;
            this.tool_name = "Zoom In";
            this.icon = icons_css_1.tool_icon_zoom_in;
        }
        static init_ZoomInTool() {
            this.prototype.default_view = ZoomInToolView;
            this.register_alias("zoom_in", () => new ZoomInTool({ dimensions: "both" }));
            this.register_alias("xzoom_in", () => new ZoomInTool({ dimensions: "width" }));
            this.register_alias("yzoom_in", () => new ZoomInTool({ dimensions: "height" }));
        }
    }
    exports.ZoomInTool = ZoomInTool;
    ZoomInTool.__name__ = "ZoomInTool";
    ZoomInTool.init_ZoomInTool();
},
/* models/tools/actions/zoom_base_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const action_tool_1 = require(251) /* ./action_tool */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const zoom_1 = require(368) /* ../../../core/util/zoom */;
    class ZoomBaseToolView extends action_tool_1.ActionToolView {
        doit() {
            var _a;
            const frame = this.plot_view.frame;
            const dims = this.model.dimensions;
            // restrict to axis configured in tool's dimensions property
            const h_axis = dims == 'width' || dims == 'both';
            const v_axis = dims == 'height' || dims == 'both';
            const zoom_info = zoom_1.scale_range(frame, this.model.sign * this.model.factor, h_axis, v_axis);
            this.plot_view.state.push("zoom_out", { range: zoom_info });
            this.plot_view.update_range(zoom_info, { scrolling: true });
            (_a = this.model.document) === null || _a === void 0 ? void 0 : _a.interactive_start(this.plot_model);
        }
    }
    exports.ZoomBaseToolView = ZoomBaseToolView;
    ZoomBaseToolView.__name__ = "ZoomBaseToolView";
    class ZoomBaseTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
        }
        static init_ZoomBaseTool() {
            this.define(({ Percent }) => ({
                factor: [Percent, 0.1],
                dimensions: [enums_1.Dimensions, "both"],
            }));
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.ZoomBaseTool = ZoomBaseTool;
    ZoomBaseTool.__name__ = "ZoomBaseTool";
    ZoomBaseTool.init_ZoomBaseTool();
},
/* core/util/zoom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const math_1 = require(10) /* ./math */;
    // Module for zoom-related functions
    function scale_highlow(range, factor, center) {
        const [low, high] = [range.start, range.end];
        const x = center != null ? center : (high + low) / 2.0;
        const x0 = low - (low - x) * factor;
        const x1 = high - (high - x) * factor;
        return [x0, x1];
    }
    exports.scale_highlow = scale_highlow;
    function get_info(scales, [sxy0, sxy1]) {
        const info = new Map();
        for (const [name, scale] of scales) {
            const [start, end] = scale.r_invert(sxy0, sxy1);
            info.set(name, { start, end });
        }
        return info;
    }
    exports.get_info = get_info;
    function scale_range(frame, factor, h_axis = true, v_axis = true, center) {
        /*
         * Utility function for zoom tools to calculate/create the zoom_info object
         * of the form required by ``PlotView.update_range``
         *
         * Parameters:
         *   frame : CartesianFrame
         *   factor : Number
         *   h_axis : Boolean, optional
         *     whether to zoom the horizontal axis (default = true)
         *   v_axis : Boolean, optional
         *     whether to zoom the horizontal axis (default = true)
         *   center : object, optional
         *     of form {'x': Number, 'y', Number}
         *
         * Returns:
         *   object:
         */
        // clamp the  magnitude of factor, if it is > 1 bad things happen
        factor = math_1.clamp(factor, -0.9, 0.9);
        const hfactor = h_axis ? factor : 0;
        const [sx0, sx1] = scale_highlow(frame.bbox.h_range, hfactor, center != null ? center.x : undefined);
        const xrs = get_info(frame.x_scales, [sx0, sx1]);
        const vfactor = v_axis ? factor : 0;
        const [sy0, sy1] = scale_highlow(frame.bbox.v_range, vfactor, center != null ? center.y : undefined);
        const yrs = get_info(frame.y_scales, [sy0, sy1]);
        // OK this sucks we can't set factor independently in each direction. It is used
        // for GMap plots, and GMap plots always preserve aspect, so effective the value
        // of 'dimensions' is ignored.
        return { xrs, yrs, factor };
    }
    exports.scale_range = scale_range;
},
/* models/tools/actions/zoom_out_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const zoom_base_tool_1 = require(367) /* ./zoom_base_tool */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class ZoomOutToolView extends zoom_base_tool_1.ZoomBaseToolView {
    }
    exports.ZoomOutToolView = ZoomOutToolView;
    ZoomOutToolView.__name__ = "ZoomOutToolView";
    class ZoomOutTool extends zoom_base_tool_1.ZoomBaseTool {
        constructor(attrs) {
            super(attrs);
            this.sign = -1;
            this.tool_name = "Zoom Out";
            this.icon = icons_css_1.tool_icon_zoom_out;
        }
        static init_ZoomOutTool() {
            this.prototype.default_view = ZoomOutToolView;
            this.register_alias("zoom_out", () => new ZoomOutTool({ dimensions: "both" }));
            this.register_alias("xzoom_out", () => new ZoomOutTool({ dimensions: "width" }));
            this.register_alias("yzoom_out", () => new ZoomOutTool({ dimensions: "height" }));
        }
    }
    exports.ZoomOutTool = ZoomOutTool;
    ZoomOutTool.__name__ = "ZoomOutTool";
    ZoomOutTool.init_ZoomOutTool();
},
/* models/tools/edit/edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(9) /* ../../../core/util/array */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const assert_1 = require(11) /* ../../../core/util/assert */;
    const glyph_renderer_1 = require(61) /* ../../renderers/glyph_renderer */;
    const gesture_tool_1 = require(237) /* ../gestures/gesture_tool */;
    class EditToolView extends gesture_tool_1.GestureToolView {
        constructor() {
            super(...arguments);
            this._mouse_in_frame = true;
        }
        _select_mode(ev) {
            const { shiftKey, ctrlKey } = ev;
            if (!shiftKey && !ctrlKey)
                return "replace";
            else if (shiftKey && !ctrlKey)
                return "append";
            else if (!shiftKey && ctrlKey)
                return "intersect";
            else if (shiftKey && ctrlKey)
                return "subtract";
            else
                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 || !columns.length)
                return;
            for (const column of columns) {
                let array = cds.get_array(column);
                const drop = array.length - num_objects + 1;
                if (drop < 1)
                    continue;
                if (!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) {
                cds.data = cds.data;
                cds.properties.data.change.emit();
            }
        }
        _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 (!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);
        }
        static init_EditTool() {
            this.define(({ Unknown, String, Array, Ref }) => ({
                custom_icon: [String],
                empty_value: [Unknown],
                renderers: [Array(Ref(glyph_renderer_1.GlyphRenderer)), []],
            }));
        }
        get computed_icon() {
            var _a;
            return (_a = this.custom_icon) !== null && _a !== void 0 ? _a : this.icon;
        }
    }
    exports.EditTool = EditTool;
    EditTool.__name__ = "EditTool";
    EditTool.init_EditTool();
},
/* models/tools/edit/box_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(43) /* ../../../core/dom */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const edit_tool_1 = require(370) /* ./edit_tool */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class BoxEditToolView extends edit_tool_1.EditToolView {
        _tap(ev) {
            if ((this._draw_basepoint != null) || (this._basepoint != null))
                return;
            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.keyCode === dom_1.Keys.Backspace) {
                    this._delete_selected(renderer);
                }
                else if (ev.keyCode == dom_1.Keys.Esc) {
                    // 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) {
            const renderer = this.model.renderers[0];
            const renderer_view = this.plot_view.renderer_view(renderer);
            if (renderer_view == null)
                return;
            // Type once dataspecs are typed
            const glyph = renderer.glyph;
            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 [x, y] = [(x0 + x1) / 2, (y0 + y1) / 2];
            const [w, h] = [x1 - x0, y1 - y0];
            const [xkey, ykey] = [glyph.x.field, glyph.y.field];
            const [wkey, hkey] = [glyph.width.field, glyph.height.field];
            if (append) {
                this._pop_glyphs(cds, this.model.num_objects);
                if (xkey)
                    cds.get_array(xkey).push(x);
                if (ykey)
                    cds.get_array(ykey).push(y);
                if (wkey)
                    cds.get_array(wkey).push(w);
                if (hkey)
                    cds.get_array(hkey).push(h);
                this._pad_empty_columns(cds, [xkey, ykey, wkey, hkey]);
            }
            else {
                const index = cds.data[xkey].length - 1;
                if (xkey)
                    cds.data[xkey][index] = x;
                if (ykey)
                    cds.data[ykey][index] = y;
                if (wkey)
                    cds.data[wkey][index] = w;
                if (hkey)
                    cds.data[hkey][index] = h;
            }
            this._emit_cds_changes(cds, true, false, emit);
        }
        _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 limits = this.model._get_dim_limits(this._draw_basepoint, curpoint, frame, dims);
            if (limits != null) {
                const [sxlim, sylim] = limits;
                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.shiftKey) {
                if (this._draw_basepoint != null)
                    return;
                this._draw_basepoint = [ev.sx, ev.sy];
                this._update_box(ev, true, false);
            }
            else {
                if (this._basepoint != null)
                    return;
                this._select_event(ev, "append", this.model.renderers);
                this._basepoint = [ev.sx, ev.sy];
            }
        }
        _pan(ev, append = false, emit = false) {
            if (ev.shiftKey) {
                if (this._draw_basepoint == null)
                    return;
                this._update_box(ev, append, emit);
            }
            else {
                if (this._basepoint == null)
                    return;
                this._drag_points(ev, this.model.renderers);
            }
        }
        _pan_end(ev) {
            this._pan(ev, false, true);
            if (ev.shiftKey) {
                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.icon = icons_css_1.tool_icon_box_edit;
            this.event_type = ["tap", "pan", "move"];
            this.default_order = 1;
        }
        static init_BoxEditTool() {
            this.prototype.default_view = BoxEditToolView;
            this.define(({ Int }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                num_objects: [Int, 0],
            }));
        }
    }
    exports.BoxEditTool = BoxEditTool;
    BoxEditTool.__name__ = "BoxEditTool";
    BoxEditTool.init_BoxEditTool();
},
/* models/tools/edit/freehand_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(43) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const edit_tool_1 = require(370) /* ./edit_tool */;
    const icons_css_1 = require(242) /* ../../../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 (!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 (!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.keyCode === dom_1.Keys.Esc) {
                    renderer.data_source.selection_manager.clear();
                }
                else if (ev.keyCode === dom_1.Keys.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.icon = icons_css_1.tool_icon_freehand_draw;
            this.event_type = ["pan", "tap"];
            this.default_order = 3;
        }
        static init_FreehandDrawTool() {
            this.prototype.default_view = FreehandDrawToolView;
            this.define(({ Int }) => ({
                num_objects: [Int, 0],
            }));
        }
    }
    exports.FreehandDrawTool = FreehandDrawTool;
    FreehandDrawTool.__name__ = "FreehandDrawTool";
    FreehandDrawTool.init_FreehandDrawTool();
},
/* models/tools/edit/point_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(43) /* ../../../core/dom */;
    const edit_tool_1 = require(370) /* ./edit_tool */;
    const icons_css_1 = require(242) /* ../../../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 || !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]);
            cds.change.emit();
            cds.data = cds.data;
            cds.properties.data.change.emit();
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame)
                return;
            for (const renderer of this.model.renderers) {
                if (ev.keyCode === dom_1.Keys.Backspace) {
                    this._delete_selected(renderer);
                }
                else if (ev.keyCode == dom_1.Keys.Esc) {
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        _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.icon = icons_css_1.tool_icon_point_draw;
            this.event_type = ["tap", "pan", "move"];
            this.default_order = 2;
        }
        static init_PointDrawTool() {
            this.prototype.default_view = PointDrawToolView;
            this.define(({ Boolean, Int }) => ({
                add: [Boolean, true],
                drag: [Boolean, true],
                num_objects: [Int, 0],
            }));
        }
    }
    exports.PointDrawTool = PointDrawTool;
    PointDrawTool.__name__ = "PointDrawTool";
    PointDrawTool.init_PointDrawTool();
},
/* models/tools/edit/poly_draw_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(43) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const poly_tool_1 = require(375) /* ./poly_tool */;
    const icons_css_1 = require(242) /* ../../../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 (!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 (!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.keyCode === dom_1.Keys.Backspace) {
                    this._delete_selected(renderer);
                }
                else if (ev.keyCode == dom_1.Keys.Esc) {
                    if (this._drawing) {
                        this._remove();
                        this._drawing = false;
                    }
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        _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 || !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)
                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.icon = icons_css_1.tool_icon_poly_draw;
            this.event_type = ["pan", "tap", "move"];
            this.default_order = 3;
        }
        static init_PolyDrawTool() {
            this.prototype.default_view = PolyDrawToolView;
            this.define(({ Boolean, Int }) => ({
                drag: [Boolean, true],
                num_objects: [Int, 0],
            }));
        }
    }
    exports.PolyDrawTool = PolyDrawTool;
    PolyDrawTool.__name__ = "PolyDrawTool";
    PolyDrawTool.init_PolyDrawTool();
},
/* models/tools/edit/poly_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ../../../core/util/types */;
    const edit_tool_1 = require(370) /* ./edit_tool */;
    class PolyToolView extends edit_tool_1.EditToolView {
        _set_vertices(xs, ys) {
            const point_glyph = this.model.vertex_renderer.glyph;
            const point_cds = this.model.vertex_renderer.data_source;
            const [pxkey, pykey] = [point_glyph.x.field, point_glyph.y.field];
            if (pxkey) {
                if (types_1.isArray(xs))
                    point_cds.data[pxkey] = xs;
                else
                    point_glyph.x = { value: xs };
            }
            if (pykey) {
                if (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) {
                // 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) {
                    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);
        }
        static init_PolyTool() {
            this.define(({ AnyRef }) => ({
                vertex_renderer: [AnyRef()],
            }));
        }
    }
    exports.PolyTool = PolyTool;
    PolyTool.__name__ = "PolyTool";
    PolyTool.init_PolyTool();
},
/* models/tools/edit/poly_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(43) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const poly_tool_1 = require(375) /* ./poly_tool */;
    const icons_css_1 = require(242) /* ../../../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.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 && 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;
            const vsync_renderer = this.model.renderers[0];
            const vsync_updater = () => this._update_vertices(vsync_renderer);
            const vsync_ds = vsync_renderer === null || vsync_renderer === void 0 ? void 0 : vsync_renderer.data_source;
            const renderers = this._select_event(ev, "replace", this.model.renderers);
            if (!renderers.length) {
                this._set_vertices([], []);
                this._selected_renderer = null;
                this._drawing = false;
                this._cur_index = null;
                if (vsync_ds != null)
                    vsync_ds.disconnect(vsync_ds.properties.data.change, vsync_updater);
                return;
            }
            if (vsync_ds != null)
                vsync_ds.connect(vsync_ds.properties.data.change, vsync_updater);
            this._cur_index = renderers[0].data_source.selected.indices[0];
            this._update_vertices(renderers[0]);
        }
        _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 (!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 (!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;
                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;
            const point = this._map_drag(ev.sx, ev.sy, renderer);
            if (point == null)
                return;
            else if (this._drawing && this._selected_renderer) {
                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)
                return;
            const renderer = this.model.vertex_renderer;
            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) {
            this._select_event(ev, "append", [this.model.vertex_renderer]);
            this._basepoint = [ev.sx, ev.sy];
        }
        _pan(ev) {
            if (this._basepoint == null)
                return;
            this._drag_points(ev, [this.model.vertex_renderer]);
            if (this._selected_renderer)
                this._selected_renderer.data_source.change.emit();
        }
        _pan_end(ev) {
            if (this._basepoint == null)
                return;
            this._drag_points(ev, [this.model.vertex_renderer]);
            this._emit_cds_changes(this.model.vertex_renderer.data_source, false, true, true);
            if (this._selected_renderer) {
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            this._basepoint = null;
        }
        _keyup(ev) {
            if (!this.model.active || !this._mouse_in_frame)
                return;
            let renderers;
            if (this._selected_renderer) {
                renderers = [this.model.vertex_renderer];
            }
            else {
                renderers = this.model.renderers;
            }
            for (const renderer of renderers) {
                if (ev.keyCode === dom_1.Keys.Backspace) {
                    this._delete_selected(renderer);
                    if (this._selected_renderer) {
                        this._emit_cds_changes(this._selected_renderer.data_source);
                    }
                }
                else if (ev.keyCode == dom_1.Keys.Esc) {
                    if (this._drawing) {
                        this._remove_vertex();
                        this._drawing = false;
                    }
                    else if (this._selected_renderer) {
                        this._hide_vertices();
                    }
                    renderer.data_source.selection_manager.clear();
                }
            }
        }
        deactivate() {
            if (!this._selected_renderer) {
                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.icon = icons_css_1.tool_icon_poly_edit;
            this.event_type = ["tap", "pan", "move"];
            this.default_order = 4;
        }
        static init_PolyEditTool() {
            this.prototype.default_view = PolyEditToolView;
        }
    }
    exports.PolyEditTool = PolyEditTool;
    PolyEditTool.__name__ = "PolyEditTool";
    PolyEditTool.init_PolyEditTool();
},
/* models/tools/gestures/box_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const select_tool_1 = require(378) /* ./select_tool */;
    const box_annotation_1 = require(136) /* ../../annotations/box_annotation */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class BoxSelectToolView extends select_tool_1.SelectToolView {
        _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);
        }
        _pan_start(ev) {
            const { sx, sy } = ev;
            this._base_point = [sx, sy];
        }
        _pan(ev) {
            const { sx, sy } = ev;
            const curpoint = [sx, sy];
            const [sxlim, sylim] = this._compute_limits(curpoint);
            this.model.overlay.update({ left: sxlim[0], right: sxlim[1], top: sylim[0], bottom: sylim[1] });
            if (this.model.select_every_mousemove) {
                this._do_select(sxlim, sylim, false, this._select_mode(ev));
            }
        }
        _pan_end(ev) {
            const { sx, sy } = ev;
            const curpoint = [sx, sy];
            const [sxlim, sylim] = this._compute_limits(curpoint);
            this._do_select(sxlim, sylim, true, this._select_mode(ev));
            this.model.overlay.update({ left: null, right: null, top: null, bottom: null });
            this._base_point = null;
            this.plot_view.state.push("box_select", { selection: this.plot_view.get_selection() });
        }
        _do_select([sx0, sx1], [sy0, sy1], final, mode = "replace") {
            const geometry = { type: 'rect', sx0, sx1, sy0, sy1 };
            this._select(geometry, final, mode);
        }
    }
    exports.BoxSelectToolView = BoxSelectToolView;
    BoxSelectToolView.__name__ = "BoxSelectToolView";
    const DEFAULT_BOX_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            level: "overlay",
            top_units: "screen",
            left_units: "screen",
            bottom_units: "screen",
            right_units: "screen",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    class BoxSelectTool extends select_tool_1.SelectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Box Select";
            this.icon = icons_css_1.tool_icon_box_select;
            this.event_type = "pan";
            this.default_order = 30;
        }
        static init_BoxSelectTool() {
            this.prototype.default_view = BoxSelectToolView;
            this.define(({ Boolean, Ref }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                select_every_mousemove: [Boolean, false],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_BOX_OVERLAY],
                origin: [enums_1.BoxOrigin, "corner"],
            }));
            this.register_alias("box_select", () => new BoxSelectTool());
            this.register_alias("xbox_select", () => new BoxSelectTool({ dimensions: 'width' }));
            this.register_alias("ybox_select", () => new BoxSelectTool({ dimensions: 'height' }));
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.BoxSelectTool = BoxSelectTool;
    BoxSelectTool.__name__ = "BoxSelectTool";
    BoxSelectTool.init_BoxSelectTool();
},
/* models/tools/gestures/select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const gesture_tool_1 = require(237) /* ./gesture_tool */;
    const glyph_renderer_1 = require(61) /* ../../renderers/glyph_renderer */;
    const graph_renderer_1 = require(123) /* ../../renderers/graph_renderer */;
    const data_renderer_1 = require(62) /* ../../renderers/data_renderer */;
    const util_1 = require(161) /* ../../util */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const dom_1 = require(43) /* ../../../core/dom */;
    const bokeh_events_1 = require(264) /* ../../../core/bokeh_events */;
    const signaling_1 = require(15) /* ../../../core/signaling */;
    const assert_1 = require(11) /* ../../../core/util/assert */;
    class SelectToolView extends gesture_tool_1.GestureToolView {
        connect_signals() {
            super.connect_signals();
            this.model.clear.connect(() => this._clear());
        }
        get computed_renderers() {
            const { renderers, names } = this.model;
            const all_renderers = this.plot_model.data_renderers;
            return util_1.compute_renderers(renderers, all_renderers, names);
        }
        _computed_renderers_by_data_source() {
            var _a;
            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 = (_a = renderers_by_source.get(source)) !== null && _a !== void 0 ? _a : [];
                renderers_by_source.set(source, [...renderers, r]);
            }
            return renderers_by_source;
        }
        _select_mode(ev) {
            const { shiftKey, ctrlKey } = ev;
            if (!shiftKey && !ctrlKey)
                return this.model.mode;
            else if (shiftKey && !ctrlKey)
                return "append";
            else if (!shiftKey && ctrlKey)
                return "intersect";
            else if (shiftKey && ctrlKey)
                return "subtract";
            else
                assert_1.unreachable();
        }
        _keyup(ev) {
            if (ev.keyCode == dom_1.Keys.Esc) {
                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);
        }
        _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);
            }
            // XXX: messed up class structure
            if (this.model.callback != null)
                this._emit_callback(geometry);
            this._emit_selection_event(geometry, final);
        }
        _emit_selection_event(geometry, final = true) {
            const { x_scale, y_scale } = this.plot_view.frame;
            let geometry_data;
            switch (geometry.type) {
                case "point": {
                    const { sx, sy } = geometry;
                    const x = x_scale.invert(sx);
                    const y = y_scale.invert(sy);
                    geometry_data = Object.assign(Object.assign({}, geometry), { x, y });
                    break;
                }
                case "span": {
                    const { sx, sy } = geometry;
                    const x = x_scale.invert(sx);
                    const y = y_scale.invert(sy);
                    geometry_data = Object.assign(Object.assign({}, geometry), { x, y });
                    break;
                }
                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);
                    geometry_data = Object.assign(Object.assign({}, geometry), { x0, y0, x1, y1 });
                    break;
                }
                case "poly": {
                    const { sx, sy } = geometry;
                    const x = x_scale.v_invert(sx);
                    const y = y_scale.v_invert(sy);
                    geometry_data = Object.assign(Object.assign({}, geometry), { x, y });
                    break;
                }
            }
            this.plot_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");
        }
        static init_SelectTool() {
            this.define(({ String, Array, Ref, Or, Auto }) => ({
                renderers: [Or(Array(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
                names: [Array(String), []],
                mode: [enums_1.SelectionMode, "replace"],
            }));
        }
        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 (Esc)",
                    handler: () => {
                        this.clear.emit();
                    },
                },
            ];
        }
    }
    exports.SelectTool = SelectTool;
    SelectTool.__name__ = "SelectTool";
    SelectTool.init_SelectTool();
},
/* models/tools/gestures/box_zoom_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const gesture_tool_1 = require(237) /* ./gesture_tool */;
    const box_annotation_1 = require(136) /* ../../annotations/box_annotation */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class BoxZoomToolView extends gesture_tool_1.GestureToolView {
        _match_aspect(base_point, curpoint, 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(base_point[0] - curpoint[0]);
            let vh = Math.abs(base_point[1] - curpoint[1]);
            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
            // base_point[0] is left
            let left;
            let right;
            if (base_point[0] <= curpoint[0]) {
                left = base_point[0];
                right = base_point[0] + vw * xmod;
                if (right > hend)
                    right = hend;
                // base_point[0] is right
            }
            else {
                right = base_point[0];
                left = base_point[0] - vw * xmod;
                if (left < hstart)
                    left = hstart;
            }
            vw = Math.abs(right - left);
            // base_point[1] is bottom
            let top;
            let bottom;
            if (base_point[1] <= curpoint[1]) {
                bottom = base_point[1];
                top = base_point[1] + vw / a;
                if (top > vend)
                    top = vend;
                // base_point[1] is top
            }
            else {
                top = base_point[1];
                bottom = base_point[1] - vw / a;
                if (bottom < vstart)
                    bottom = vstart;
            }
            vh = Math.abs(top - bottom);
            // base_point[0] is left
            if (base_point[0] <= curpoint[0])
                right = base_point[0] + a * vh;
            // base_point[0] is right
            else
                left = base_point[0] - a * vh;
            return [[left, right], [bottom, top]];
        }
        _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)];
            }
            let sx;
            let sy;
            if (this.model.match_aspect && dims == 'both')
                [sx, sy] = this._match_aspect(base_point, curpoint, frame);
            else
                [sx, sy] = this.model._get_dim_limits(base_point, curpoint, frame, dims);
            return [sx, sy];
        }
        _pan_start(ev) {
            this._base_point = [ev.sx, ev.sy];
        }
        _pan(ev) {
            const curpoint = [ev.sx, ev.sy];
            const [sx, sy] = this._compute_limits(curpoint);
            this.model.overlay.update({ left: sx[0], right: sx[1], top: sy[0], bottom: sy[1] });
        }
        _pan_end(ev) {
            const curpoint = [ev.sx, ev.sy];
            const [sx, sy] = this._compute_limits(curpoint);
            this._update(sx, sy);
            this.model.overlay.update({ left: null, right: null, top: null, bottom: null });
            this._base_point = null;
        }
        _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 [name, scale] of x_scales) {
                const [start, end] = scale.r_invert(sx0, sx1);
                xrs.set(name, { start, end });
            }
            const yrs = new Map();
            for (const [name, scale] of y_scales) {
                const [start, end] = scale.r_invert(sy0, sy1);
                yrs.set(name, { start, end });
            }
            const zoom_info = { xrs, yrs };
            this.plot_view.state.push("box_zoom", { range: zoom_info });
            this.plot_view.update_range(zoom_info);
        }
    }
    exports.BoxZoomToolView = BoxZoomToolView;
    BoxZoomToolView.__name__ = "BoxZoomToolView";
    const DEFAULT_BOX_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            level: "overlay",
            top_units: "screen",
            left_units: "screen",
            bottom_units: "screen",
            right_units: "screen",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    class BoxZoomTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Box Zoom";
            this.icon = icons_css_1.tool_icon_box_zoom;
            this.event_type = "pan";
            this.default_order = 20;
        }
        static init_BoxZoomTool() {
            this.prototype.default_view = BoxZoomToolView;
            this.define(({ Boolean, Ref }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_BOX_OVERLAY],
                match_aspect: [Boolean, false],
                origin: [enums_1.BoxOrigin, "corner"],
            }));
            this.register_alias("box_zoom", () => new BoxZoomTool({ dimensions: 'both' }));
            this.register_alias("xbox_zoom", () => new BoxZoomTool({ dimensions: 'width' }));
            this.register_alias("ybox_zoom", () => new BoxZoomTool({ dimensions: 'height' }));
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.BoxZoomTool = BoxZoomTool;
    BoxZoomTool.__name__ = "BoxZoomTool";
    BoxZoomTool.init_BoxZoomTool();
},
/* models/tools/gestures/lasso_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const select_tool_1 = require(378) /* ./select_tool */;
    const poly_annotation_1 = require(231) /* ../../annotations/poly_annotation */;
    const poly_select_tool_1 = require(381) /* ./poly_select_tool */;
    const dom_1 = require(43) /* ../../../core/dom */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class LassoSelectToolView extends select_tool_1.SelectToolView {
        constructor() {
            super(...arguments);
            this.sxs = [];
            this.sys = [];
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.active.change, () => this._active_change());
        }
        _active_change() {
            if (!this.model.active)
                this._clear_overlay();
        }
        _keyup(ev) {
            if (ev.keyCode == dom_1.Keys.Enter)
                this._clear_overlay();
        }
        _pan_start(ev) {
            this.sxs = [];
            this.sys = [];
            const { sx, sy } = ev;
            this._append_overlay(sx, sy);
        }
        _pan(ev) {
            const [sx, sy] = this.plot_view.frame.bbox.clip(ev.sx, ev.sy);
            this._append_overlay(sx, sy);
            if (this.model.select_every_mousemove) {
                this._do_select(this.sxs, this.sys, false, this._select_mode(ev));
            }
        }
        _pan_end(ev) {
            const { sxs, sys } = this;
            this._clear_overlay();
            this._do_select(sxs, sys, true, this._select_mode(ev));
            this.plot_view.state.push("lasso_select", { selection: this.plot_view.get_selection() });
        }
        _append_overlay(sx, sy) {
            const { sxs, sys } = this;
            sxs.push(sx);
            sys.push(sy);
            this.model.overlay.update({ xs: sxs, ys: sys });
        }
        _clear_overlay() {
            this.sxs = [];
            this.sys = [];
            this.model.overlay.update({ xs: this.sxs, ys: this.sys });
        }
        _do_select(sx, sy, final, mode) {
            const geometry = { type: "poly", sx, sy };
            this._select(geometry, final, mode);
        }
    }
    exports.LassoSelectToolView = LassoSelectToolView;
    LassoSelectToolView.__name__ = "LassoSelectToolView";
    class LassoSelectTool extends select_tool_1.SelectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Lasso Select";
            this.icon = icons_css_1.tool_icon_lasso_select;
            this.event_type = "pan";
            this.default_order = 12;
        }
        static init_LassoSelectTool() {
            this.prototype.default_view = LassoSelectToolView;
            this.define(({ Boolean, Ref }) => ({
                select_every_mousemove: [Boolean, true],
                overlay: [Ref(poly_annotation_1.PolyAnnotation), poly_select_tool_1.DEFAULT_POLY_OVERLAY],
            }));
            this.register_alias("lasso_select", () => new LassoSelectTool());
        }
    }
    exports.LassoSelectTool = LassoSelectTool;
    LassoSelectTool.__name__ = "LassoSelectTool";
    LassoSelectTool.init_LassoSelectTool();
},
/* models/tools/gestures/poly_select_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const select_tool_1 = require(378) /* ./select_tool */;
    const poly_annotation_1 = require(231) /* ../../annotations/poly_annotation */;
    const dom_1 = require(43) /* ../../../core/dom */;
    const array_1 = require(9) /* ../../../core/util/array */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class PolySelectToolView extends select_tool_1.SelectToolView {
        initialize() {
            super.initialize();
            this.data = { sx: [], sy: [] };
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.active.change, () => this._active_change());
        }
        _active_change() {
            if (!this.model.active)
                this._clear_data();
        }
        _keyup(ev) {
            if (ev.keyCode == dom_1.Keys.Enter)
                this._clear_data();
        }
        _doubletap(ev) {
            this._do_select(this.data.sx, this.data.sy, true, this._select_mode(ev));
            this.plot_view.state.push("poly_select", { selection: this.plot_view.get_selection() });
            this._clear_data();
        }
        _clear_data() {
            this.data = { sx: [], sy: [] };
            this.model.overlay.update({ xs: [], ys: [] });
        }
        _tap(ev) {
            const { sx, sy } = ev;
            const frame = this.plot_view.frame;
            if (!frame.bbox.contains(sx, sy))
                return;
            this.data.sx.push(sx);
            this.data.sy.push(sy);
            this.model.overlay.update({ xs: array_1.copy(this.data.sx), ys: array_1.copy(this.data.sy) });
        }
        _do_select(sx, sy, final, mode) {
            const geometry = { type: 'poly', sx, sy };
            this._select(geometry, final, mode);
        }
    }
    exports.PolySelectToolView = PolySelectToolView;
    PolySelectToolView.__name__ = "PolySelectToolView";
    const DEFAULT_POLY_OVERLAY = () => {
        return new poly_annotation_1.PolyAnnotation({
            level: "overlay",
            xs_units: "screen",
            ys_units: "screen",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 2,
            line_dash: [4, 4],
        });
    };
    exports.DEFAULT_POLY_OVERLAY = DEFAULT_POLY_OVERLAY;
    class PolySelectTool extends select_tool_1.SelectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Poly Select";
            this.icon = icons_css_1.tool_icon_polygon_select;
            this.event_type = "tap";
            this.default_order = 11;
        }
        static init_PolySelectTool() {
            this.prototype.default_view = PolySelectToolView;
            this.define(({ Ref }) => ({
                overlay: [Ref(poly_annotation_1.PolyAnnotation), exports.DEFAULT_POLY_OVERLAY],
            }));
            this.register_alias("poly_select", () => new PolySelectTool());
        }
    }
    exports.PolySelectTool = PolySelectTool;
    PolySelectTool.__name__ = "PolySelectTool";
    PolySelectTool.init_PolySelectTool();
},
/* models/tools/edit/line_edit_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const enums_1 = require(20) /* ../../../core/enums */;
    const line_tool_1 = require(383) /* ./line_tool */;
    const icons_css_1 = require(242) /* ../../../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) {
                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) {
                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)
                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) {
                this._emit_cds_changes(this._selected_renderer.data_source);
            }
            this._basepoint = null;
        }
        activate() {
            this._drawing = true;
        }
        deactivate() {
            if (!this._selected_renderer) {
                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.icon = icons_css_1.tool_icon_line_edit;
            this.event_type = ["tap", "pan", "move"];
            this.default_order = 4;
        }
        static init_LineEditTool() {
            this.prototype.default_view = LineEditToolView;
            this.define(() => ({
                dimensions: [enums_1.Dimensions, "both"],
            }));
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.LineEditTool = LineEditTool;
    LineEditTool.__name__ = "LineEditTool";
    LineEditTool.init_LineEditTool();
},
/* models/tools/edit/line_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(8) /* ../../../core/util/types */;
    const edit_tool_1 = require(370) /* ./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 (types_1.isArray(x))
                    point_cds.data[pxkey] = x;
                else
                    point_glyph.x = { value: x };
            }
            if (pykey) {
                if (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);
        }
        static init_LineTool() {
            this.define(({ AnyRef }) => ({
                intersection_renderer: [AnyRef()],
            }));
        }
    }
    exports.LineTool = LineTool;
    LineTool.__name__ = "LineTool";
    LineTool.init_LineTool();
},
/* models/tools/gestures/pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const gesture_tool_1 = require(237) /* ./gesture_tool */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons = tslib_1.__importStar(require(242) /* ../../../styles/icons.css */);
    function update_ranges(scales, p0, p1) {
        const r = new Map();
        for (const [name, scale] of scales) {
            const [start, end] = scale.r_invert(p0, p1);
            r.set(name, { start, end });
        }
        return r;
    }
    exports.update_ranges = update_ranges;
    class PanToolView extends gesture_tool_1.GestureToolView {
        _pan_start(ev) {
            var _a;
            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;
            }
            (_a = this.model.document) === null || _a === void 0 ? void 0 : _a.interactive_start(this.plot_model);
        }
        _pan(ev) {
            var _a;
            this._update(ev.deltaX, ev.deltaY);
            (_a = this.model.document) === null || _a === void 0 ? void 0 : _a.interactive_start(this.plot_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 });
        }
        _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;
        }
        static init_PanTool() {
            this.prototype.default_view = PanToolView;
            this.define(() => ({
                dimensions: [enums_1.Dimensions, "both", {
                        on_update(value, obj) {
                            switch (value) {
                                case "both":
                                    obj.icon = icons.tool_icon_pan;
                                    break;
                                case "width":
                                    obj.icon = icons.tool_icon_xpan;
                                    break;
                                case "height":
                                    obj.icon = icons.tool_icon_ypan;
                                    break;
                            }
                        },
                    }],
            }));
            this.register_alias("pan", () => new PanTool({ dimensions: 'both' }));
            this.register_alias("xpan", () => new PanTool({ dimensions: 'width' }));
            this.register_alias("ypan", () => new PanTool({ dimensions: 'height' }));
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.PanTool = PanTool;
    PanTool.__name__ = "PanTool";
    PanTool.init_PanTool();
},
/* models/tools/gestures/range_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const box_annotation_1 = require(136) /* ../../annotations/box_annotation */;
    const range1d_1 = require(156) /* ../../ranges/range1d */;
    const logging_1 = require(19) /* ../../../core/logging */;
    const gesture_tool_1 = require(237) /* ./gesture_tool */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    function flip_side(side) {
        switch (side) {
            case 1 /* Left */: return 2 /* Right */;
            case 2 /* Right */: return 1 /* Left */;
            case 4 /* Bottom */: return 5 /* Top */;
            case 5 /* Top */: return 4 /* Bottom */;
            default: return side;
        }
    }
    exports.flip_side = flip_side;
    // TODO (bev) This would be better directly with BoxAnnotation, but hard
    // to test on a view. Move when "View Models" are implemented
    function is_near(pos, value, scale, tolerance) {
        if (value == null)
            return false;
        const svalue = scale.compute(value);
        return Math.abs(pos - svalue) < tolerance;
    }
    exports.is_near = is_near;
    // TODO (bev) This would be better directly with BoxAnnotation, but hard
    // to test on a view. Move when "View Models" are implemented
    function is_inside(sx, sy, xscale, yscale, overlay) {
        let result = true;
        if (overlay.left != null && overlay.right != null) {
            const x = xscale.invert(sx);
            if (x < overlay.left || x > overlay.right)
                result = false;
        }
        if (overlay.bottom != null && overlay.top != null) {
            const y = yscale.invert(sy);
            if (y < overlay.bottom || y > overlay.top)
                result = false;
        }
        return result;
    }
    exports.is_inside = is_inside;
    function sides_inside(start, end, range) {
        let result = 0;
        if (start >= range.start && start <= range.end)
            result += 1;
        if (end >= range.start && end <= range.end)
            result += 1;
        return result;
    }
    exports.sides_inside = sides_inside;
    function compute_value(value, scale, sdelta, range) {
        const svalue = scale.compute(value);
        const new_value = scale.invert(svalue + sdelta);
        if (new_value >= range.start && new_value <= range.end)
            return new_value;
        return value;
    }
    exports.compute_value = compute_value;
    function update_range_end_side(end, range, side) {
        if (end > range.start) {
            range.end = end;
            return side;
        }
        else {
            range.end = range.start;
            range.start = end;
            return flip_side(side);
        }
    }
    exports.update_range_end_side = update_range_end_side;
    function update_range_start_side(start, range, side) {
        if (start < range.end) {
            range.start = start;
            return side;
        }
        else {
            range.start = range.end;
            range.end = start;
            return flip_side(side);
        }
    }
    exports.update_range_start_side = update_range_start_side;
    function update_range(range, scale, delta, plot_range) {
        const [sstart, send] = scale.r_compute(range.start, range.end);
        const [start, end] = scale.r_invert(sstart + delta, send + delta);
        const initial_sides_inside = sides_inside(range.start, range.end, plot_range);
        const final_sides_inside = sides_inside(start, end, plot_range);
        // Allow the update as long as the number of sides in-bounds does not decrease
        if (final_sides_inside >= initial_sides_inside) {
            range.start = start;
            range.end = end;
        }
    }
    exports.update_range = update_range;
    class RangeToolView extends gesture_tool_1.GestureToolView {
        initialize() {
            super.initialize();
            this.side = 0 /* None */;
            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());
        }
        _pan_start(ev) {
            this.last_dx = 0;
            this.last_dy = 0;
            const xr = this.model.x_range;
            const yr = this.model.y_range;
            const { frame } = this.plot_view;
            const xscale = frame.x_scale;
            const yscale = frame.y_scale;
            const overlay = this.model.overlay;
            const { left, right, top, bottom } = overlay;
            const tolerance = this.model.overlay.line_width + box_annotation_1.EDGE_TOLERANCE;
            if (xr != null && this.model.x_interaction) {
                if (is_near(ev.sx, left, xscale, tolerance))
                    this.side = 1 /* Left */;
                else if (is_near(ev.sx, right, xscale, tolerance))
                    this.side = 2 /* Right */;
                else if (is_inside(ev.sx, ev.sy, xscale, yscale, overlay)) {
                    this.side = 3 /* LeftRight */;
                }
            }
            if (yr != null && this.model.y_interaction) {
                if (this.side == 0 /* None */ && is_near(ev.sy, bottom, yscale, tolerance))
                    this.side = 4 /* Bottom */;
                if (this.side == 0 /* None */ && is_near(ev.sy, top, yscale, tolerance))
                    this.side = 5 /* Top */;
                else if (is_inside(ev.sx, ev.sy, xscale, yscale, this.model.overlay)) {
                    if (this.side == 3 /* LeftRight */)
                        this.side = 7 /* LeftRightBottomTop */;
                    else
                        this.side = 6 /* BottomTop */;
                }
            }
        }
        _pan(ev) {
            const frame = this.plot_view.frame;
            const new_dx = ev.deltaX - this.last_dx;
            const new_dy = ev.deltaY - this.last_dy;
            const xr = this.model.x_range;
            const yr = this.model.y_range;
            const xscale = frame.x_scale;
            const yscale = frame.y_scale;
            if (xr != null) {
                if (this.side == 3 /* LeftRight */ || this.side == 7 /* LeftRightBottomTop */)
                    update_range(xr, xscale, new_dx, frame.x_range);
                else if (this.side == 1 /* Left */) {
                    const start = compute_value(xr.start, xscale, new_dx, frame.x_range);
                    this.side = update_range_start_side(start, xr, this.side);
                }
                else if (this.side == 2 /* Right */) {
                    const end = compute_value(xr.end, xscale, new_dx, frame.x_range);
                    this.side = update_range_end_side(end, xr, this.side);
                }
            }
            if (yr != null) {
                if (this.side == 6 /* BottomTop */ || this.side == 7 /* LeftRightBottomTop */)
                    update_range(yr, yscale, new_dy, frame.y_range);
                else if (this.side == 4 /* Bottom */) {
                    const start = compute_value(yr.start, yscale, new_dy, frame.y_range);
                    this.side = update_range_start_side(start, yr, this.side);
                }
                else if (this.side == 5 /* Top */) {
                    const end = compute_value(yr.end, yscale, new_dy, frame.y_range);
                    this.side = update_range_end_side(end, yr, this.side);
                }
            }
            this.last_dx = ev.deltaX;
            this.last_dy = ev.deltaY;
        }
        _pan_end(_ev) {
            this.side = 0 /* None */;
        }
    }
    exports.RangeToolView = RangeToolView;
    RangeToolView.__name__ = "RangeToolView";
    const DEFAULT_RANGE_OVERLAY = () => {
        return new box_annotation_1.BoxAnnotation({
            level: "overlay",
            fill_color: "lightgrey",
            fill_alpha: 0.5,
            line_color: "black",
            line_alpha: 1.0,
            line_width: 0.5,
            line_dash: [2, 2],
        });
    };
    class RangeTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Range Tool";
            this.icon = icons_css_1.tool_icon_range;
            this.event_type = "pan";
            this.default_order = 1;
        }
        static init_RangeTool() {
            this.prototype.default_view = RangeToolView;
            this.define(({ Boolean, Ref, Nullable }) => ({
                x_range: [Nullable(Ref(range1d_1.Range1d)), null],
                x_interaction: [Boolean, true],
                y_range: [Nullable(Ref(range1d_1.Range1d)), null],
                y_interaction: [Boolean, true],
                overlay: [Ref(box_annotation_1.BoxAnnotation), DEFAULT_RANGE_OVERLAY],
            }));
        }
        initialize() {
            super.initialize();
            this.overlay.in_cursor = "grab";
            this.overlay.ew_cursor = this.x_range != null && this.x_interaction ? "ew-resize" : null;
            this.overlay.ns_cursor = this.y_range != null && this.y_interaction ? "ns-resize" : null;
        }
        update_overlay_from_ranges() {
            if (this.x_range == null && this.y_range == null) {
                this.overlay.left = null;
                this.overlay.right = null;
                this.overlay.bottom = null;
                this.overlay.top = null;
                logging_1.logger.warn('RangeTool not configured with any Ranges.');
            }
            if (this.x_range == null) {
                this.overlay.left = null;
                this.overlay.right = null;
            }
            else {
                this.overlay.left = this.x_range.start;
                this.overlay.right = this.x_range.end;
            }
            if (this.y_range == null) {
                this.overlay.bottom = null;
                this.overlay.top = null;
            }
            else {
                this.overlay.bottom = this.y_range.start;
                this.overlay.top = this.y_range.end;
            }
        }
    }
    exports.RangeTool = RangeTool;
    RangeTool.__name__ = "RangeTool";
    RangeTool.init_RangeTool();
},
/* models/tools/gestures/tap_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const select_tool_1 = require(378) /* ./select_tool */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons_css_1 = require(242) /* ../../../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 { sx, sy } = ev;
            const geometry = { type: "point", sx, sy };
            this._select(geometry, true, this._select_mode(ev));
        }
        _select(geometry, final, mode) {
            const { callback } = this.model;
            if (this.model.behavior == "select") {
                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 && callback != null) {
                        const x = r_views[0].coordinates.x_scale.invert(geometry.sx);
                        const y = r_views[0].coordinates.y_scale.invert(geometry.sy);
                        const data = { geometries: Object.assign(Object.assign({}, geometry), { x, y }), source: sm.source };
                        callback.execute(this.model, data);
                    }
                }
                this._emit_selection_event(geometry);
                this.plot_view.state.push("tap", { selection: this.plot_view.get_selection() });
            }
            else {
                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 && 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: sm.source };
                        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.icon = icons_css_1.tool_icon_tap_select;
            this.event_type = "tap";
            this.default_order = 10;
        }
        static init_TapTool() {
            this.prototype.default_view = TapToolView;
            this.define(({ Any, Enum, Nullable }) => ({
                behavior: [enums_1.TapBehavior, "select"],
                gesture: [Enum("tap", "doubletap"), "tap"],
                callback: [Nullable(Any /*TODO*/)],
            }));
            this.register_alias("click", () => new TapTool({ behavior: "inspect" }));
            this.register_alias("tap", () => new TapTool());
            this.register_alias("doubletap", () => new TapTool({ gesture: "doubletap" }));
        }
    }
    exports.TapTool = TapTool;
    TapTool.__name__ = "TapTool";
    TapTool.init_TapTool();
},
/* models/tools/gestures/wheel_pan_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const gesture_tool_1 = require(237) /* ./gesture_tool */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    const pan_tool_1 = require(384) /* ./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 _a;
            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 = pan_tool_1.update_ranges(x_scales, sx0, sx1);
            const yrs = 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 });
            (_a = this.model.document) === null || _a === void 0 ? void 0 : _a.interactive_start(this.plot_model);
        }
    }
    exports.WheelPanToolView = WheelPanToolView;
    WheelPanToolView.__name__ = "WheelPanToolView";
    class WheelPanTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Wheel Pan";
            this.icon = icons_css_1.tool_icon_wheel_pan;
            this.event_type = "scroll";
            this.default_order = 12;
        }
        static init_WheelPanTool() {
            this.prototype.default_view = WheelPanToolView;
            this.define(() => ({
                dimension: [enums_1.Dimension, "width"],
            }));
            this.internal(({ Number }) => ({
                speed: [Number, 1 / 1000],
            }));
            this.register_alias("xwheel_pan", () => new WheelPanTool({ dimension: "width" }));
            this.register_alias("ywheel_pan", () => new WheelPanTool({ dimension: "height" }));
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimension);
        }
    }
    exports.WheelPanTool = WheelPanTool;
    WheelPanTool.__name__ = "WheelPanTool";
    WheelPanTool.init_WheelPanTool();
},
/* models/tools/gestures/wheel_zoom_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const gesture_tool_1 = require(237) /* ./gesture_tool */;
    const zoom_1 = require(368) /* ../../../core/util/zoom */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const platform_1 = require(27) /* ../../../core/util/platform */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class WheelZoomToolView extends gesture_tool_1.GestureToolView {
        _pinch(ev) {
            // TODO (bev) this can probably be done much better
            const { sx, sy, scale, ctrlKey, shiftKey } = ev;
            let delta;
            if (scale >= 1)
                delta = (scale - 1) * 20.0;
            else
                delta = -20.0 / scale;
            this._scroll({ type: "wheel", sx, sy, delta, ctrlKey, shiftKey });
        }
        _scroll(ev) {
            var _a;
            const { frame } = this.plot_view;
            const hr = frame.bbox.h_range;
            const vr = frame.bbox.v_range;
            const { sx, sy } = ev;
            const dims = this.model.dimensions;
            // restrict to axis configured in tool's dimensions property and if
            // zoom origin is inside of frame range/domain
            const h_axis = (dims == 'width' || dims == 'both') && hr.start < sx && sx < hr.end;
            const v_axis = (dims == 'height' || dims == 'both') && vr.start < sy && sy < vr.end;
            if ((!h_axis || !v_axis) && !this.model.zoom_on_axis) {
                return;
            }
            const factor = this.model.speed * ev.delta;
            const zoom_info = zoom_1.scale_range(frame, factor, h_axis, v_axis, { x: sx, y: sy });
            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 });
            (_a = this.model.document) === null || _a === void 0 ? void 0 : _a.interactive_start(this.plot_model);
        }
    }
    exports.WheelZoomToolView = WheelZoomToolView;
    WheelZoomToolView.__name__ = "WheelZoomToolView";
    class WheelZoomTool extends gesture_tool_1.GestureTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Wheel Zoom";
            this.icon = icons_css_1.tool_icon_wheel_zoom;
            this.event_type = platform_1.is_mobile ? "pinch" : "scroll";
            this.default_order = 10;
        }
        static init_WheelZoomTool() {
            this.prototype.default_view = WheelZoomToolView;
            this.define(({ Boolean, Number }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                maintain_focus: [Boolean, true],
                zoom_on_axis: [Boolean, true],
                speed: [Number, 1 / 600],
            }));
            this.register_alias("wheel_zoom", () => new WheelZoomTool({ dimensions: 'both' }));
            this.register_alias("xwheel_zoom", () => new WheelZoomTool({ dimensions: 'width' }));
            this.register_alias("ywheel_zoom", () => new WheelZoomTool({ dimensions: 'height' }));
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
    }
    exports.WheelZoomTool = WheelZoomTool;
    WheelZoomTool.__name__ = "WheelZoomTool";
    WheelZoomTool.init_WheelZoomTool();
},
/* models/tools/inspectors/crosshair_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const inspect_tool_1 = require(247) /* ./inspect_tool */;
    const span_1 = require(233) /* ../../annotations/span */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const object_1 = require(13) /* ../../../core/util/object */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    class CrosshairToolView extends inspect_tool_1.InspectToolView {
        _move(ev) {
            if (!this.model.active)
                return;
            const { sx, sy } = ev;
            if (!this.plot_view.frame.bbox.contains(sx, sy))
                this._update_spans(null, null);
            else
                this._update_spans(sx, sy);
        }
        _move_exit(_e) {
            this._update_spans(null, null);
        }
        _update_spans(x, y) {
            const dims = this.model.dimensions;
            if (dims == "width" || dims == "both")
                this.model.spans.width.location = y;
            if (dims == "height" || dims == "both")
                this.model.spans.height.location = x;
        }
    }
    exports.CrosshairToolView = CrosshairToolView;
    CrosshairToolView.__name__ = "CrosshairToolView";
    class CrosshairTool extends inspect_tool_1.InspectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Crosshair";
            this.icon = icons_css_1.tool_icon_crosshair;
        }
        static init_CrosshairTool() {
            this.prototype.default_view = CrosshairToolView;
            this.define(({ Alpha, Number, Color }) => ({
                dimensions: [enums_1.Dimensions, "both"],
                line_color: [Color, "black"],
                line_width: [Number, 1],
                line_alpha: [Alpha, 1],
            }));
            function span(self, dimension) {
                return new span_1.Span({
                    for_hover: true,
                    dimension,
                    location_units: "screen",
                    level: "overlay",
                    line_color: self.line_color,
                    line_width: self.line_width,
                    line_alpha: self.line_alpha,
                });
            }
            this.internal(({ Struct, Ref }) => ({
                spans: [
                    Struct({ width: Ref(span_1.Span), height: Ref(span_1.Span) }),
                    (self) => ({
                        width: span(self, "width"),
                        height: span(self, "height"),
                    }),
                ],
            }));
            this.register_alias("crosshair", () => new CrosshairTool());
        }
        get tooltip() {
            return this._get_dim_tooltip(this.dimensions);
        }
        get synthetic_renderers() {
            return object_1.values(this.spans);
        }
    }
    exports.CrosshairTool = CrosshairTool;
    CrosshairTool.__name__ = "CrosshairTool";
    CrosshairTool.init_CrosshairTool();
},
/* models/tools/inspectors/customjs_hover.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(53) /* ../../../model */;
    const object_1 = require(13) /* ../../../core/util/object */;
    const string_1 = require(34) /* ../../../core/util/string */;
    class CustomJSHover extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_CustomJSHover() {
            this.define(({ Unknown, String, Dict }) => ({
                args: [Dict(Unknown), {}],
                code: [String, ""],
            }));
        }
        get values() {
            return 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(...object_1.keys(this.args), valname, formatname, varsname, 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;
    CustomJSHover.__name__ = "CustomJSHover";
    CustomJSHover.init_CustomJSHover();
},
/* models/tools/inspectors/hover_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const inspect_tool_1 = require(247) /* ./inspect_tool */;
    const customjs_hover_1 = require(390) /* ./customjs_hover */;
    const tooltip_1 = require(254) /* ../../annotations/tooltip */;
    const glyph_renderer_1 = require(61) /* ../../renderers/glyph_renderer */;
    const graph_renderer_1 = require(123) /* ../../renderers/graph_renderer */;
    const data_renderer_1 = require(62) /* ../../renderers/data_renderer */;
    const line_1 = require(63) /* ../../glyphs/line */;
    const multi_line_1 = require(127) /* ../../glyphs/multi_line */;
    const hittest = tslib_1.__importStar(require(107) /* ../../../core/hittest */);
    const templating_1 = require(182) /* ../../../core/util/templating */;
    const dom_1 = require(43) /* ../../../core/dom */;
    const color_1 = require(22) /* ../../../core/util/color */;
    const object_1 = require(13) /* ../../../core/util/object */;
    const iterator_1 = require(245) /* ../../../core/util/iterator */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const build_views_1 = require(122) /* ../../../core/build_views */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const icons_css_1 = require(242) /* ../../../styles/icons.css */;
    const signaling_1 = require(15) /* ../../../core/signaling */;
    const util_1 = require(161) /* ../../util */;
    const styles = tslib_1.__importStar(require(255) /* ../../../styles/tooltips.css */);
    function _nearest_line_hit(i, geometry, sx, sy, dx, dy) {
        const d1 = { x: dx[i], y: dy[i] };
        const d2 = { x: dx[i + 1], y: dy[i + 1] };
        let dist1;
        let dist2;
        if (geometry.type == "span") {
            if (geometry.direction == "h") {
                dist1 = Math.abs(d1.x - sx);
                dist2 = Math.abs(d2.x - sx);
            }
            else {
                dist1 = Math.abs(d1.y - sy);
                dist2 = Math.abs(d2.y - sy);
            }
        }
        else {
            const s = { x: sx, y: sy };
            dist1 = hittest.dist_2_pts(d1, s);
            dist2 = hittest.dist_2_pts(d2, s);
        }
        if (dist1 < dist2)
            return [[d1.x, d1.y], i];
        else
            return [[d2.x, d2.y], i + 1];
    }
    exports._nearest_line_hit = _nearest_line_hit;
    function _line_hit(xs, ys, ind) {
        return [[xs[ind], ys[ind]], ind];
    }
    exports._line_hit = _line_hit;
    class HoverToolView extends inspect_tool_1.InspectToolView {
        initialize() {
            super.initialize();
            this._ttmodels = new Map();
            this._ttviews = new Map();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._update_ttmodels();
        }
        remove() {
            build_views_1.remove_views(this._ttviews);
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            const plot_renderers = this.plot_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());
        }
        async _update_ttmodels() {
            const { _ttmodels, computed_renderers } = this;
            _ttmodels.clear();
            const { tooltips } = this.model;
            if (tooltips != null) {
                for (const r of this.computed_renderers) {
                    const tooltip = new tooltip_1.Tooltip({
                        custom: types_1.isString(tooltips) || types_1.isFunction(tooltips),
                        attachment: this.model.attachment,
                        show_arrow: this.model.show_arrow,
                    });
                    if (r instanceof glyph_renderer_1.GlyphRenderer) {
                        _ttmodels.set(r, tooltip);
                    }
                    else if (r instanceof graph_renderer_1.GraphRenderer) {
                        _ttmodels.set(r.node_renderer, tooltip);
                        _ttmodels.set(r.edge_renderer, tooltip);
                    }
                }
            }
            const views = await build_views_1.build_views(this._ttviews, [..._ttmodels.values()], { parent: this.plot_view });
            for (const ttview of views) {
                ttview.render();
            }
            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, names } = this.model;
            const all_renderers = this.plot_model.data_renderers;
            return util_1.compute_renderers(renderers, all_renderers, names);
        }
        get ttmodels() {
            return this._ttmodels;
        }
        _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._inspect(sx, sy);
        }
        _move_exit() {
            this._clear();
        }
        _inspect(sx, sy) {
            let geometry;
            if (this.model.mode == 'mouse')
                geometry = { type: 'point', sx, sy };
            else {
                const direction = this.model.mode == 'vline' ? 'h' : 'v';
                geometry = { 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 }]) {
            var _a, _b;
            if (!this.model.active)
                return;
            if (!(geometry.type == "point" || geometry.type == "span"))
                return;
            if (!(renderer instanceof glyph_renderer_1.GlyphRenderer)) // || renderer instanceof GraphRenderer))
                return;
            if (this.model.muted_policy == 'ignore' && renderer.muted)
                return;
            const tooltip = this.ttmodels.get(renderer);
            if (tooltip == null)
                return;
            const selection_manager = renderer.get_selection_manager();
            let indices = selection_manager.inspectors.get(renderer);
            indices = renderer.view.convert_selection_to_subset(indices);
            if (indices.is_empty()) {
                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 line_1.LineView) {
                for (const i of indices.line_indices) {
                    let data_x = glyph._x[i + 1];
                    let data_y = glyph._y[i + 1];
                    let ii = i;
                    let rx;
                    let ry;
                    switch (this.model.line_policy) {
                        case "interp": { // and renderer.get_interpolation_hit?
                            [data_x, data_y] = glyph.get_interpolation_hit(i, geometry);
                            rx = xscale.compute(data_x);
                            ry = yscale.compute(data_y);
                            break;
                        }
                        case "prev": {
                            [[rx, ry], ii] = _line_hit(glyph.sx, glyph.sy, i);
                            break;
                        }
                        case "next": {
                            [[rx, ry], ii] = _line_hit(glyph.sx, glyph.sy, i + 1);
                            break;
                        }
                        case "nearest": {
                            [[rx, ry], ii] = _nearest_line_hit(i, geometry, sx, sy, glyph.sx, glyph.sy);
                            data_x = glyph._x[ii];
                            data_y = glyph._y[ii];
                            break;
                        }
                        default: {
                            [rx, ry] = [sx, sy];
                        }
                    }
                    const vars = {
                        index: ii,
                        x, y, sx, sy, data_x, data_y, rx, ry,
                        indices: indices.line_indices,
                        name: renderer.name,
                    };
                    tooltips.push([rx, ry, this._render_tooltips(ds, ii, vars)]);
                }
            }
            for (const struct of indices.image_indices) {
                const vars = {
                    index: struct.index,
                    x, y, sx, sy,
                    name: renderer.name,
                };
                const rendered = this._render_tooltips(ds, struct, vars);
                tooltips.push([sx, sy, rendered]);
            }
            for (const i of indices.indices) {
                // multiglyphs set additional indices, e.g. multiline_indices for different tooltips
                if (glyph instanceof multi_line_1.MultiLineView && !object_1.isEmpty(indices.multiline_indices)) {
                    for (const j of indices.multiline_indices[i.toString()]) { // TODO: indices.multiline_indices.get(i)
                        let data_x = glyph._xs.get(i)[j];
                        let data_y = glyph._ys.get(i)[j];
                        let jj = j;
                        let rx;
                        let ry;
                        switch (this.model.line_policy) {
                            case "interp": { // and renderer.get_interpolation_hit?
                                [data_x, data_y] = glyph.get_interpolation_hit(i, j, geometry);
                                rx = xscale.compute(data_x);
                                ry = yscale.compute(data_y);
                                break;
                            }
                            case "prev": {
                                [[rx, ry], jj] = _line_hit(glyph.sxs.get(i), glyph.sys.get(i), j);
                                break;
                            }
                            case "next": {
                                [[rx, ry], jj] = _line_hit(glyph.sxs.get(i), glyph.sys.get(i), j + 1);
                                break;
                            }
                            case "nearest": {
                                [[rx, ry], jj] = _nearest_line_hit(j, geometry, sx, sy, glyph.sxs.get(i), glyph.sys.get(i));
                                data_x = glyph._xs.get(i)[jj];
                                data_y = glyph._ys.get(i)[jj];
                                break;
                            }
                            default:
                                throw new Error("shouldn't have happened");
                        }
                        let index;
                        if (renderer instanceof glyph_renderer_1.GlyphRenderer)
                            index = renderer.view.convert_indices_from_subset([i])[0];
                        else
                            index = i;
                        const vars = {
                            index, x, y, sx, sy, data_x, data_y,
                            segment_index: jj,
                            indices: indices.multiline_indices,
                            name: renderer.name,
                        };
                        tooltips.push([rx, ry, this._render_tooltips(ds, index, vars)]);
                    }
                }
                else {
                    // handle non-multiglyphs
                    const data_x = (_a = glyph._x) === null || _a === void 0 ? void 0 : _a[i];
                    const data_y = (_b = glyph._y) === null || _b === void 0 ? void 0 : _b[i];
                    let rx;
                    let ry;
                    if (this.model.point_policy == 'snap_to_data') { // and renderer.glyph.sx? and renderer.glyph.sy?
                        // Pass in our screen position so we can determine which patch we're
                        // over if there are discontinuous patches.
                        let pt = glyph.get_anchor_point(this.model.anchor, i, [sx, sy]);
                        if (pt == null) {
                            pt = glyph.get_anchor_point("center", i, [sx, sy]);
                            if (pt == null)
                                continue; // TODO?
                        }
                        rx = pt.x;
                        ry = pt.y;
                    }
                    else
                        [rx, ry] = [sx, sy];
                    let index;
                    if (renderer instanceof glyph_renderer_1.GlyphRenderer)
                        index = renderer.view.convert_indices_from_subset([i])[0];
                    else
                        index = i;
                    const vars = {
                        index, x, y, sx, sy, data_x, data_y,
                        indices: indices.indices,
                        name: renderer.name,
                    };
                    tooltips.push([rx, ry, this._render_tooltips(ds, index, vars)]);
                }
            }
            if (tooltips.length == 0)
                tooltip.clear();
            else {
                const { content } = tooltip;
                dom_1.empty(tooltip.content);
                for (const [, , node] of tooltips) {
                    if (node != null)
                        content.appendChild(node);
                }
                const [x, y] = tooltips[tooltips.length - 1];
                tooltip.setv({ position: [x, y] }, { check_eq: false }); // XXX: force update
            }
        }
        _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 = dom_1.div({ style: { display: "table", borderSpacing: "2px" } });
            for (const [label] of tooltips) {
                const row = dom_1.div({ style: { display: "table-row" } });
                rows.appendChild(row);
                const label_cell = dom_1.div({ style: { display: "table-cell" }, class: styles.tooltip_row_label }, label.length != 0 ? `${label}: ` : "");
                row.appendChild(label_cell);
                const value_el = dom_1.span();
                value_el.dataset.value = "";
                const swatch_el = dom_1.span({ class: styles.tooltip_color_block }, " ");
                swatch_el.dataset.swatch = "";
                dom_1.undisplay(swatch_el);
                const value_cell = 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, i, vars) {
            const el = template.cloneNode(true);
            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 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) {
                    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 = types_1.isNumber(i) ? column[i] : null;
                            if (color != null) {
                                swatch_els[j].style.backgroundColor = color_1.color2css(color);
                                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 = types_1.isNumber(i) ? column[i] : null;
                        if (color == null) {
                            value_els[j].textContent = "(null)";
                            continue;
                        }
                        value_els[j].textContent = hex ? color_1.color2hex(color) : color_1.color2css(color); // TODO: color2pretty
                        if (swatch) {
                            swatch_els[j].style.backgroundColor = color_1.color2css(color);
                            dom_1.display(swatch_els[j]);
                        }
                    }
                }
                else {
                    const content = templating_1.replace_placeholders(value.replace("$~", "$data_"), ds, i, this.model.formatters, vars);
                    if (types_1.isString(content)) {
                        value_els[j].textContent = content;
                    }
                    else {
                        for (const el of content) {
                            value_els[j].appendChild(el);
                        }
                    }
                }
            }
            return el;
        }
        _render_tooltips(ds, i, vars) {
            var _a;
            const { tooltips } = this.model;
            if (types_1.isString(tooltips)) {
                const content = templating_1.replace_placeholders({ html: tooltips }, ds, i, this.model.formatters, vars);
                return dom_1.div({}, content);
            }
            else if (types_1.isFunction(tooltips)) {
                return tooltips(ds, vars);
            }
            else if (tooltips != null) {
                const template = (_a = this._template_el) !== null && _a !== void 0 ? _a : (this._template_el = this._create_template(tooltips));
                return this._render_template(template, tooltips, ds, i, vars);
            }
            else
                return null;
        }
    }
    exports.HoverToolView = HoverToolView;
    HoverToolView.__name__ = "HoverToolView";
    class HoverTool extends inspect_tool_1.InspectTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Hover";
            this.icon = icons_css_1.tool_icon_hover;
        }
        static init_HoverTool() {
            this.prototype.default_view = HoverToolView;
            this.define(({ Any, Boolean, String, Array, Tuple, Dict, Or, Ref, Function, Auto, Nullable }) => ({
                tooltips: [Nullable(Or(String, Array(Tuple(String, String)), Function())), [
                        ["index", "$index"],
                        ["data (x, y)", "($x, $y)"],
                        ["screen (x, y)", "($sx, $sy)"],
                    ]],
                formatters: [Dict(Or(Ref(customjs_hover_1.CustomJSHover), templating_1.FormatterType)), {}],
                renderers: [Or(Array(Ref(data_renderer_1.DataRenderer)), Auto), "auto"],
                names: [Array(String), []],
                mode: [enums_1.HoverMode, "mouse"],
                muted_policy: [enums_1.MutedPolicy, "show"],
                point_policy: [enums_1.PointPolicy, "snap_to_data"],
                line_policy: [enums_1.LinePolicy, "nearest"],
                show_arrow: [Boolean, true],
                anchor: [enums_1.Anchor, "center"],
                attachment: [enums_1.TooltipAttachment, "horizontal"],
                callback: [Nullable(Any /*TODO*/)],
            }));
            this.register_alias("hover", () => new HoverTool());
        }
    }
    exports.HoverTool = HoverTool;
    HoverTool.__name__ = "HoverTool";
    HoverTool.init_HoverTool();
},
/* models/tools/tool_proxy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const signaling_1 = require(15) /* ../../core/signaling */;
    const model_1 = require(53) /* ../../model */;
    const button_tool_1 = require(238) /* ./button_tool */;
    const inspect_tool_1 = require(247) /* ./inspectors/inspect_tool */;
    const iterator_1 = require(245) /* ../../core/util/iterator */;
    class ToolProxy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        static init_ToolProxy() {
            this.define(({ Boolean, Array, Ref }) => ({
                tools: [Array(Ref(button_tool_1.ButtonTool)), []],
                active: [Boolean, false],
                disabled: [Boolean, false],
            }));
        }
        // Operates all the tools given only one button
        get button_view() {
            return this.tools[0].button_view;
        }
        get event_type() {
            return this.tools[0].event_type;
        }
        get tooltip() {
            return this.tools[0].tooltip;
        }
        get tool_name() {
            return this.tools[0].tool_name;
        }
        get icon() {
            return this.tools[0].computed_icon;
        }
        get computed_icon() {
            return this.icon;
        }
        get toggleable() {
            const tool = this.tools[0];
            return tool instanceof inspect_tool_1.InspectTool && 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 iterator_1.enumerate(menu)) {
                if (item == null)
                    items.push(null);
                else {
                    const handler = () => {
                        var _a, _b;
                        for (const tool of this.tools) {
                            (_b = (_a = tool.menu) === null || _a === void 0 ? void 0 : _a[i]) === null || _b === void 0 ? void 0 : _b.handler();
                        }
                    };
                    items.push(Object.assign(Object.assign({}, item), { handler }));
                }
            }
            return items;
        }
    }
    exports.ToolProxy = ToolProxy;
    ToolProxy.__name__ = "ToolProxy";
    ToolProxy.init_ToolProxy();
},
/* models/tools/toolbar_box.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(9) /* ../../core/util/array */;
    const object_1 = require(13) /* ../../core/util/object */;
    const toolbar_base_1 = require(248) /* ./toolbar_base */;
    const toolbar_1 = require(235) /* ./toolbar */;
    const tool_proxy_1 = require(392) /* ./tool_proxy */;
    const layout_dom_1 = require(319) /* ../layouts/layout_dom */;
    const layout_1 = require(221) /* ../../core/layout */;
    class ProxyToolbar extends toolbar_base_1.ToolbarBase {
        constructor(attrs) {
            super(attrs);
        }
        static init_ProxyToolbar() {
            this.define(({ Array, Ref }) => ({
                toolbars: [Array(Ref(toolbar_1.Toolbar)), []],
            }));
        }
        initialize() {
            super.initialize();
            this._merge_tools();
        }
        _merge_tools() {
            // Go through all the tools on the toolbar and replace them with
            // a proxy e.g. PanTool, BoxSelectTool, etc.
            this._proxied_tools = [];
            const inspectors = {};
            const actions = {};
            const gestures = {};
            const new_help_tools = [];
            const new_help_urls = [];
            for (const helptool of this.help) {
                if (!array_1.includes(new_help_urls, helptool.redirect)) {
                    new_help_tools.push(helptool);
                    new_help_urls.push(helptool.redirect);
                }
            }
            this._proxied_tools.push(...new_help_tools);
            this.help = new_help_tools;
            for (const [event_type, gesture] of object_1.entries(this.gestures)) {
                if (!(event_type in gestures)) {
                    gestures[event_type] = {};
                }
                for (const tool of gesture.tools) {
                    if (!(tool.type in gestures[event_type])) {
                        gestures[event_type][tool.type] = [];
                    }
                    gestures[event_type][tool.type].push(tool);
                }
            }
            for (const tool of this.inspectors) {
                if (!(tool.type in inspectors)) {
                    inspectors[tool.type] = [];
                }
                inspectors[tool.type].push(tool);
            }
            for (const tool of this.actions) {
                if (!(tool.type in actions)) {
                    actions[tool.type] = [];
                }
                actions[tool.type].push(tool);
            }
            // Add a proxy for each of the groups of tools.
            const make_proxy = (tools, active = false) => {
                const proxy = new tool_proxy_1.ToolProxy({ tools, active });
                this._proxied_tools.push(proxy);
                return proxy;
            };
            for (const event_type of object_1.keys(gestures)) {
                const gesture = this.gestures[event_type];
                gesture.tools = [];
                for (const tool_type of object_1.keys(gestures[event_type])) {
                    const tools = gestures[event_type][tool_type];
                    if (tools.length > 0) {
                        if (event_type == 'multi') {
                            for (const tool of tools) {
                                const proxy = make_proxy([tool]);
                                gesture.tools.push(proxy);
                                this.connect(proxy.properties.active.change, () => this._active_change(proxy));
                            }
                        }
                        else {
                            const proxy = make_proxy(tools);
                            gesture.tools.push(proxy);
                            this.connect(proxy.properties.active.change, () => this._active_change(proxy));
                        }
                    }
                }
            }
            this.actions = [];
            for (const [tool_type, tools] of object_1.entries(actions)) {
                if (tool_type == 'CustomAction') {
                    for (const tool of tools)
                        this.actions.push(make_proxy([tool]));
                }
                else if (tools.length > 0) {
                    this.actions.push(make_proxy(tools)); // XXX
                }
            }
            this.inspectors = [];
            for (const tools of object_1.values(inspectors)) {
                if (tools.length > 0)
                    this.inspectors.push(make_proxy(tools, true)); // XXX
            }
            for (const [et, gesture] of object_1.entries(this.gestures)) {
                if (gesture.tools.length == 0)
                    continue;
                gesture.tools = array_1.sort_by(gesture.tools, (tool) => tool.default_order);
                if (!(et == 'pinch' || et == 'scroll' || et == 'multi'))
                    gesture.tools[0].active = true;
            }
        }
    }
    exports.ProxyToolbar = ProxyToolbar;
    ProxyToolbar.__name__ = "ProxyToolbar";
    ProxyToolbar.init_ProxyToolbar();
    class ToolbarBoxView extends layout_dom_1.LayoutDOMView {
        initialize() {
            this.model.toolbar.toolbar_location = this.model.toolbar_location;
            super.initialize();
        }
        get child_models() {
            return [this.model.toolbar]; // XXX
        }
        _update_layout() {
            this.layout = new layout_1.ContentBox(this.child_views[0].el);
            const { toolbar } = this.model;
            if (toolbar.horizontal) {
                this.layout.set_sizing({
                    width_policy: "fit", min_width: 100, height_policy: "fixed",
                });
            }
            else {
                this.layout.set_sizing({
                    width_policy: "fixed", height_policy: "fit", min_height: 100,
                });
            }
        }
    }
    exports.ToolbarBoxView = ToolbarBoxView;
    ToolbarBoxView.__name__ = "ToolbarBoxView";
    class ToolbarBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
        static init_ToolbarBox() {
            this.prototype.default_view = ToolbarBoxView;
            this.define(({ Ref }) => ({
                toolbar: [Ref(toolbar_base_1.ToolbarBase)],
                toolbar_location: [enums_1.Location, "right"],
            }));
        }
    }
    exports.ToolbarBox = ToolbarBox;
    ToolbarBox.__name__ = "ToolbarBox";
    ToolbarBox.init_ToolbarBox();
},
/* document/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const base_1 = require(7) /* ../base */;
    const model_1 = require(53) /* ../model */;
    const kinds = tslib_1.__importStar(require(21) /* ../core/kinds */);
    const types_1 = require(8) /* ../core/util/types */;
    const object_1 = require(13) /* ../core/util/object */;
    function resolve_defs(defs) {
        var _b, _c, _d;
        var _a;
        function qualified(ref) {
            return ref.module != null ? `${ref.module}.${ref.name}` : ref.name;
        }
        function kind_of(ref) {
            if (types_1.isString(ref)) {
                switch (ref) {
                    case "Any": return kinds.Any;
                    case "Unknown": return kinds.Unknown;
                    case "Boolean": return kinds.Boolean;
                    case "Number": return kinds.Number;
                    case "Int": return kinds.Int;
                    case "String": return kinds.String;
                    case "Null": return kinds.Null;
                }
            }
            else {
                switch (ref[0]) {
                    case "Nullable": {
                        const [, subref] = ref;
                        return kinds.Nullable(kind_of(subref));
                    }
                    case "Or": {
                        const [, ...subrefs] = ref;
                        return kinds.Or(...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(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 = base_1.Models.get(qualified(modelref));
                        if (model != null)
                            return kinds.Ref(model);
                        else
                            throw new Error(`${qualified(modelref)} wasn't defined before referencing it`);
                    }
                    case "AnyRef": {
                        return kinds.AnyRef();
                    }
                }
            }
        }
        for (const def of defs) {
            const base = (() => {
                if (def.extends == null)
                    return model_1.Model;
                else {
                    const base = base_1.Models.get(qualified(def.extends));
                    if (base != null)
                        return base;
                    else
                        throw new Error(`base model ${qualified(def.extends)} of ${qualified(def)} is not defined`);
                }
            })();
            const model = (_a = class extends base {
            },
                _a.__name__ = def.name,
                _a.__module__ = def.module,
                _a);
            for (const prop of (_b = def.properties) !== null && _b !== void 0 ? _b : []) {
                const kind = kind_of((_c = prop.kind) !== null && _c !== void 0 ? _c : "Unknown");
                model.define({ [prop.name]: [kind, prop.default] });
            }
            for (const prop of (_d = def.overrides) !== null && _d !== void 0 ? _d : []) {
                model.override({ [prop.name]: prop.default });
            }
            base_1.Models.register_models([model]);
        }
    }
    exports.resolve_defs = resolve_defs;
},
/* embed/standalone.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const document_1 = require(5) /* ../document */;
    const dom_view_1 = require(240) /* ../core/dom_view */;
    const build_views_1 = require(122) /* ../core/build_views */;
    const dom_1 = require(43) /* ../core/dom */;
    const dom_2 = require(396) /* ./dom */;
    // A map from the root model IDs to their views.
    exports.index = {};
    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 Map();
        async function render_model(model) {
            let root_el;
            const root_models = document.roots();
            const idx = root_models.indexOf(model);
            const root = roots[idx];
            if (root != null)
                root_el = root;
            else if (element.classList.contains(dom_2.BOKEH_ROOT))
                root_el = element;
            else {
                root_el = dom_1.div({ class: dom_2.BOKEH_ROOT });
                element.appendChild(root_el);
            }
            const view = await build_views_1.build_view(model, { parent: null });
            if (view instanceof dom_view_1.DOMView)
                view.renderTo(root_el);
            views.set(model, view);
            exports.index[model.id] = view;
            return view;
        }
        function unrender_model(model) {
            const view = views.get(model);
            if (view != null) {
                view.remove();
                views.delete(model);
                delete exports.index[model.id];
            }
        }
        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.values()];
    }
    exports.add_document_standalone = add_document_standalone;
},
/* embed/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(43) /* ../core/dom */;
    const root_css_1 = require(44) /* ../styles/root.css */;
    // Matches Bokeh CSS class selector. Setting all Bokeh parent element class names
    // with this var prevents user configurations where css styling is unset.
    exports.BOKEH_ROOT = root_css_1.root;
    function _get_element(elementid) {
        let element = document.getElementById(elementid);
        if (element == null)
            throw new Error(`Error rendering Bokeh model: could not find #${elementid} HTML tag`);
        if (!document.body.contains(element))
            throw new Error(`Error rendering Bokeh model: element #${elementid} must be under <body>`);
        // If autoload script, replace script tag with div for embedding.
        if (element.tagName == "SCRIPT") {
            const root_el = dom_1.div({ class: exports.BOKEH_ROOT });
            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/server.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const connection_1 = require(398) /* ../client/connection */;
    const logging_1 = require(19) /* ../core/logging */;
    const standalone_1 = require(395) /* ./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;
    // map { websocket url to map { session id to promise of ClientSession } }
    const _sessions = {};
    function _get_session(websocket_url, token, args_string) {
        const session_id = connection_1.parse_token(token).session_id;
        if (!(websocket_url in _sessions))
            _sessions[websocket_url] = {};
        const subsessions = _sessions[websocket_url];
        if (!(session_id in subsessions))
            subsessions[session_id] = connection_1.pull_session(websocket_url, token, args_string);
        return subsessions[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.substr(1);
        let session;
        try {
            session = await _get_session(websocket_url, token, args_string);
        }
        catch (error) {
            const session_id = connection_1.parse_token(token).session_id;
            logging_1.logger.error(`Failed to load Bokeh session ${session_id}: ${error}`);
            throw error;
        }
        return 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(399) /* ../protocol/message */;
    const receiver_1 = require(400) /* ../protocol/receiver */;
    const session_1 = require(401) /* ./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.url = url;
            this.token = token;
            this.args_string = args_string;
            this._number = _connection_count++;
            this.socket = null;
            this.session = null;
            this.closed_permanently = false;
            this._current_handler = null;
            this._pending_replies = new Map();
            this._pending_messages = [];
            this._receiver = new receiver_1.Receiver();
            this.id = parse_token(token).session_id.split('.')[0];
            logging_1.logger.debug(`Creating websocket ${this._number} to '${this.url}' session '${this.id}'`);
        }
        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 = () => {
                // TODO commented code below until we fix reconnection to repull
                // the document when required. Otherwise, we get a lot of
                // confusing errors that are causing trouble when debugging.
                /*
                if (this.closed_permanently) {
                */
                if (!this.closed_permanently)
                    logging_1.logger.info(`Websocket connection ${this._number} disconnected, will not attempt to reconnect`);
                return;
                /*
                } else {
                  logger.debug(`Attempting to reconnect websocket ${this._number}`)
                  this.connect()
                }
                */
            };
            setTimeout(retry, milliseconds);
        }
        send(message) {
            if (this.socket == null)
                throw new Error(`not connected so cannot send ${message}`);
            message.send(this.socket);
        }
        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) {
            var _a;
            logging_1.logger.debug(this.session ? "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 document = document_1.Document.from_json(doc_json);
                        // Constructing models changes some of their attributes, we deal with that
                        // here. This happens when models set attributes during construction
                        // or initialization.
                        const patch = document_1.Document._compute_patch_since_json(doc_json, document);
                        if (patch.events.length > 0) {
                            logging_1.logger.debug(`Sending ${patch.events.length} changes from model construction back to server`);
                            const patch_message = message_1.Message.create('PATCH-DOC', {}, patch);
                            this.send(patch_message);
                        }
                        this.session = new session_1.ClientSession(this, document, this.id);
                        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) {
                (_a = console.trace) === null || _a === void 0 ? void 0 : _a.call(console, 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) {
                this._pending_replies.delete(reqid);
                pr.resolve(message);
            }
            else if (this.session) {
                this.session.handle(message);
            }
            else if (message.msgtype() != 'PATCH-DOC') {
                // This branch can be executed only before we get the document.
                // When we get the document, all of the patches will already be incorporated.
                // In general, it's not possible to apply patches received before the document,
                // since they may change some models that were removed before serving the document.
                this._pending_messages.push(message);
            }
        }
    }
    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 string_1 = require(34) /* ../core/util/string */;
    class Message {
        constructor(header, metadata, content) {
            this.header = header;
            this.metadata = metadata;
            this.content = content;
            this.buffers = new Map();
        }
        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) {
            const nb = this.header.num_buffers != null ? this.header.num_buffers : 0;
            if (nb <= this.buffers.size)
                throw new Error(`too many buffers received, expecting ${nb}`);
            const { id } = JSON.parse(buf_header);
            this.buffers.set(id, buf_payload);
        }
        // not defined for BokehJS, only *receiving* buffers is supported
        // add_buffer: (buf_header, buf_payload) ->
        // write_buffers: (socket)
        static create(msgtype, metadata, content = {}) {
            const header = Message.create_header(msgtype);
            return new Message(header, metadata, content);
        }
        static create_header(msgtype) {
            return {
                msgid: string_1.uniqueId(),
                msgtype,
            };
        }
        complete() {
            if (this.header != null && this.metadata != null && this.content != null) {
                if (this.header.num_buffers != undefined)
                    return this.buffers.size == this.header.num_buffers;
                else
                    return true;
            }
            else
                return false;
        }
        send(socket) {
            const nb = this.header.num_buffers != null ? this.header.num_buffers : 0;
            if (nb > 0)
                throw new Error("BokehJS only supports receiving buffers, not sending");
            const header_json = JSON.stringify(this.header);
            const metadata_json = JSON.stringify(this.metadata);
            const content_json = JSON.stringify(this.content);
            socket.send(header_json);
            socket.send(metadata_json);
            socket.send(content_json);
        }
        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(399) /* ./message */;
    const types_1 = require(8) /* ../core/util/types */;
    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.slice(0, 3);
            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);
            this._partial.assemble_buffer(this._buf_header, fragment);
            this._check_complete();
        }
        _assume_text(fragment) {
            if (!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 message_1 = require(399) /* ../protocol/message */;
    const logging_1 = require(19) /* ../core/logging */;
    class ClientSession {
        constructor(_connection, document, id) {
            this._connection = _connection;
            this.document = document;
            this.id = id;
            this._document_listener = (event) => {
                this._document_changed(event);
            };
            this.document.on_change(this._document_listener, true);
        }
        handle(message) {
            const msgtype = message.msgtype();
            if (msgtype === 'PATCH-DOC')
                this._handle_patch(message);
            else if (msgtype === 'OK')
                this._handle_ok(message);
            else if (msgtype === 'ERROR')
                this._handle_error(message);
            else
                logging_1.logger.debug(`Doing nothing with message ${message.msgtype()}`);
        }
        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) {
            // Filter out events that were initiated by the ClientSession itself
            if (event.setter_id === this.id) // XXX: not all document events define this
                return;
            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, this.id);
        }
        _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/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(400) /* ../protocol/receiver */;
    const logging_1 = require(19) /* ../core/logging */;
    const dom_1 = require(43) /* ../core/dom */;
    const object_1 = require(13) /* ../core/util/object */;
    const standalone_1 = require(395) /* ./standalone */;
    const dom_2 = require(396) /* ./dom */;
    const root_css_1 = tslib_1.__importDefault(require(44) /* ../styles/root.css */);
    const logo_css_1 = tslib_1.__importDefault(require(253) /* ../styles/logo.css */);
    const notebook_css_1 = tslib_1.__importDefault(require(403) /* ../styles/notebook.css */);
    dom_1.stylesheet.append(root_css_1.default);
    dom_1.stylesheet.append(logo_css_1.default);
    dom_1.stylesheet.append(notebook_css_1.default);
    // This exists to allow the @bokeh/jupyter_bokeh extension to store the
    // notebook kernel so that _init_comms can register the comms target.
    // This has to be available at Bokeh.embed.kernels in JupyterLab.
    exports.kernels = {};
    function _handle_notebook_comms(receiver, comm_msg) {
        if (comm_msg.buffers.length > 0)
            receiver.consume(comm_msg.buffers[0].buffer);
        else
            receiver.consume(comm_msg.content.data);
        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 e_1, _a;
                    var _b;
                    logging_1.logger.info(`Registering Google Colab comms for target ${target}`);
                    const r = new receiver_1.Receiver();
                    try {
                        for (var _c = tslib_1.__asyncValues(comm.messages), _d; _d = await _c.next(), !_d.done;) {
                            const message = _d.value;
                            const content = { data: message.data };
                            const buffers = [];
                            for (const buffer of (_b = message.buffers) !== null && _b !== void 0 ? _b : []) {
                                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 (_d && !_d.done && (_a = _c.return))
                                await _a.call(_c);
                        }
                        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 (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(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 = dom_2._resolve_element(item);
            const roots = dom_2._resolve_root_elements(item);
            standalone_1.add_document_standalone(document, element, roots);
        }
    }
    exports.embed_items_notebook = embed_items_notebook;
},
/* styles/notebook.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.root = "bk-root";
    exports.tooltip = "bk-tooltip";
    exports.default = `.rendered_html .bk-root .bk-tooltip table,.rendered_html .bk-root .bk-tooltip tr,.rendered_html .bk-root .bk-tooltip th,.rendered_html .bk-root .bk-tooltip td{border:none;padding:1px;}`;
},
/* protocol/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(399) /* ./message */, exports);
    tslib_1.__exportStar(require(400) /* ./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 ? error.stack : `${error}`;
            _burst_into_flames(text);
            if (!silent)
                throw error;
            else
                return;
        }
    }
    exports.safely = safely;
},
], 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/array":9,"core/util/math":10,"core/util/assert":11,"core/util/arrayable":12,"core/util/object":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/settings":28,"core/util/ndarray":29,"core/serializer":30,"core/util/serialization":31,"core/util/buffer":32,"core/uniforms":33,"core/util/string":34,"document/events":35,"core/util/pretty":36,"core/util/cloneable":37,"models/index":38,"models/annotations/index":39,"models/annotations/annotation":40,"models/renderers/renderer":41,"core/view":42,"core/dom":43,"styles/root.css":44,"core/visuals/index":45,"core/visuals/line":46,"core/visuals/visual":47,"core/property_mixins":48,"core/visuals/fill":49,"core/visuals/text":50,"core/visuals/hatch":51,"core/visuals/patterns":52,"model":53,"models/canvas/coordinates":54,"models/annotations/arrow":55,"models/annotations/data_annotation":56,"models/sources/columnar_data_source":57,"models/sources/data_source":58,"models/selections/selection":59,"core/selection_manager":60,"models/renderers/glyph_renderer":61,"models/renderers/data_renderer":62,"models/glyphs/line":63,"models/glyphs/xy_glyph":64,"core/util/projections":65,"models/glyphs/glyph":98,"core/util/bbox":99,"core/util/ragged_array":100,"core/util/spatial":101,"models/ranges/factor_range":104,"models/ranges/range":105,"models/glyphs/utils":106,"core/hittest":107,"models/glyphs/webgl/line":108,"models/glyphs/webgl/utils/index":109,"models/glyphs/webgl/utils/program":110,"models/glyphs/webgl/utils/buffer":111,"models/glyphs/webgl/utils/texture":112,"models/glyphs/webgl/base":113,"models/glyphs/webgl/line.vert":114,"models/glyphs/webgl/line.frag":115,"models/glyphs/patch":116,"models/glyphs/harea":117,"models/glyphs/area":118,"models/glyphs/varea":119,"models/sources/cds_view":120,"models/filters/filter":121,"core/build_views":122,"models/renderers/graph_renderer":123,"models/expressions/expression":124,"models/graphs/layout_provider":125,"models/graphs/graph_hit_test_policy":126,"models/glyphs/multi_line":127,"models/glyphs/patches":128,"models/selections/interaction_policy":129,"models/sources/column_data_source":130,"core/util/typed_array":131,"core/util/set":132,"models/annotations/arrow_head":133,"models/annotations/band":134,"models/annotations/upper_lower":135,"models/annotations/box_annotation":136,"models/annotations/color_bar":137,"models/annotations/title":138,"models/annotations/text_annotation":139,"core/layout/side_panel":140,"core/layout/types":141,"core/layout/layoutable":142,"core/util/text":143,"models/canvas/cartesian_frame":144,"models/scales/categorical_scale":145,"models/scales/scale":146,"models/transforms/index":147,"models/transforms/customjs_transform":148,"models/transforms/transform":149,"models/transforms/dodge":150,"models/transforms/range_transform":151,"models/transforms/interpolator":152,"models/transforms/jitter":153,"models/transforms/linear_interpolator":154,"models/transforms/step_interpolator":155,"models/ranges/range1d":156,"models/scales/log_scale":157,"models/scales/continuous_scale":158,"models/ranges/data_range1d":159,"models/ranges/data_range":160,"models/util":161,"models/axes/index":162,"models/axes/axis":163,"models/renderers/guide_renderer":164,"models/tickers/ticker":165,"models/formatters/tick_formatter":166,"core/graphics":167,"core/util/affine":168,"models/policies/labeling":169,"models/axes/categorical_axis":170,"models/tickers/categorical_ticker":171,"models/formatters/categorical_tick_formatter":172,"models/axes/continuous_axis":173,"models/axes/datetime_axis":174,"models/axes/linear_axis":175,"models/formatters/basic_tick_formatter":176,"models/tickers/basic_ticker":177,"models/tickers/adaptive_ticker":178,"models/tickers/continuous_ticker":179,"models/formatters/datetime_tick_formatter":180,"core/util/templating":182,"models/tickers/datetime_ticker":185,"models/tickers/composite_ticker":186,"models/tickers/days_ticker":187,"models/tickers/single_interval_ticker":188,"models/tickers/util":189,"models/tickers/months_ticker":190,"models/tickers/years_ticker":191,"models/axes/log_axis":192,"models/formatters/log_tick_formatter":193,"models/tickers/log_ticker":194,"models/axes/mercator_axis":195,"models/formatters/mercator_tick_formatter":196,"models/tickers/mercator_ticker":197,"models/tickers/index":198,"models/tickers/fixed_ticker":199,"models/tickers/binned_ticker":200,"models/mappers/scanning_color_mapper":201,"models/mappers/continuous_color_mapper":202,"models/mappers/color_mapper":203,"models/mappers/mapper":204,"models/formatters/index":205,"models/formatters/func_tick_formatter":206,"models/formatters/numeral_tick_formatter":207,"models/formatters/printf_tick_formatter":208,"models/mappers/index":209,"models/mappers/categorical_color_mapper":210,"models/mappers/categorical_mapper":211,"models/mappers/categorical_marker_mapper":212,"models/mappers/categorical_pattern_mapper":213,"models/mappers/linear_color_mapper":214,"models/mappers/log_color_mapper":215,"models/mappers/eqhist_color_mapper":216,"models/scales/index":217,"models/scales/linear_scale":218,"models/scales/linear_interpolation_scale":219,"models/ranges/index":220,"core/layout/index":221,"core/layout/alignments":222,"core/layout/grid":223,"core/layout/html":224,"core/layout/border":225,"models/annotations/label":226,"models/annotations/label_set":227,"models/annotations/legend":228,"models/annotations/legend_item":229,"core/vectorization":230,"models/annotations/poly_annotation":231,"models/annotations/slope":232,"models/annotations/span":233,"models/annotations/toolbar_panel":234,"models/tools/toolbar":235,"models/tools/tool":236,"models/tools/gestures/gesture_tool":237,"models/tools/button_tool":238,"core/dom_view":240,"styles/toolbar.css":241,"styles/icons.css":242,"styles/menus.css":243,"core/util/menus":244,"core/util/iterator":245,"models/tools/on_off_button":246,"models/tools/inspectors/inspect_tool":247,"models/tools/toolbar_base":248,"core/util/canvas":249,"core/util/svg":250,"models/tools/actions/action_tool":251,"models/tools/actions/help_tool":252,"styles/logo.css":253,"models/annotations/tooltip":254,"styles/tooltips.css":255,"models/annotations/whisker":256,"models/callbacks/index":257,"models/callbacks/customjs":258,"models/callbacks/callback":259,"models/callbacks/open_url":260,"models/canvas/index":261,"models/canvas/canvas":262,"core/ui_events":263,"core/bokeh_events":264,"core/util/wheel":265,"models/expressions/index":266,"models/expressions/customjs_expr":267,"models/expressions/stack":268,"models/expressions/cumsum":269,"models/expressions/minimum":270,"models/expressions/maximum":271,"models/filters/index":272,"models/filters/boolean_filter":273,"models/filters/customjs_filter":274,"models/filters/group_filter":275,"models/filters/index_filter":276,"models/glyphs/index":277,"models/glyphs/annular_wedge":278,"models/glyphs/annulus":279,"models/glyphs/arc":280,"models/glyphs/bezier":281,"models/glyphs/circle":282,"models/glyphs/webgl/markers":283,"models/glyphs/webgl/markers.vert":284,"models/glyphs/webgl/markers.frag":285,"models/glyphs/ellipse":286,"models/glyphs/ellipse_oval":287,"models/glyphs/center_rotatable":288,"models/glyphs/hbar":289,"models/glyphs/box":290,"models/glyphs/hex_tile":291,"models/glyphs/image":292,"models/glyphs/image_base":293,"models/glyphs/image_rgba":294,"models/glyphs/image_url":295,"core/util/image":296,"models/glyphs/multi_polygons":297,"models/glyphs/oval":298,"models/glyphs/quad":299,"models/glyphs/quadratic":300,"models/glyphs/ray":301,"models/glyphs/rect":302,"models/glyphs/scatter":303,"models/glyphs/marker":304,"models/glyphs/defs":305,"models/glyphs/segment":306,"models/glyphs/spline":307,"core/util/interpolation":308,"models/glyphs/step":309,"models/glyphs/text":310,"models/glyphs/vbar":311,"models/glyphs/wedge":312,"models/graphs/index":313,"models/graphs/static_layout_provider":314,"models/grids/index":315,"models/grids/grid":316,"models/layouts/index":317,"models/layouts/box":318,"models/layouts/layout_dom":319,"models/layouts/column":320,"models/layouts/grid_box":321,"models/layouts/html_box":322,"models/layouts/panel":323,"models/layouts/row":324,"models/layouts/spacer":325,"models/layouts/tabs":326,"styles/tabs.css":327,"styles/buttons.css":328,"models/layouts/widget_box":329,"models/plots/index":330,"models/plots/gmap_plot":331,"models/plots/plot":332,"models/plots/plot_canvas":333,"core/util/throttle":334,"models/plots/range_manager":335,"models/plots/state_manager":336,"models/plots/gmap_plot_canvas":337,"models/policies/index":338,"models/renderers/index":339,"models/selections/index":340,"models/sources/index":341,"models/sources/server_sent_data_source":342,"models/sources/web_data_source":343,"models/sources/ajax_data_source":344,"models/sources/geojson_data_source":345,"models/tiles/index":346,"models/tiles/bbox_tile_source":347,"models/tiles/mercator_tile_source":348,"models/tiles/tile_source":349,"models/tiles/tile_utils":350,"models/tiles/quadkey_tile_source":351,"models/tiles/tile_renderer":352,"models/tiles/wmts_tile_source":353,"styles/tiles.css":354,"models/tiles/tms_tile_source":355,"models/textures/index":356,"models/textures/canvas_texture":357,"models/textures/texture":358,"models/textures/image_url_texture":359,"models/tools/index":360,"models/tools/actions/custom_action":361,"models/tools/actions/redo_tool":362,"models/tools/actions/reset_tool":363,"models/tools/actions/save_tool":364,"models/tools/actions/undo_tool":365,"models/tools/actions/zoom_in_tool":366,"models/tools/actions/zoom_base_tool":367,"core/util/zoom":368,"models/tools/actions/zoom_out_tool":369,"models/tools/edit/edit_tool":370,"models/tools/edit/box_edit_tool":371,"models/tools/edit/freehand_draw_tool":372,"models/tools/edit/point_draw_tool":373,"models/tools/edit/poly_draw_tool":374,"models/tools/edit/poly_tool":375,"models/tools/edit/poly_edit_tool":376,"models/tools/gestures/box_select_tool":377,"models/tools/gestures/select_tool":378,"models/tools/gestures/box_zoom_tool":379,"models/tools/gestures/lasso_select_tool":380,"models/tools/gestures/poly_select_tool":381,"models/tools/edit/line_edit_tool":382,"models/tools/edit/line_tool":383,"models/tools/gestures/pan_tool":384,"models/tools/gestures/range_tool":385,"models/tools/gestures/tap_tool":386,"models/tools/gestures/wheel_pan_tool":387,"models/tools/gestures/wheel_zoom_tool":388,"models/tools/inspectors/crosshair_tool":389,"models/tools/inspectors/customjs_hover":390,"models/tools/inspectors/hover_tool":391,"models/tools/tool_proxy":392,"models/tools/toolbar_box":393,"document/defs":394,"embed/standalone":395,"embed/dom":396,"embed/server":397,"client/connection":398,"protocol/message":399,"protocol/receiver":400,"client/session":401,"embed/notebook":402,"styles/notebook.css":403,"protocol/index":404,"testing":405,"safely":406}, {});export default main;
//# sourceMappingURL=bokeh.esm.js.map
